usergroup.lib.php 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class UserGroup.
  5. *
  6. * This class provides methods for the UserGroup management.
  7. * Include/require it in your code to use its features.
  8. *
  9. * @package chamilo.library
  10. */
  11. class UserGroup extends Model
  12. {
  13. const SOCIAL_CLASS = 1;
  14. const NORMAL_CLASS = 0;
  15. public $columns = [
  16. 'id',
  17. 'name',
  18. 'description',
  19. 'group_type',
  20. 'picture',
  21. 'url',
  22. 'allow_members_leave_group',
  23. 'visibility',
  24. 'updated_at',
  25. 'created_at',
  26. ];
  27. public $useMultipleUrl = false;
  28. public $groupType = 0;
  29. public $showGroupTypeSetting = false;
  30. public $usergroup_rel_user_table;
  31. public $usergroup_rel_course_table;
  32. public $usergroup_rel_session_table;
  33. public $access_url_rel_usergroup;
  34. public $access_url_rel_user;
  35. public $table_course;
  36. public $table_user;
  37. /**
  38. * Set ups DB tables.
  39. */
  40. public function __construct()
  41. {
  42. parent::__construct();
  43. $this->table = Database::get_main_table(TABLE_USERGROUP);
  44. $this->usergroup_rel_user_table = Database::get_main_table(TABLE_USERGROUP_REL_USER);
  45. $this->usergroup_rel_course_table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
  46. $this->usergroup_rel_session_table = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
  47. $this->access_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
  48. $this->access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  49. $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  50. $this->table_user = Database::get_main_table(TABLE_MAIN_USER);
  51. $this->useMultipleUrl = api_get_configuration_value('multiple_access_urls');
  52. if ($this->allowTeachers()) {
  53. $this->columns[] = 'author_id';
  54. }
  55. }
  56. /**
  57. * @return bool
  58. */
  59. public function getUseMultipleUrl()
  60. {
  61. return $this->useMultipleUrl;
  62. }
  63. /**
  64. * @return int
  65. */
  66. public function getTotalCount()
  67. {
  68. $options = [];
  69. $from = $this->table;
  70. if ($this->getUseMultipleUrl()) {
  71. $urlId = api_get_current_access_url_id();
  72. $options = [
  73. 'where' => [
  74. 'access_url_id = ?' => [
  75. $urlId,
  76. ],
  77. ],
  78. ];
  79. $from = " $this->table u
  80. INNER JOIN $this->access_url_rel_usergroup a
  81. ON (u.id = a.usergroup_id) ";
  82. }
  83. $row = Database::select('count(*) as count', $from, $options, 'first');
  84. return $row['count'];
  85. }
  86. /**
  87. * @param int $id user group id
  88. * @param bool $getCount
  89. *
  90. * @return array|int
  91. */
  92. public function getUserGroupUsers($id, $getCount = false)
  93. {
  94. $id = (int) $id;
  95. $select = ' u.* ';
  96. if ($getCount) {
  97. $select = 'COUNT(u.id) count ';
  98. }
  99. if ($this->getUseMultipleUrl()) {
  100. $urlId = api_get_current_access_url_id();
  101. $sql = "SELECT $select
  102. FROM $this->usergroup_rel_user_table u
  103. INNER JOIN $this->access_url_rel_user a
  104. ON (u.user_id = a.user_id)
  105. WHERE u.usergroup_id = $id AND access_url_id = $urlId ";
  106. } else {
  107. $sql = "SELECT $select
  108. FROM $this->usergroup_rel_user_table u
  109. WHERE u.usergroup_id = $id";
  110. }
  111. $result = Database::query($sql);
  112. if ($getCount) {
  113. if (Database::num_rows($result)) {
  114. $row = Database::fetch_array($result);
  115. return $row['count'];
  116. }
  117. return 0;
  118. } else {
  119. $list = [];
  120. $showCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  121. $calendarPlugin = null;
  122. if ($showCalendar) {
  123. $calendarPlugin = LearningCalendarPlugin::create();
  124. }
  125. $url = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/calendar.php?';
  126. while ($data = Database::fetch_array($result)) {
  127. $userId = $data['user_id'];
  128. $userInfo = api_get_user_info($userId);
  129. $data['name'] = $userInfo['complete_name_with_username'];
  130. if ($showCalendar) {
  131. $calendar = $calendarPlugin->getUserCalendar($userId);
  132. $data['calendar_id'] = 0;
  133. $data['calendar'] = '';
  134. if (!empty($calendar)) {
  135. $calendarInfo = $calendarPlugin->getCalendar($calendar['calendar_id']);
  136. if ($calendarInfo) {
  137. $data['calendar_id'] = $calendar['calendar_id'];
  138. $data['calendar'] = Display::url(
  139. $calendarInfo['title'],
  140. $url.'&id='.$calendar['calendar_id']
  141. );
  142. }
  143. }
  144. $courseAndSessionList = Tracking::show_user_progress(
  145. $userId,
  146. 0,
  147. '',
  148. true,
  149. true,
  150. true
  151. );
  152. $stats = $calendarPlugin->getUserStats($userId, $courseAndSessionList);
  153. $evaluations = $calendarPlugin->getGradebookEvaluationListToString($userId, $courseAndSessionList);
  154. $data['gradebook_items'] = $evaluations;
  155. $totalTime = 0;
  156. foreach ($courseAndSessionList as $sessionId => $course) {
  157. foreach ($course as $courseId) {
  158. $totalTime += Tracking::get_time_spent_on_the_course($userId, $courseId, $sessionId);
  159. }
  160. }
  161. $data['time_spent'] = api_time_to_hms($totalTime);
  162. $data['lp_day_completed'] = $stats['completed'];
  163. $data['days_diff'] = $stats['completed'] - $stats['user_event_count'];
  164. }
  165. $data['id'] = $data['user_id'];
  166. $list[] = $data;
  167. }
  168. return $list;
  169. }
  170. }
  171. /**
  172. * @param int $type
  173. *
  174. * @return int
  175. */
  176. public function get_count()
  177. {
  178. $authorCondition = '';
  179. if ($this->allowTeachers()) {
  180. if (!api_is_platform_admin()) {
  181. $userId = api_get_user_id();
  182. $authorCondition = " AND author_id = $userId";
  183. }
  184. }
  185. if ($this->getUseMultipleUrl()) {
  186. $urlId = api_get_current_access_url_id();
  187. $sql = "SELECT count(u.id) as count
  188. FROM $this->table u
  189. INNER JOIN $this->access_url_rel_usergroup a
  190. ON (u.id = a.usergroup_id)
  191. WHERE access_url_id = $urlId $authorCondition
  192. ";
  193. $result = Database::query($sql);
  194. if (Database::num_rows($result)) {
  195. $row = Database::fetch_array($result);
  196. return $row['count'];
  197. }
  198. } else {
  199. $sql = "SELECT count(a.id) as count
  200. FROM {$this->table} a
  201. WHERE 1 = 1
  202. $authorCondition
  203. ";
  204. $result = Database::query($sql);
  205. if (Database::num_rows($result)) {
  206. $row = Database::fetch_array($result);
  207. return $row['count'];
  208. }
  209. }
  210. return 0;
  211. }
  212. /**
  213. * @param string $name
  214. *
  215. * @return mixed
  216. */
  217. public function getIdByName($name)
  218. {
  219. $row = Database::select(
  220. 'id',
  221. $this->table,
  222. ['where' => ['name = ?' => $name]],
  223. 'first'
  224. );
  225. return $row['id'];
  226. }
  227. /**
  228. * Displays the title + grid.
  229. */
  230. public function returnGrid()
  231. {
  232. // action links
  233. $html = '<div class="actions">';
  234. if (api_is_platform_admin()) {
  235. $html .= '<a href="../admin/index.php">'.
  236. Display::return_icon(
  237. 'back.png',
  238. get_lang('Back to').' '.get_lang('Administration'),
  239. '',
  240. ICON_SIZE_MEDIUM
  241. ).
  242. '</a>';
  243. }
  244. $html .= '<a href="'.api_get_self().'?action=add">'.
  245. Display::return_icon('new_class.png', get_lang('Add classes'), '', ICON_SIZE_MEDIUM).
  246. '</a>';
  247. $html .= Display::url(
  248. Display::return_icon('import_csv.png', get_lang('Import'), [], ICON_SIZE_MEDIUM),
  249. 'usergroup_import.php'
  250. );
  251. $html .= Display::url(
  252. Display::return_icon('export_csv.png', get_lang('Export'), [], ICON_SIZE_MEDIUM),
  253. 'usergroup_export.php'
  254. );
  255. $html .= '</div>';
  256. $html .= Display::grid_html('usergroups');
  257. return $html;
  258. }
  259. /**
  260. * Displays the title + grid.
  261. */
  262. public function displayToolBarUserGroupUsers()
  263. {
  264. // action links
  265. echo '<div class="actions">';
  266. $courseInfo = api_get_course_info();
  267. if (empty($courseInfo)) {
  268. echo '<a href="../admin/usergroups.php">'.
  269. Display::return_icon('back.png', get_lang('Back to').' '.get_lang('Administration'), '', '32').
  270. '</a>';
  271. } else {
  272. echo Display::url(
  273. Display::return_icon('back.png', get_lang('Back to').' '.get_lang('Administration'), '', '32'),
  274. api_get_path(WEB_CODE_PATH).'user/class.php?'.api_get_cidreq()
  275. );
  276. }
  277. echo '</div>';
  278. echo Display::grid_html('usergroups');
  279. }
  280. /**
  281. * Get HTML grid.
  282. */
  283. public function display_teacher_view()
  284. {
  285. echo Display::grid_html('usergroups');
  286. }
  287. /**
  288. * Gets a list of course ids by user group.
  289. *
  290. * @param int $id user group id
  291. * @param bool $loadCourseData
  292. *
  293. * @return array
  294. */
  295. public function get_courses_by_usergroup($id, $loadCourseData = false)
  296. {
  297. if ($this->getUseMultipleUrl()) {
  298. $urlId = api_get_current_access_url_id();
  299. $from = $this->usergroup_rel_course_table." c
  300. INNER JOIN {$this->access_url_rel_usergroup} a
  301. ON (a.usergroup_id = c.usergroup_id) ";
  302. $whereConditionSql = 'a.usergroup_id = ? AND access_url_id = ? ';
  303. $whereConditionValues = [$id, $urlId];
  304. } else {
  305. $whereConditionSql = 'usergroup_id = ?';
  306. $whereConditionValues = [$id];
  307. $from = $this->usergroup_rel_course_table.' c ';
  308. }
  309. if ($loadCourseData) {
  310. $from .= " INNER JOIN {$this->table_course} as course ON c.course_id = course.id";
  311. }
  312. $where = ['where' => [$whereConditionSql => $whereConditionValues]];
  313. $select = 'course_id';
  314. if ($loadCourseData) {
  315. $select = 'course.*';
  316. }
  317. $results = Database::select(
  318. $select,
  319. $from,
  320. $where
  321. );
  322. $array = [];
  323. if (!empty($results)) {
  324. foreach ($results as $row) {
  325. if ($loadCourseData) {
  326. $array[$row['id']] = $row;
  327. } else {
  328. $array[] = $row['course_id'];
  329. }
  330. }
  331. }
  332. return $array;
  333. }
  334. /**
  335. * @param array $options
  336. * @param int $type
  337. *
  338. * @return array
  339. */
  340. public function getUserGroupInCourse($options = [], $type = -1, $getCount = false)
  341. {
  342. $select = 'DISTINCT u.*';
  343. if ($getCount) {
  344. $select = 'count(u.id) as count';
  345. }
  346. if ($this->getUseMultipleURL()) {
  347. $sql = "SELECT $select
  348. FROM {$this->usergroup_rel_course_table} usergroup
  349. INNER JOIN {$this->table} u
  350. ON (u.id = usergroup.usergroup_id)
  351. INNER JOIN {$this->table_course} c
  352. ON (usergroup.course_id = c.id)
  353. INNER JOIN {$this->access_url_rel_usergroup} a
  354. ON (a.usergroup_id = u.id)
  355. ";
  356. } else {
  357. $sql = "SELECT $select
  358. FROM {$this->usergroup_rel_course_table} usergroup
  359. INNER JOIN {$this->table} u
  360. ON (u.id = usergroup.usergroup_id)
  361. INNER JOIN {$this->table_course} c
  362. ON (usergroup.course_id = c.id)
  363. ";
  364. }
  365. if ($type != -1) {
  366. $type = (int) $type;
  367. $options['where']['AND group_type = ? '] = $type;
  368. }
  369. if ($this->getUseMultipleUrl()) {
  370. $urlId = api_get_current_access_url_id();
  371. $options['where']['AND access_url_id = ? '] = $urlId;
  372. }
  373. $conditions = Database::parse_conditions($options);
  374. $sql .= $conditions;
  375. $result = Database::query($sql);
  376. if ($getCount) {
  377. if (Database::num_rows($result)) {
  378. $row = Database::fetch_array($result);
  379. return $row['count'];
  380. }
  381. }
  382. $array = Database::store_result($result, 'ASSOC');
  383. return $array;
  384. }
  385. /**
  386. * @param array $options
  387. * @param int $type
  388. * @param bool $getCount
  389. *
  390. * @return array|bool
  391. */
  392. public function getUserGroupNotInCourse($options = [], $type = -1, $getCount = false)
  393. {
  394. $course_id = null;
  395. if (isset($options['course_id'])) {
  396. $course_id = (int) $options['course_id'];
  397. unset($options['course_id']);
  398. }
  399. if (empty($course_id)) {
  400. return false;
  401. }
  402. $select = 'DISTINCT u.*';
  403. if ($getCount) {
  404. $select = 'count(u.id) as count';
  405. }
  406. if ($this->getUseMultipleUrl()) {
  407. $sql = "SELECT $select
  408. FROM {$this->table} u
  409. INNER JOIN {$this->access_url_rel_usergroup} a
  410. ON (a.usergroup_id = u.id)
  411. LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
  412. ON (u.id = urc.usergroup_id AND course_id = $course_id)
  413. ";
  414. } else {
  415. $sql = "SELECT $select
  416. FROM {$this->table} u
  417. LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
  418. ON (u.id = urc.usergroup_id AND course_id = $course_id)
  419. ";
  420. }
  421. if ($type != -1) {
  422. $type = (int) $type;
  423. $options['where']['AND group_type = ? '] = $type;
  424. }
  425. if ($this->getUseMultipleUrl()) {
  426. $urlId = api_get_current_access_url_id();
  427. $options['where']['AND access_url_id = ? '] = $urlId;
  428. }
  429. /*if ($this->allowTeachers()) {
  430. if (!api_is_platform_admin()) {
  431. $userId = api_get_user_id();
  432. $options['where']['AND author_id = ? '] = $userId;
  433. }
  434. }*/
  435. $conditions = Database::parse_conditions($options);
  436. $sql .= $conditions;
  437. if ($getCount) {
  438. $result = Database::query($sql);
  439. $array = Database::fetch_array($result, 'ASSOC');
  440. return $array['count'];
  441. }
  442. $result = Database::query($sql);
  443. $array = Database::store_result($result, 'ASSOC');
  444. return $array;
  445. }
  446. /**
  447. * @param int $course_id
  448. *
  449. * @deprecated ?
  450. *
  451. * @return array
  452. */
  453. public function get_usergroup_by_course($course_id)
  454. {
  455. if ($this->getUseMultipleUrl()) {
  456. $urlId = api_get_current_access_url_id();
  457. $options = [
  458. 'where' => [
  459. 'c.course_id = ? AND access_url_id = ?' => [
  460. $course_id,
  461. $urlId,
  462. ],
  463. ],
  464. ];
  465. $from = " $this->usergroup_rel_course_table as c
  466. INNER JOIN $this->access_url_rel_usergroup a
  467. ON c.usergroup_id = a.usergroup_id ";
  468. } else {
  469. $options = ['where' => ['c.course_id = ?' => $course_id]];
  470. $from = $this->usergroup_rel_course_table." c";
  471. }
  472. $results = Database::select('c.usergroup_id', $from, $options);
  473. $array = [];
  474. if (!empty($results)) {
  475. foreach ($results as $row) {
  476. $array[] = $row['usergroup_id'];
  477. }
  478. }
  479. return $array;
  480. }
  481. /**
  482. * @param int $usergroup_id
  483. * @param int $course_id
  484. *
  485. * @return bool
  486. */
  487. public function usergroup_was_added_in_course($usergroup_id, $course_id)
  488. {
  489. $results = Database::select(
  490. 'usergroup_id',
  491. $this->usergroup_rel_course_table,
  492. ['where' => ['course_id = ? AND usergroup_id = ?' => [$course_id, $usergroup_id]]]
  493. );
  494. if (empty($results)) {
  495. return false;
  496. }
  497. return true;
  498. }
  499. /**
  500. * Gets a list of session ids by user group.
  501. *
  502. * @param int $id group id
  503. *
  504. * @return array
  505. */
  506. public function get_sessions_by_usergroup($id)
  507. {
  508. $results = Database::select(
  509. 'session_id',
  510. $this->usergroup_rel_session_table,
  511. ['where' => ['usergroup_id = ?' => $id]]
  512. );
  513. $array = [];
  514. if (!empty($results)) {
  515. foreach ($results as $row) {
  516. $array[] = $row['session_id'];
  517. }
  518. }
  519. return $array;
  520. }
  521. /**
  522. * Gets a list of user ids by user group.
  523. *
  524. * @param int $id user group id
  525. * @param array $roles
  526. *
  527. * @return array with a list of user ids
  528. */
  529. public function get_users_by_usergroup($id = null, $roles = [])
  530. {
  531. $relationCondition = '';
  532. if (!empty($roles)) {
  533. $relationConditionArray = [];
  534. foreach ($roles as $relation) {
  535. $relation = (int) $relation;
  536. if (empty($relation)) {
  537. $relationConditionArray[] = " (relation_type = 0 OR relation_type IS NULL OR relation_type = '') ";
  538. } else {
  539. $relationConditionArray[] = " relation_type = $relation ";
  540. }
  541. }
  542. $relationCondition = ' AND ( ';
  543. $relationCondition .= implode('OR', $relationConditionArray);
  544. $relationCondition .= ' ) ';
  545. }
  546. if (empty($id)) {
  547. $conditions = [];
  548. } else {
  549. $conditions = ['where' => ["usergroup_id = ? $relationCondition " => $id]];
  550. }
  551. $results = Database::select(
  552. 'user_id',
  553. $this->usergroup_rel_user_table,
  554. $conditions
  555. );
  556. $array = [];
  557. if (!empty($results)) {
  558. foreach ($results as $row) {
  559. $array[] = $row['user_id'];
  560. }
  561. }
  562. return $array;
  563. }
  564. /**
  565. * Gets a list of user ids by user group.
  566. *
  567. * @param int $id user group id
  568. * @param int $relation
  569. *
  570. * @return array with a list of user ids
  571. */
  572. public function getUsersByUsergroupAndRelation($id, $relation = 0)
  573. {
  574. $relation = (int) $relation;
  575. if (empty($relation)) {
  576. $conditions = ['where' => ['usergroup_id = ? AND (relation_type = 0 OR relation_type IS NULL OR relation_type = "") ' => [$id]]];
  577. } else {
  578. $conditions = ['where' => ['usergroup_id = ? AND relation_type = ?' => [$id, $relation]]];
  579. }
  580. $results = Database::select(
  581. 'user_id',
  582. $this->usergroup_rel_user_table,
  583. $conditions
  584. );
  585. $array = [];
  586. if (!empty($results)) {
  587. foreach ($results as $row) {
  588. $array[] = $row['user_id'];
  589. }
  590. }
  591. return $array;
  592. }
  593. /**
  594. * Get the group list for a user.
  595. *
  596. * @param int $userId The user ID
  597. * @param int $filterByType Optional. The type of group
  598. *
  599. * @return array
  600. */
  601. public function getUserGroupListByUser($userId, $filterByType = null)
  602. {
  603. $userId = (int) $userId;
  604. if ($this->getUseMultipleUrl()) {
  605. $urlId = api_get_current_access_url_id();
  606. $from = $this->usergroup_rel_user_table." u
  607. INNER JOIN {$this->access_url_rel_usergroup} a
  608. ON (a.usergroup_id AND u.usergroup_id)
  609. INNER JOIN {$this->table} g
  610. ON (u.usergroup_id = g.id)
  611. ";
  612. $where = ['where' => ['user_id = ? AND access_url_id = ? ' => [$userId, $urlId]]];
  613. } else {
  614. $from = $this->usergroup_rel_user_table." u
  615. INNER JOIN {$this->table} g
  616. ON (u.usergroup_id = g.id)
  617. ";
  618. $where = ['where' => ['user_id = ?' => $userId]];
  619. }
  620. if ($filterByType !== null) {
  621. $where['where'][' AND g.group_type = ?'] = (int) $filterByType;
  622. }
  623. $results = Database::select(
  624. 'g.*',
  625. $from,
  626. $where
  627. );
  628. $array = [];
  629. if (!empty($results)) {
  630. foreach ($results as $row) {
  631. $array[] = $row;
  632. }
  633. }
  634. return $array;
  635. }
  636. /**
  637. * Gets the usergroup id list by user id.
  638. *
  639. * @param int $userId user id
  640. *
  641. * @return array
  642. */
  643. public function get_usergroup_by_user($userId)
  644. {
  645. $userId = (int) $userId;
  646. if ($this->getUseMultipleUrl()) {
  647. $urlId = api_get_current_access_url_id();
  648. $from = $this->usergroup_rel_user_table." u
  649. INNER JOIN {$this->access_url_rel_usergroup} a
  650. ON (a.usergroup_id = u.usergroup_id) ";
  651. $where = ['where' => ['user_id = ? AND access_url_id = ? ' => [$userId, $urlId]]];
  652. } else {
  653. $from = $this->usergroup_rel_user_table.' u ';
  654. $where = ['where' => ['user_id = ?' => $userId]];
  655. }
  656. $results = Database::select(
  657. 'u.usergroup_id',
  658. $from,
  659. $where
  660. );
  661. $array = [];
  662. if (!empty($results)) {
  663. foreach ($results as $row) {
  664. $array[] = $row['usergroup_id'];
  665. }
  666. }
  667. return $array;
  668. }
  669. /**
  670. * Subscribes sessions to a group (also adding the members of the group in the session and course).
  671. *
  672. * @param int $usergroup_id usergroup id
  673. * @param array $list list of session ids
  674. * @param bool $deleteCurrentSessions Optional. Empty the session list for the usergroup (class)
  675. */
  676. public function subscribe_sessions_to_usergroup($usergroup_id, $list, $deleteCurrentSessions = true)
  677. {
  678. $current_list = $this->get_sessions_by_usergroup($usergroup_id);
  679. $user_list = $this->get_users_by_usergroup($usergroup_id);
  680. $delete_items = $new_items = [];
  681. if (!empty($list)) {
  682. foreach ($list as $session_id) {
  683. if (!in_array($session_id, $current_list)) {
  684. $new_items[] = $session_id;
  685. }
  686. }
  687. }
  688. if ($deleteCurrentSessions) {
  689. if (!empty($current_list)) {
  690. foreach ($current_list as $session_id) {
  691. if (!in_array($session_id, $list)) {
  692. $delete_items[] = $session_id;
  693. }
  694. }
  695. }
  696. // Deleting items
  697. if (!empty($delete_items)) {
  698. foreach ($delete_items as $session_id) {
  699. if (!empty($user_list)) {
  700. foreach ($user_list as $user_id) {
  701. SessionManager::unsubscribe_user_from_session($session_id, $user_id);
  702. }
  703. }
  704. Database::delete(
  705. $this->usergroup_rel_session_table,
  706. ['usergroup_id = ? AND session_id = ?' => [$usergroup_id, $session_id]]
  707. );
  708. }
  709. }
  710. }
  711. // Adding new relationships.
  712. if (!empty($new_items)) {
  713. foreach ($new_items as $session_id) {
  714. $params = ['session_id' => $session_id, 'usergroup_id' => $usergroup_id];
  715. Database::insert($this->usergroup_rel_session_table, $params);
  716. if (!empty($user_list)) {
  717. SessionManager::subscribeUsersToSession(
  718. $session_id,
  719. $user_list,
  720. null,
  721. false
  722. );
  723. }
  724. }
  725. }
  726. }
  727. /**
  728. * Subscribes courses to a group (also adding the members of the group in the course).
  729. *
  730. * @param int $usergroup_id usergroup id
  731. * @param array $list list of course ids (integers)
  732. * @param bool $delete_groups
  733. */
  734. public function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
  735. {
  736. $current_list = $this->get_courses_by_usergroup($usergroup_id);
  737. $user_list = $this->get_users_by_usergroup($usergroup_id);
  738. $delete_items = $new_items = [];
  739. if (!empty($list)) {
  740. foreach ($list as $id) {
  741. if (!in_array($id, $current_list)) {
  742. $new_items[] = $id;
  743. }
  744. }
  745. }
  746. if (!empty($current_list)) {
  747. foreach ($current_list as $id) {
  748. if (!in_array($id, $list)) {
  749. $delete_items[] = $id;
  750. }
  751. }
  752. }
  753. if ($delete_groups) {
  754. $this->unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
  755. }
  756. // Adding new relationships
  757. if (!empty($new_items)) {
  758. foreach ($new_items as $course_id) {
  759. $course_info = api_get_course_info_by_id($course_id);
  760. if ($course_info) {
  761. if (!empty($user_list)) {
  762. foreach ($user_list as $user_id) {
  763. CourseManager::subscribeUser(
  764. $user_id,
  765. $course_info['code']
  766. );
  767. }
  768. }
  769. $params = [
  770. 'course_id' => $course_id,
  771. 'usergroup_id' => $usergroup_id,
  772. ];
  773. Database::insert(
  774. $this->usergroup_rel_course_table,
  775. $params
  776. );
  777. }
  778. }
  779. }
  780. }
  781. /**
  782. * @param int $usergroup_id
  783. * @param array $delete_items
  784. */
  785. public function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
  786. {
  787. // Deleting items.
  788. if (!empty($delete_items)) {
  789. $user_list = $this->get_users_by_usergroup($usergroup_id);
  790. foreach ($delete_items as $course_id) {
  791. $course_info = api_get_course_info_by_id($course_id);
  792. if ($course_info) {
  793. if (!empty($user_list)) {
  794. foreach ($user_list as $user_id) {
  795. CourseManager::unsubscribe_user(
  796. $user_id,
  797. $course_info['code']
  798. );
  799. }
  800. }
  801. Database::delete(
  802. $this->usergroup_rel_course_table,
  803. [
  804. 'usergroup_id = ? AND course_id = ?' => [
  805. $usergroup_id,
  806. $course_id,
  807. ],
  808. ]
  809. );
  810. }
  811. }
  812. }
  813. }
  814. /**
  815. * Subscribe users to a group.
  816. *
  817. * @param int $usergroup_id usergroup id
  818. * @param array $list list of user ids
  819. * @param bool $delete_users_not_present_in_list
  820. * @param int $relationType
  821. */
  822. public function subscribe_users_to_usergroup(
  823. $usergroup_id,
  824. $list,
  825. $delete_users_not_present_in_list = true,
  826. $relationType = 0
  827. ) {
  828. $current_list = $this->get_users_by_usergroup($usergroup_id);
  829. $course_list = $this->get_courses_by_usergroup($usergroup_id);
  830. $session_list = $this->get_sessions_by_usergroup($usergroup_id);
  831. $session_list = array_filter($session_list);
  832. $relationType = (int) $relationType;
  833. $delete_items = [];
  834. $new_items = [];
  835. if (!empty($list)) {
  836. foreach ($list as $user_id) {
  837. if (!in_array($user_id, $current_list)) {
  838. $new_items[] = $user_id;
  839. }
  840. }
  841. }
  842. if (!empty($current_list)) {
  843. foreach ($current_list as $user_id) {
  844. if (!in_array($user_id, $list)) {
  845. $delete_items[] = $user_id;
  846. }
  847. }
  848. }
  849. // Deleting items
  850. if (!empty($delete_items) && $delete_users_not_present_in_list) {
  851. foreach ($delete_items as $user_id) {
  852. // Removing courses
  853. if (!empty($course_list)) {
  854. foreach ($course_list as $course_id) {
  855. $course_info = api_get_course_info_by_id($course_id);
  856. CourseManager::unsubscribe_user($user_id, $course_info['code']);
  857. }
  858. }
  859. // Removing sessions
  860. if (!empty($session_list)) {
  861. foreach ($session_list as $session_id) {
  862. SessionManager::unsubscribe_user_from_session($session_id, $user_id);
  863. }
  864. }
  865. if (empty($relationType)) {
  866. Database::delete(
  867. $this->usergroup_rel_user_table,
  868. [
  869. 'usergroup_id = ? AND user_id = ? AND (relation_type = "0" OR relation_type IS NULL OR relation_type = "")' => [
  870. $usergroup_id,
  871. $user_id,
  872. ],
  873. ]
  874. );
  875. } else {
  876. Database::delete(
  877. $this->usergroup_rel_user_table,
  878. [
  879. 'usergroup_id = ? AND user_id = ? AND relation_type = ?' => [
  880. $usergroup_id,
  881. $user_id,
  882. $relationType,
  883. ],
  884. ]
  885. );
  886. }
  887. }
  888. }
  889. // Adding new relationships
  890. if (!empty($new_items)) {
  891. // Adding sessions
  892. if (!empty($session_list)) {
  893. foreach ($session_list as $session_id) {
  894. SessionManager::subscribeUsersToSession($session_id, $new_items, null, false);
  895. }
  896. }
  897. foreach ($new_items as $user_id) {
  898. // Adding courses
  899. if (!empty($course_list)) {
  900. foreach ($course_list as $course_id) {
  901. $course_info = api_get_course_info_by_id($course_id);
  902. CourseManager::subscribeUser($user_id, $course_info['code']);
  903. }
  904. }
  905. $params = [
  906. 'user_id' => $user_id,
  907. 'usergroup_id' => $usergroup_id,
  908. 'relation_type' => $relationType,
  909. ];
  910. Database::insert($this->usergroup_rel_user_table, $params);
  911. }
  912. }
  913. }
  914. /**
  915. * @param string $name
  916. *
  917. * @return bool
  918. */
  919. public function usergroup_exists($name)
  920. {
  921. $name = Database::escape_string($name);
  922. if ($this->getUseMultipleUrl()) {
  923. $urlId = api_get_current_access_url_id();
  924. $sql = "SELECT * FROM $this->table u
  925. INNER JOIN {$this->access_url_rel_usergroup} a
  926. ON (a.usergroup_id = u.id)
  927. WHERE name = '".$name."' AND access_url_id = $urlId";
  928. } else {
  929. $sql = "SELECT * FROM $this->table WHERE name = '".$name."'";
  930. }
  931. $res = Database::query($sql);
  932. return Database::num_rows($res) != 0;
  933. }
  934. /**
  935. * @return bool
  936. */
  937. public function allowTeachers()
  938. {
  939. return api_get_configuration_value('allow_teachers_to_classes') === true;
  940. }
  941. /**
  942. * @param int $sidx
  943. * @param int $sord
  944. * @param int $start
  945. * @param int $limit
  946. *
  947. * @return array
  948. */
  949. public function getUsergroupsPagination($sidx, $sord, $start, $limit)
  950. {
  951. $sord = in_array(strtolower($sord), ['asc', 'desc']) ? $sord : 'desc';
  952. $start = (int) $start;
  953. $limit = (int) $limit;
  954. if ($this->getUseMultipleUrl()) {
  955. $urlId = api_get_current_access_url_id();
  956. $from = $this->table." u
  957. INNER JOIN {$this->access_url_rel_usergroup} a
  958. ON (u.id = a.usergroup_id)";
  959. $where = [' access_url_id = ?' => $urlId];
  960. } else {
  961. $from = $this->table.' u ';
  962. $where = [];
  963. }
  964. if ($this->allowTeachers()) {
  965. if (!api_is_platform_admin()) {
  966. $userId = api_get_user_id();
  967. $where = [' author_id = ?' => $userId];
  968. }
  969. }
  970. $result = Database::select(
  971. 'u.*',
  972. $from,
  973. [
  974. 'where' => $where,
  975. 'order' => "name $sord",
  976. 'LIMIT' => "$start , $limit",
  977. ]
  978. );
  979. $new_result = [];
  980. if (!empty($result)) {
  981. foreach ($result as $group) {
  982. $group['sessions'] = count($this->get_sessions_by_usergroup($group['id']));
  983. $group['courses'] = count($this->get_courses_by_usergroup($group['id']));
  984. $roles = [];
  985. switch ($group['group_type']) {
  986. case 0:
  987. $group['group_type'] = Display::label(get_lang('Class'), 'info');
  988. $roles = [0];
  989. break;
  990. case 1:
  991. $group['group_type'] = Display::label(get_lang('Social'), 'success');
  992. $roles = [
  993. GROUP_USER_PERMISSION_ADMIN,
  994. GROUP_USER_PERMISSION_READER,
  995. GROUP_USER_PERMISSION_MODERATOR,
  996. GROUP_USER_PERMISSION_HRM,
  997. ];
  998. break;
  999. }
  1000. $group['users'] = Display::url(
  1001. count($this->get_users_by_usergroup($group['id'], $roles)),
  1002. api_get_path(WEB_CODE_PATH).'admin/usergroup_users.php?id='.$group['id']
  1003. );
  1004. $new_result[] = $group;
  1005. }
  1006. $result = $new_result;
  1007. }
  1008. $columns = ['name', 'users', 'courses', 'sessions', 'group_type'];
  1009. if (!in_array($sidx, $columns)) {
  1010. $sidx = 'name';
  1011. }
  1012. // Multidimensional sort
  1013. $result = msort($result, $sidx, $sord);
  1014. return $result;
  1015. }
  1016. /**
  1017. * @param array $options
  1018. *
  1019. * @return array
  1020. */
  1021. public function getDataToExport($options = [])
  1022. {
  1023. if ($this->getUseMultipleUrl()) {
  1024. $urlId = api_get_current_access_url_id();
  1025. $from = $this->table." u
  1026. INNER JOIN {$this->access_url_rel_usergroup} a
  1027. ON (u.id = a.usergroup_id)";
  1028. $options = ['where' => ['access_url_id = ? ' => $urlId]];
  1029. if ($this->allowTeachers()) {
  1030. $options['where'] = [' author_id = ? ' => api_get_user_id()];
  1031. }
  1032. $classes = Database::select('a.id, name, description', $from, $options);
  1033. } else {
  1034. if ($this->allowTeachers()) {
  1035. $options['where'] = [' author_id = ? ' => api_get_user_id()];
  1036. }
  1037. $classes = Database::select('id, name, description', $this->table, $options);
  1038. }
  1039. $result = [];
  1040. if (!empty($classes)) {
  1041. foreach ($classes as $data) {
  1042. $users = $this->getUserListByUserGroup($data['id']);
  1043. $userToString = null;
  1044. if (!empty($users)) {
  1045. $userNameList = [];
  1046. foreach ($users as $userData) {
  1047. $userNameList[] = $userData['username'];
  1048. }
  1049. $userToString = implode(',', $userNameList);
  1050. }
  1051. $data['users'] = $userToString;
  1052. $result[] = $data;
  1053. }
  1054. }
  1055. return $result;
  1056. }
  1057. /**
  1058. * @param string $firstLetter
  1059. * @param int $limit
  1060. *
  1061. * @return array
  1062. */
  1063. public function filterByFirstLetter($firstLetter, $limit = 0)
  1064. {
  1065. $firstLetter = Database::escape_string($firstLetter);
  1066. $limit = (int) $limit;
  1067. $sql = ' SELECT g.id, name ';
  1068. $urlCondition = '';
  1069. if ($this->getUseMultipleUrl()) {
  1070. $urlId = api_get_current_access_url_id();
  1071. $sql .= " FROM $this->table g
  1072. INNER JOIN $this->access_url_rel_usergroup a
  1073. ON (g.id = a.usergroup_id) ";
  1074. $urlCondition = " AND access_url_id = $urlId ";
  1075. } else {
  1076. $sql = " FROM $this->table g ";
  1077. }
  1078. $sql .= "
  1079. WHERE
  1080. name LIKE '".$firstLetter."%' OR
  1081. name LIKE '".api_strtolower($firstLetter)."%'
  1082. $urlCondition
  1083. ORDER BY name DESC ";
  1084. if (!empty($limit)) {
  1085. $sql .= " LIMIT $limit ";
  1086. }
  1087. $result = Database::query($sql);
  1088. return Database::store_result($result);
  1089. }
  1090. /**
  1091. * Select user group not in list.
  1092. *
  1093. * @param array $list
  1094. *
  1095. * @return array
  1096. */
  1097. public function getUserGroupNotInList($list)
  1098. {
  1099. if (empty($list)) {
  1100. return [];
  1101. }
  1102. $list = array_map('intval', $list);
  1103. $listToString = implode("','", $list);
  1104. $sql = 'SELECT * ';
  1105. $urlCondition = '';
  1106. if ($this->getUseMultipleUrl()) {
  1107. $urlId = api_get_current_access_url_id();
  1108. $sql .= " FROM $this->table g
  1109. INNER JOIN $this->access_url_rel_usergroup a
  1110. ON (g.id = a.usergroup_id)";
  1111. $urlCondition = " AND access_url_id = $urlId ";
  1112. } else {
  1113. $sql = " FROM $this->table g ";
  1114. }
  1115. $sql .= " WHERE g.id NOT IN ('$listToString') $urlCondition ";
  1116. $result = Database::query($sql);
  1117. return Database::store_result($result, 'ASSOC');
  1118. }
  1119. /**
  1120. * @param $params
  1121. * @param bool $show_query
  1122. *
  1123. * @return bool|int
  1124. */
  1125. public function save($params, $show_query = false)
  1126. {
  1127. $params['updated_at'] = $params['created_at'] = api_get_utc_datetime();
  1128. $params['group_type'] = isset($params['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
  1129. $params['allow_members_leave_group'] = isset($params['allow_members_leave_group']) ? 1 : 0;
  1130. $groupExists = $this->usergroup_exists(trim($params['name']));
  1131. if ($groupExists == false) {
  1132. if ($this->allowTeachers()) {
  1133. $params['author_id'] = api_get_user_id();
  1134. }
  1135. $id = parent::save($params, $show_query);
  1136. if ($id) {
  1137. if ($this->getUseMultipleUrl()) {
  1138. $this->subscribeToUrl($id, api_get_current_access_url_id());
  1139. }
  1140. if ($params['group_type'] == self::SOCIAL_CLASS) {
  1141. $this->add_user_to_group(
  1142. api_get_user_id(),
  1143. $id,
  1144. $params['group_type']
  1145. );
  1146. }
  1147. $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
  1148. $picture = $this->manageFileUpload($id, $picture);
  1149. if ($picture) {
  1150. $params = [
  1151. 'id' => $id,
  1152. 'picture' => $picture,
  1153. 'group_type' => $params['group_type'],
  1154. ];
  1155. $this->update($params);
  1156. }
  1157. }
  1158. return $id;
  1159. }
  1160. return false;
  1161. }
  1162. /**
  1163. * {@inheritdoc}
  1164. */
  1165. public function update($values, $showQuery = false)
  1166. {
  1167. $values['updated_on'] = api_get_utc_datetime();
  1168. $values['group_type'] = isset($values['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
  1169. $values['allow_members_leave_group'] = isset($values['allow_members_leave_group']) ? 1 : 0;
  1170. $values['crop_image'] = isset($values['picture_crop_result']) ? $values['picture_crop_result'] : null;
  1171. if (isset($values['id'])) {
  1172. $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
  1173. if (!empty($picture)) {
  1174. $picture = $this->manageFileUpload($values['id'], $picture, $values['crop_image']);
  1175. if ($picture) {
  1176. $values['picture'] = $picture;
  1177. }
  1178. }
  1179. if (isset($values['delete_picture'])) {
  1180. $values['picture'] = null;
  1181. }
  1182. }
  1183. parent::update($values, $showQuery);
  1184. if (isset($values['delete_picture'])) {
  1185. $this->delete_group_picture($values['id']);
  1186. }
  1187. return true;
  1188. }
  1189. /**
  1190. * @param int $groupId
  1191. * @param string $picture
  1192. * @param string $cropParameters
  1193. *
  1194. * @return bool|string
  1195. */
  1196. public function manageFileUpload($groupId, $picture, $cropParameters = '')
  1197. {
  1198. if (!empty($picture['name'])) {
  1199. return $this->update_group_picture(
  1200. $groupId,
  1201. $picture['name'],
  1202. $picture['tmp_name'],
  1203. $cropParameters
  1204. );
  1205. }
  1206. return false;
  1207. }
  1208. /**
  1209. * @param int $groupId
  1210. *
  1211. * @return string
  1212. */
  1213. public function delete_group_picture($groupId)
  1214. {
  1215. return $this->update_group_picture($groupId);
  1216. }
  1217. /**
  1218. * Creates new group pictures in various sizes of a user, or deletes user pfotos.
  1219. * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php.
  1220. *
  1221. * @param int The group id
  1222. * @param string $file The common file name for the newly created photos.
  1223. * It will be checked and modified for compatibility with the file system.
  1224. * If full name is provided, path component is ignored.
  1225. * If an empty name is provided, then old user photos are deleted only,
  1226. *
  1227. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  1228. *
  1229. * @param string $source_file the full system name of the image from which user photos will be created
  1230. * @param string $cropParameters
  1231. *
  1232. * @return mixed Returns the resulting common file name of created images which usually should be stored in database.
  1233. * When an image is removed the function returns an empty string. In case of internal error or negative validation it returns FALSE.
  1234. *
  1235. * @see UserManager::delete_user_picture() as the prefered way for deletion.
  1236. */
  1237. public function update_group_picture($group_id, $file = null, $source_file = null, $cropParameters = null)
  1238. {
  1239. $group_id = (int) $group_id;
  1240. if (empty($group_id)) {
  1241. return false;
  1242. }
  1243. $delete = empty($file);
  1244. if (empty($source_file)) {
  1245. $source_file = $file;
  1246. }
  1247. // User-reserved directory where photos have to be placed.
  1248. $path_info = $this->get_group_picture_path_by_id($group_id, 'system', true);
  1249. $path = $path_info['dir'];
  1250. // If this directory does not exist - we create it.
  1251. if (!is_dir($path)) {
  1252. $res = @mkdir($path, api_get_permissions_for_new_directories(), true);
  1253. if ($res === false) {
  1254. // There was an issue creating the directory $path, probably
  1255. // permissions-related
  1256. return false;
  1257. }
  1258. }
  1259. // Exit if only deletion has been requested. Return an empty picture name.
  1260. if ($delete) {
  1261. return '';
  1262. }
  1263. // Validation 2.
  1264. $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
  1265. $file = str_replace('\\', '/', $file);
  1266. $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
  1267. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  1268. if (!in_array($extension, $allowed_types)) {
  1269. return false;
  1270. }
  1271. $avatar = 'group_avatar.jpg';
  1272. $filename = $group_id.'_'.$filename;
  1273. $groupImageBig = $path.'big_'.$filename;
  1274. $groupImage = $path.'medium_'.$filename;
  1275. if (file_exists($groupImageBig)) {
  1276. unlink($groupImageBig);
  1277. }
  1278. if (file_exists($groupImage)) {
  1279. unlink($groupImage);
  1280. }
  1281. $image = new Image($source_file);
  1282. $image->crop($cropParameters);
  1283. //Resize the images in two formats
  1284. $medium = new Image($source_file);
  1285. $medium->resize(128);
  1286. $medium->send_image($groupImage, -1, 'jpg');
  1287. $normal = new Image($source_file);
  1288. $normal->resize(450);
  1289. $normal->send_image($groupImageBig, -1, 'jpg');
  1290. return $filename;
  1291. }
  1292. /**
  1293. * @return mixed
  1294. */
  1295. public function getGroupType()
  1296. {
  1297. return $this->groupType;
  1298. }
  1299. /**
  1300. * @param int $id
  1301. *
  1302. * @return bool|void
  1303. */
  1304. public function delete($id)
  1305. {
  1306. $id = (int) $id;
  1307. if ($this->getUseMultipleUrl()) {
  1308. $this->unsubscribeToUrl($id, api_get_current_access_url_id());
  1309. }
  1310. $sql = "DELETE FROM $this->usergroup_rel_user_table
  1311. WHERE usergroup_id = $id";
  1312. Database::query($sql);
  1313. $sql = "DELETE FROM $this->usergroup_rel_course_table
  1314. WHERE usergroup_id = $id";
  1315. Database::query($sql);
  1316. $sql = "DELETE FROM $this->usergroup_rel_session_table
  1317. WHERE usergroup_id = $id";
  1318. Database::query($sql);
  1319. parent::delete($id);
  1320. }
  1321. /**
  1322. * @param int $id
  1323. * @param int $urlId
  1324. */
  1325. public function subscribeToUrl($id, $urlId)
  1326. {
  1327. Database::insert(
  1328. $this->access_url_rel_usergroup,
  1329. [
  1330. 'access_url_id' => $urlId,
  1331. 'usergroup_id' => $id,
  1332. ]
  1333. );
  1334. }
  1335. /**
  1336. * @param int $id
  1337. * @param int $urlId
  1338. */
  1339. public function unsubscribeToUrl($id, $urlId)
  1340. {
  1341. Database::delete(
  1342. $this->access_url_rel_usergroup,
  1343. [
  1344. 'access_url_id = ? AND usergroup_id = ? ' => [$urlId, $id],
  1345. ]
  1346. );
  1347. }
  1348. /**
  1349. * @param $needle
  1350. *
  1351. * @return xajaxResponse
  1352. */
  1353. public static function searchUserGroupAjax($needle)
  1354. {
  1355. $response = new xajaxResponse();
  1356. $return = '';
  1357. if (!empty($needle)) {
  1358. // xajax send utf8 datas... datas in db can be non-utf8 datas
  1359. $charset = api_get_system_encoding();
  1360. $needle = api_convert_encoding($needle, $charset, 'utf-8');
  1361. $needle = Database::escape_string($needle);
  1362. $sql = 'SELECT id, name
  1363. FROM '.Database::get_main_table(TABLE_USERGROUP).' u
  1364. WHERE name LIKE "'.$needle.'%"
  1365. ORDER BY name
  1366. LIMIT 11';
  1367. $result = Database::query($sql);
  1368. $i = 0;
  1369. while ($data = Database::fetch_array($result)) {
  1370. $i++;
  1371. if ($i <= 10) {
  1372. $return .= '<a
  1373. href="javascript: void(0);"
  1374. onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['name']).' \')">'.$data['name'].' </a><br />';
  1375. } else {
  1376. $return .= '...<br />';
  1377. }
  1378. }
  1379. }
  1380. $response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return));
  1381. return $response;
  1382. }
  1383. /**
  1384. * Get user list by usergroup.
  1385. *
  1386. * @param int $id
  1387. *
  1388. * @return array
  1389. */
  1390. public function getUserListByUserGroup($id)
  1391. {
  1392. $id = (int) $id;
  1393. $sql = "SELECT u.* FROM $this->table_user u
  1394. INNER JOIN $this->usergroup_rel_user_table c
  1395. ON c.user_id = u.id
  1396. WHERE c.usergroup_id = $id"
  1397. ;
  1398. $result = Database::query($sql);
  1399. return Database::store_result($result);
  1400. }
  1401. /**
  1402. * @param FormValidator $form
  1403. * @param string $type
  1404. * @param array $data
  1405. */
  1406. public function setForm($form, $type = 'add', $data = [])
  1407. {
  1408. $header = '';
  1409. switch ($type) {
  1410. case 'add':
  1411. $header = get_lang('Add');
  1412. break;
  1413. case 'edit':
  1414. $header = get_lang('Edit');
  1415. break;
  1416. }
  1417. $form->addHeader($header);
  1418. // Name
  1419. $form->addElement('text', 'name', get_lang('Name'), ['maxlength' => 255]);
  1420. $form->applyFilter('name', 'trim');
  1421. $form->addRule('name', get_lang('Required field'), 'required');
  1422. $form->addRule('name', '', 'maxlength', 255);
  1423. // Description
  1424. $form->addHtmlEditor(
  1425. 'description',
  1426. get_lang('Description'),
  1427. true,
  1428. false,
  1429. [
  1430. 'ToolbarSet' => 'Minimal',
  1431. ]
  1432. );
  1433. $form->applyFilter('description', 'trim');
  1434. if ($this->showGroupTypeSetting) {
  1435. $form->addElement(
  1436. 'checkbox',
  1437. 'group_type',
  1438. null,
  1439. get_lang('Social group')
  1440. );
  1441. }
  1442. // url
  1443. $form->addElement('text', 'url', get_lang('URL'));
  1444. $form->applyFilter('url', 'trim');
  1445. // Picture
  1446. //$allowed_picture_types = $this->getAllowedPictureExtensions();
  1447. // Picture
  1448. $form->addFile(
  1449. 'picture',
  1450. get_lang('Add a picture'),
  1451. ['id' => 'picture', 'class' => 'picture-form', 'crop_image' => true, 'crop_ratio' => '1 / 1']
  1452. );
  1453. if (isset($data['picture']) && strlen($data['picture']) > 0) {
  1454. $picture = $this->get_picture_group($data['id'], $data['picture'], 80);
  1455. $img = '<img src="'.$picture.'" />';
  1456. $form->addElement('label', null, $img);
  1457. $form->addElement('checkbox', 'delete_picture', '', get_lang('Remove picture'));
  1458. }
  1459. $form->addElement('select', 'visibility', get_lang('Group Permissions'), $this->getGroupStatusList());
  1460. $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('Required field').'</small>');
  1461. $form->addElement('checkbox', 'allow_members_leave_group', '', get_lang('Allow members to leave group'));
  1462. // Setting the form elements
  1463. if ($type === 'add') {
  1464. $form->addButtonCreate($header);
  1465. } else {
  1466. $form->addButtonUpdate($header);
  1467. }
  1468. }
  1469. /**
  1470. * Gets the current group image.
  1471. *
  1472. * @param string $id group id
  1473. * @param string picture group name
  1474. * @param string height
  1475. * @param string $size_picture picture size it can be small_, medium_ or big_
  1476. * @param string style css
  1477. *
  1478. * @return array with the file and the style of an image i.e $array['file'] $array['style']
  1479. */
  1480. public function get_picture_group(
  1481. $id,
  1482. $picture_file,
  1483. $height,
  1484. $size_picture = GROUP_IMAGE_SIZE_MEDIUM,
  1485. $style = ''
  1486. ) {
  1487. $picture = [];
  1488. //$picture['style'] = $style;
  1489. if ($picture_file === 'unknown.jpg') {
  1490. $picture['file'] = Display::returnIconPath($picture_file);
  1491. return $picture;
  1492. }
  1493. switch ($size_picture) {
  1494. case GROUP_IMAGE_SIZE_ORIGINAL:
  1495. $size_picture = '';
  1496. break;
  1497. case GROUP_IMAGE_SIZE_BIG:
  1498. $size_picture = 'big_';
  1499. break;
  1500. case GROUP_IMAGE_SIZE_MEDIUM:
  1501. $size_picture = 'medium_';
  1502. break;
  1503. case GROUP_IMAGE_SIZE_SMALL:
  1504. $size_picture = 'small_';
  1505. break;
  1506. default:
  1507. $size_picture = 'medium_';
  1508. }
  1509. $image_array_sys = $this->get_group_picture_path_by_id($id, 'system', false, true);
  1510. $image_array = $this->get_group_picture_path_by_id($id, 'web', false, true);
  1511. $file = $image_array_sys['dir'].$size_picture.$picture_file;
  1512. if (file_exists($file)) {
  1513. $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
  1514. //$picture['style'] = '';
  1515. if ($height > 0) {
  1516. $dimension = api_getimagesize($picture['file']);
  1517. $margin = ($height - $dimension['width']) / 2;
  1518. //@ todo the padding-top should not be here
  1519. }
  1520. } else {
  1521. $file = $image_array_sys['dir'].$picture_file;
  1522. if (file_exists($file) && !is_dir($file)) {
  1523. $picture['file'] = $image_array['dir'].$picture_file;
  1524. } else {
  1525. $picture['file'] = Display::returnIconPath('group_na.png', 64);
  1526. }
  1527. }
  1528. return $picture;
  1529. }
  1530. /**
  1531. * Gets the group picture URL or path from group ID (returns an array).
  1532. * The return format is a complete path, enabling recovery of the directory
  1533. * with dirname() or the file with basename(). This also works for the
  1534. * functions dealing with the user's productions, as they are located in
  1535. * the same directory.
  1536. *
  1537. * @param int User ID
  1538. * @param string Type of path to return (can be 'none', 'system', 'rel', 'web')
  1539. * @param bool Whether we want to have the directory name returned 'as if'
  1540. * there was a file or not (in the case we want to know which directory to create -
  1541. * otherwise no file means no split subdir)
  1542. * @param bool If we want that the function returns the /main/img/unknown.jpg image set it at true
  1543. *
  1544. * @return array Array of 2 elements: 'dir' and 'file' which contain the dir
  1545. * and file as the name implies if image does not exist it will return the unknown
  1546. * image if anonymous parameter is true if not it returns an empty er's
  1547. */
  1548. public function get_group_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
  1549. {
  1550. switch ($type) {
  1551. case 'system': // Base: absolute system path.
  1552. $base = api_get_path(SYS_UPLOAD_PATH);
  1553. break;
  1554. case 'rel': // Base: semi-absolute web path (no server base).
  1555. $base = api_get_path(REL_CODE_PATH);
  1556. break;
  1557. case 'web': // Base: absolute web path.
  1558. $base = api_get_path(WEB_UPLOAD_PATH);
  1559. break;
  1560. case 'none':
  1561. default: // Base: empty, the result path below will be relative.
  1562. $base = '';
  1563. }
  1564. $id = (int) $id;
  1565. if (empty($id) || empty($type)) {
  1566. return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
  1567. }
  1568. $group_table = Database::get_main_table(TABLE_USERGROUP);
  1569. $sql = "SELECT picture FROM $group_table WHERE id = ".$id;
  1570. $res = Database::query($sql);
  1571. if (!Database::num_rows($res)) {
  1572. return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
  1573. }
  1574. $user = Database::fetch_array($res);
  1575. $picture_filename = trim($user['picture']);
  1576. if (api_get_setting('split_users_upload_directory') === 'true') {
  1577. if (!empty($picture_filename)) {
  1578. $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
  1579. } elseif ($preview) {
  1580. $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
  1581. } else {
  1582. $dir = $base.'groups/'.$id.'/';
  1583. }
  1584. } else {
  1585. $dir = $base.'groups/'.$id.'/';
  1586. }
  1587. return ['dir' => $dir, 'file' => $picture_filename];
  1588. }
  1589. /**
  1590. * @return array
  1591. */
  1592. public function getAllowedPictureExtensions()
  1593. {
  1594. return ['jpg', 'jpeg', 'png', 'gif'];
  1595. }
  1596. /**
  1597. * @return array
  1598. */
  1599. public function getGroupStatusList()
  1600. {
  1601. $status = [
  1602. GROUP_PERMISSION_OPEN => get_lang('Open'),
  1603. GROUP_PERMISSION_CLOSED => get_lang('Closed'),
  1604. ];
  1605. return $status;
  1606. }
  1607. /**
  1608. * @param int $type
  1609. */
  1610. public function setGroupType($type)
  1611. {
  1612. $this->groupType = (int) $type;
  1613. }
  1614. /**
  1615. * @param int $group_id
  1616. * @param int $user_id
  1617. *
  1618. * @return bool
  1619. */
  1620. public function is_group_admin($group_id, $user_id = 0)
  1621. {
  1622. if (empty($user_id)) {
  1623. $user_id = api_get_user_id();
  1624. }
  1625. $user_role = $this->get_user_group_role($user_id, $group_id);
  1626. if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN])) {
  1627. return true;
  1628. } else {
  1629. return false;
  1630. }
  1631. }
  1632. /**
  1633. * @param int $group_id
  1634. * @param int $user_id
  1635. *
  1636. * @return bool
  1637. */
  1638. public function isGroupModerator($group_id, $user_id = 0)
  1639. {
  1640. if (empty($user_id)) {
  1641. $user_id = api_get_user_id();
  1642. }
  1643. $user_role = $this->get_user_group_role($user_id, $group_id);
  1644. if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR])) {
  1645. return true;
  1646. } else {
  1647. return false;
  1648. }
  1649. }
  1650. /**
  1651. * @param int $group_id
  1652. * @param int $user_id
  1653. *
  1654. * @return bool
  1655. */
  1656. public function is_group_member($group_id, $user_id = 0)
  1657. {
  1658. if (api_is_platform_admin()) {
  1659. return true;
  1660. }
  1661. if (empty($user_id)) {
  1662. $user_id = api_get_user_id();
  1663. }
  1664. $roles = [
  1665. GROUP_USER_PERMISSION_ADMIN,
  1666. GROUP_USER_PERMISSION_MODERATOR,
  1667. GROUP_USER_PERMISSION_READER,
  1668. GROUP_USER_PERMISSION_HRM,
  1669. ];
  1670. $user_role = $this->get_user_group_role($user_id, $group_id);
  1671. if (in_array($user_role, $roles)) {
  1672. return true;
  1673. } else {
  1674. return false;
  1675. }
  1676. }
  1677. /**
  1678. * Gets the relationship between a group and a User.
  1679. *
  1680. * @author Julio Montoya
  1681. *
  1682. * @param int $user_id
  1683. * @param int $group_id
  1684. *
  1685. * @return int 0 if there are not relationship otherwise returns the user group
  1686. * */
  1687. public function get_user_group_role($user_id, $group_id)
  1688. {
  1689. $table_group_rel_user = $this->usergroup_rel_user_table;
  1690. $return_value = 0;
  1691. $user_id = (int) $user_id;
  1692. $group_id = (int) $group_id;
  1693. if (!empty($user_id) && !empty($group_id)) {
  1694. $sql = "SELECT relation_type
  1695. FROM $table_group_rel_user
  1696. WHERE
  1697. usergroup_id = $group_id AND
  1698. user_id = $user_id ";
  1699. $result = Database::query($sql);
  1700. if (Database::num_rows($result) > 0) {
  1701. $row = Database::fetch_array($result, 'ASSOC');
  1702. $return_value = $row['relation_type'];
  1703. }
  1704. }
  1705. return $return_value;
  1706. }
  1707. /**
  1708. * @param int $userId
  1709. * @param int $groupId
  1710. *
  1711. * @return string
  1712. */
  1713. public function getUserRoleToString($userId, $groupId)
  1714. {
  1715. $role = $this->get_user_group_role($userId, $groupId);
  1716. $roleToString = '';
  1717. switch ($role) {
  1718. case GROUP_USER_PERMISSION_ADMIN:
  1719. $roleToString = get_lang('Admin');
  1720. break;
  1721. case GROUP_USER_PERMISSION_READER:
  1722. $roleToString = get_lang('Reader');
  1723. break;
  1724. case GROUP_USER_PERMISSION_PENDING_INVITATION:
  1725. $roleToString = get_lang('Pending invitation');
  1726. break;
  1727. case GROUP_USER_PERMISSION_MODERATOR:
  1728. $roleToString = get_lang('Moderator');
  1729. break;
  1730. case GROUP_USER_PERMISSION_HRM:
  1731. $roleToString = get_lang('Human Resources Manager');
  1732. break;
  1733. }
  1734. return $roleToString;
  1735. }
  1736. /**
  1737. * Add a group of users into a group of URLs.
  1738. *
  1739. * @author Julio Montoya
  1740. *
  1741. * @param array $user_list
  1742. * @param array $group_list
  1743. * @param int $relation_type
  1744. *
  1745. * @return array
  1746. */
  1747. public function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
  1748. {
  1749. $table_url_rel_group = $this->usergroup_rel_user_table;
  1750. $result_array = [];
  1751. $relation_type = (int) $relation_type;
  1752. if (is_array($user_list) && is_array($group_list)) {
  1753. foreach ($group_list as $group_id) {
  1754. foreach ($user_list as $user_id) {
  1755. $user_id = (int) $user_id;
  1756. $group_id = (int) $group_id;
  1757. $role = $this->get_user_group_role($user_id, $group_id);
  1758. if ($role == 0) {
  1759. $sql = "INSERT INTO $table_url_rel_group
  1760. SET
  1761. user_id = $user_id ,
  1762. usergroup_id = $group_id ,
  1763. relation_type = $relation_type ";
  1764. $result = Database::query($sql);
  1765. if ($result) {
  1766. $result_array[$group_id][$user_id] = 1;
  1767. } else {
  1768. $result_array[$group_id][$user_id] = 0;
  1769. }
  1770. }
  1771. }
  1772. }
  1773. }
  1774. return $result_array;
  1775. }
  1776. /**
  1777. * Deletes an url and session relationship.
  1778. *
  1779. * @author Julio Montoya
  1780. *
  1781. * @param int $userId
  1782. * @param int $groupId
  1783. *
  1784. * @return bool true if success
  1785. * */
  1786. public function delete_user_rel_group($userId, $groupId)
  1787. {
  1788. $userId = (int) $userId;
  1789. $groupId = (int) $groupId;
  1790. if (empty($userId) || empty($groupId)) {
  1791. return false;
  1792. }
  1793. $table = $this->usergroup_rel_user_table;
  1794. $sql = "DELETE FROM $table
  1795. WHERE
  1796. user_id = $userId AND
  1797. usergroup_id = $groupId";
  1798. $result = Database::query($sql);
  1799. return $result;
  1800. }
  1801. /**
  1802. * Add a user into a group.
  1803. *
  1804. * @author Julio Montoya
  1805. *
  1806. * @param int $user_id
  1807. * @param int $group_id
  1808. * @param int $relation_type
  1809. *
  1810. * @return bool true if success
  1811. */
  1812. public function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
  1813. {
  1814. $table_url_rel_group = $this->usergroup_rel_user_table;
  1815. if (!empty($user_id) && !empty($group_id)) {
  1816. $role = $this->get_user_group_role($user_id, $group_id);
  1817. if ($role == 0) {
  1818. $sql = "INSERT INTO $table_url_rel_group
  1819. SET
  1820. user_id = ".intval($user_id).",
  1821. usergroup_id = ".intval($group_id).",
  1822. relation_type = ".intval($relation_type);
  1823. Database::query($sql);
  1824. } elseif ($role == GROUP_USER_PERMISSION_PENDING_INVITATION) {
  1825. //if somebody already invited me I can be added
  1826. self::update_user_role($user_id, $group_id, GROUP_USER_PERMISSION_READER);
  1827. }
  1828. }
  1829. return true;
  1830. }
  1831. /**
  1832. * Updates the group_rel_user table with a given user and group ids.
  1833. *
  1834. * @author Julio Montoya
  1835. *
  1836. * @param int $user_id
  1837. * @param int $group_id
  1838. * @param int $relation_type
  1839. */
  1840. public function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
  1841. {
  1842. $table_group_rel_user = $this->usergroup_rel_user_table;
  1843. $group_id = (int) $group_id;
  1844. $user_id = (int) $user_id;
  1845. $relation_type = (int) $relation_type;
  1846. $sql = "UPDATE $table_group_rel_user
  1847. SET relation_type = $relation_type
  1848. WHERE user_id = $user_id AND usergroup_id = $group_id";
  1849. Database::query($sql);
  1850. }
  1851. /**
  1852. * Gets the inner join from users and group table.
  1853. *
  1854. * @return array Database::store_result of the result
  1855. *
  1856. * @author Julio Montoya
  1857. * */
  1858. public function get_groups_by_user($user_id, $relationType = GROUP_USER_PERMISSION_READER, $with_image = false)
  1859. {
  1860. $table_group_rel_user = $this->usergroup_rel_user_table;
  1861. $tbl_group = $this->table;
  1862. $user_id = (int) $user_id;
  1863. if ($relationType == 0) {
  1864. $relationCondition = '';
  1865. } else {
  1866. if (is_array($relationType)) {
  1867. $relationType = array_map('intval', $relationType);
  1868. $relationType = implode("','", $relationType);
  1869. $relationCondition = " AND ( gu.relation_type IN ('$relationType')) ";
  1870. } else {
  1871. $relationType = (int) $relationType;
  1872. $relationCondition = " AND gu.relation_type = $relationType ";
  1873. }
  1874. }
  1875. $sql = 'SELECT
  1876. g.picture,
  1877. g.name,
  1878. g.description,
  1879. g.id ,
  1880. gu.relation_type';
  1881. $urlCondition = '';
  1882. if ($this->getUseMultipleUrl()) {
  1883. $sql .= " FROM $tbl_group g
  1884. INNER JOIN ".$this->access_url_rel_usergroup." a
  1885. ON (g.id = a.usergroup_id)
  1886. INNER JOIN $table_group_rel_user gu
  1887. ON gu.usergroup_id = g.id";
  1888. $urlId = api_get_current_access_url_id();
  1889. $urlCondition = " AND access_url_id = $urlId ";
  1890. } else {
  1891. $sql .= " FROM $tbl_group g
  1892. INNER JOIN $table_group_rel_user gu
  1893. ON gu.usergroup_id = g.id";
  1894. }
  1895. $sql .= " WHERE
  1896. g.group_type = ".self::SOCIAL_CLASS." AND
  1897. gu.user_id = $user_id
  1898. $relationCondition
  1899. $urlCondition
  1900. ORDER BY created_at DESC ";
  1901. $result = Database::query($sql);
  1902. $array = [];
  1903. if (Database::num_rows($result) > 0) {
  1904. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1905. if ($with_image) {
  1906. $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
  1907. $img = '<img src="'.$picture['file'].'" />';
  1908. $row['picture'] = $img;
  1909. }
  1910. $array[$row['id']] = $row;
  1911. }
  1912. }
  1913. return $array;
  1914. }
  1915. /** Gets the inner join of users and group table
  1916. * @param int quantity of records
  1917. * @param bool show groups with image or not
  1918. *
  1919. * @return array with group content
  1920. *
  1921. * @author Julio Montoya
  1922. * */
  1923. public function get_groups_by_popularity($num = 6, $with_image = true)
  1924. {
  1925. $table_group_rel_user = $this->usergroup_rel_user_table;
  1926. $tbl_group = $this->table;
  1927. if (empty($num)) {
  1928. $num = 6;
  1929. } else {
  1930. $num = (int) $num;
  1931. }
  1932. // only show admins and readers
  1933. $whereCondition = " WHERE
  1934. g.group_type = ".self::SOCIAL_CLASS." AND
  1935. gu.relation_type IN
  1936. ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
  1937. $sql = 'SELECT DISTINCT count(user_id) as count, g.picture, g.name, g.description, g.id ';
  1938. $urlCondition = '';
  1939. if ($this->getUseMultipleUrl()) {
  1940. $sql .= " FROM $tbl_group g
  1941. INNER JOIN ".$this->access_url_rel_usergroup." a
  1942. ON (g.id = a.usergroup_id)
  1943. INNER JOIN $table_group_rel_user gu
  1944. ON gu.usergroup_id = g.id";
  1945. $urlId = api_get_current_access_url_id();
  1946. $urlCondition = " AND access_url_id = $urlId ";
  1947. } else {
  1948. $sql .= " FROM $tbl_group g
  1949. INNER JOIN $table_group_rel_user gu
  1950. ON gu.usergroup_id = g.id";
  1951. }
  1952. $sql .= "
  1953. $whereCondition
  1954. $urlCondition
  1955. GROUP BY g.id
  1956. ORDER BY count DESC
  1957. LIMIT $num";
  1958. $result = Database::query($sql);
  1959. $array = [];
  1960. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1961. if ($with_image) {
  1962. $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
  1963. $img = '<img src="'.$picture['file'].'" />';
  1964. $row['picture'] = $img;
  1965. }
  1966. if (empty($row['id'])) {
  1967. continue;
  1968. }
  1969. $array[$row['id']] = $row;
  1970. }
  1971. return $array;
  1972. }
  1973. /** Gets the last groups created
  1974. * @param int $num quantity of records
  1975. * @param bool $withImage show groups with image or not
  1976. *
  1977. * @return array with group content
  1978. *
  1979. * @author Julio Montoya
  1980. * */
  1981. public function get_groups_by_age($num = 6, $withImage = true)
  1982. {
  1983. $table_group_rel_user = $this->usergroup_rel_user_table;
  1984. $tbl_group = $this->table;
  1985. if (empty($num)) {
  1986. $num = 6;
  1987. } else {
  1988. $num = (int) $num;
  1989. }
  1990. $where = " WHERE
  1991. g.group_type = ".self::SOCIAL_CLASS." AND
  1992. gu.relation_type IN
  1993. ('".GROUP_USER_PERMISSION_ADMIN."' ,
  1994. '".GROUP_USER_PERMISSION_READER."',
  1995. '".GROUP_USER_PERMISSION_MODERATOR."',
  1996. '".GROUP_USER_PERMISSION_HRM."')
  1997. ";
  1998. $sql = 'SELECT DISTINCT
  1999. count(user_id) as count,
  2000. g.picture,
  2001. g.name,
  2002. g.description,
  2003. g.id ';
  2004. $urlCondition = '';
  2005. if ($this->getUseMultipleUrl()) {
  2006. $sql .= " FROM $tbl_group g
  2007. INNER JOIN ".$this->access_url_rel_usergroup." a
  2008. ON (g.id = a.usergroup_id)
  2009. INNER JOIN $table_group_rel_user gu
  2010. ON gu.usergroup_id = g.id";
  2011. $urlId = api_get_current_access_url_id();
  2012. $urlCondition = " AND access_url_id = $urlId ";
  2013. } else {
  2014. $sql .= " FROM $tbl_group g
  2015. INNER JOIN $table_group_rel_user gu
  2016. ON gu.usergroup_id = g.id";
  2017. }
  2018. $sql .= "
  2019. $where
  2020. $urlCondition
  2021. GROUP BY g.id
  2022. ORDER BY created_at DESC
  2023. LIMIT $num ";
  2024. $result = Database::query($sql);
  2025. $array = [];
  2026. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2027. if ($withImage) {
  2028. $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
  2029. $img = '<img src="'.$picture['file'].'" />';
  2030. $row['picture'] = $img;
  2031. }
  2032. if (empty($row['id'])) {
  2033. continue;
  2034. }
  2035. $array[$row['id']] = $row;
  2036. }
  2037. return $array;
  2038. }
  2039. /**
  2040. * Gets the group's members.
  2041. *
  2042. * @param int group id
  2043. * @param bool show image or not of the group
  2044. * @param array list of relation type use constants
  2045. * @param int from value
  2046. * @param int limit
  2047. * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
  2048. *
  2049. * @return array list of users in a group
  2050. */
  2051. public function get_users_by_group(
  2052. $group_id,
  2053. $withImage = false,
  2054. $relation_type = [],
  2055. $from = null,
  2056. $limit = null,
  2057. $image_conf = ['size' => USER_IMAGE_SIZE_MEDIUM, 'height' => 80]
  2058. ) {
  2059. $table_group_rel_user = $this->usergroup_rel_user_table;
  2060. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2061. $group_id = (int) $group_id;
  2062. if (empty($group_id)) {
  2063. return [];
  2064. }
  2065. $limit_text = '';
  2066. if (isset($from) && isset($limit)) {
  2067. $from = (int) $from;
  2068. $limit = (int) $limit;
  2069. $limit_text = "LIMIT $from, $limit";
  2070. }
  2071. if (count($relation_type) == 0) {
  2072. $where_relation_condition = '';
  2073. } else {
  2074. $new_relation_type = [];
  2075. foreach ($relation_type as $rel) {
  2076. $rel = (int) $rel;
  2077. $new_relation_type[] = "'$rel'";
  2078. }
  2079. $relation_type = implode(',', $new_relation_type);
  2080. if (!empty($relation_type)) {
  2081. $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
  2082. }
  2083. }
  2084. $sql = "SELECT picture_uri as image, u.id, CONCAT (u.firstname,' ', u.lastname) as fullname, relation_type
  2085. FROM $tbl_user u
  2086. INNER JOIN $table_group_rel_user gu
  2087. ON (gu.user_id = u.id)
  2088. WHERE
  2089. gu.usergroup_id= $group_id
  2090. $where_relation_condition
  2091. ORDER BY relation_type, firstname
  2092. $limit_text";
  2093. $result = Database::query($sql);
  2094. $array = [];
  2095. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2096. if ($withImage) {
  2097. $userInfo = api_get_user_info($row['id']);
  2098. $userPicture = UserManager::getUserPicture($row['id']);
  2099. $row['image'] = '<img src="'.$userPicture.'" />';
  2100. $row['user_info'] = $userInfo;
  2101. }
  2102. $array[$row['id']] = $row;
  2103. }
  2104. return $array;
  2105. }
  2106. /**
  2107. * Gets all the members of a group no matter the relationship for
  2108. * more specifications use get_users_by_group.
  2109. *
  2110. * @param int group id
  2111. *
  2112. * @return array
  2113. */
  2114. public function get_all_users_by_group($group_id)
  2115. {
  2116. $table_group_rel_user = $this->usergroup_rel_user_table;
  2117. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2118. $group_id = (int) $group_id;
  2119. if (empty($group_id)) {
  2120. return [];
  2121. }
  2122. $sql = "SELECT u.id, u.firstname, u.lastname, relation_type
  2123. FROM $tbl_user u
  2124. INNER JOIN $table_group_rel_user gu
  2125. ON (gu.user_id = u.id)
  2126. WHERE gu.usergroup_id= $group_id
  2127. ORDER BY relation_type, firstname";
  2128. $result = Database::query($sql);
  2129. $array = [];
  2130. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2131. $array[$row['id']] = $row;
  2132. }
  2133. return $array;
  2134. }
  2135. /**
  2136. * Shows the left column of the group page.
  2137. *
  2138. * @param int $group_id
  2139. * @param int $user_id
  2140. * @param string $show
  2141. *
  2142. * @return string
  2143. */
  2144. public function show_group_column_information($group_id, $user_id, $show = '')
  2145. {
  2146. $html = '';
  2147. $group_info = $this->get($group_id);
  2148. //my relation with the group is set here
  2149. $my_group_role = $this->get_user_group_role($user_id, $group_id);
  2150. // Loading group permission
  2151. $links = '';
  2152. switch ($my_group_role) {
  2153. case GROUP_USER_PERMISSION_READER:
  2154. // I'm just a reader
  2155. $relation_group_title = get_lang('I am a reader');
  2156. $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
  2157. Display::return_icon('invitation_friend.png', get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
  2158. if (self::canLeave($group_info)) {
  2159. $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
  2160. Display::return_icon('group_leave.png', get_lang('Leave group')).get_lang('Leave group').'</a></li>';
  2161. }
  2162. break;
  2163. case GROUP_USER_PERMISSION_ADMIN:
  2164. $relation_group_title = get_lang('I am an admin');
  2165. $links .= '<li class="'.($show == 'group_edit' ? 'active' : '').'"><a href="group_edit.php?id='.$group_id.'">'.
  2166. Display::return_icon('group_edit.png', get_lang('Edit this group')).get_lang('Edit this group').'</a></li>';
  2167. $links .= '<li class="'.($show == 'member_list' ? 'active' : '').'"><a href="group_waiting_list.php?id='.$group_id.'">'.
  2168. Display::return_icon('waiting_list.png', get_lang('Waiting list')).get_lang('Waiting list').'</a></li>';
  2169. $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
  2170. Display::return_icon('invitation_friend.png', get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
  2171. if (self::canLeave($group_info)) {
  2172. $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
  2173. Display::return_icon('group_leave.png', get_lang('Leave group')).get_lang('Leave group').'</a></li>';
  2174. }
  2175. break;
  2176. case GROUP_USER_PERMISSION_PENDING_INVITATION:
  2177. // $links .= '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('You have been invited to join now'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('You have been invited to join now').'</span></a></li>';
  2178. break;
  2179. case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
  2180. $relation_group_title = get_lang('Waiting for admin response');
  2181. break;
  2182. case GROUP_USER_PERMISSION_MODERATOR:
  2183. $relation_group_title = get_lang('I am a moderator');
  2184. //$links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="thickbox" title="'.get_lang('Compose message').'">'.Display::return_icon('compose_message.png', get_lang('Create thread'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('Create thread').'</span></a></li>';
  2185. //$links .= '<li><a href="groups.php?id='.$group_id.'">'. Display::return_icon('message_list.png', get_lang('Messages list'), array('hspace'=>'6')).'<span class="'.($show=='messages_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('Messages list').'</span></a></li>';
  2186. //$links .= '<li><a href="group_members.php?id='.$group_id.'">'. Display::return_icon('member_list.png', get_lang('Members list'), array('hspace'=>'6')).'<span class="'.($show=='member_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('Members list').'</span></a></li>';
  2187. if ($group_info['visibility'] == GROUP_PERMISSION_CLOSED) {
  2188. $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
  2189. Display::return_icon('waiting_list.png', get_lang('Waiting list')).get_lang('Waiting list').'</a></li>';
  2190. }
  2191. $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
  2192. Display::return_icon('invitation_friend.png', get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
  2193. if (self::canLeave($group_info)) {
  2194. $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
  2195. Display::return_icon('group_leave.png', get_lang('Leave group')).get_lang('Leave group').'</a></li>';
  2196. }
  2197. break;
  2198. case GROUP_USER_PERMISSION_HRM:
  2199. $relation_group_title = get_lang('I am a human resources manager');
  2200. $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="ajax" title="'.get_lang('Compose message').'" data-size="lg" data-title="'.get_lang('Compose message').'">'.
  2201. Display::return_icon('new-message.png', get_lang('Create thread')).get_lang('Create thread').'</a></li>';
  2202. $links .= '<li><a href="group_view.php?id='.$group_id.'">'.
  2203. Display::return_icon('message_list.png', get_lang('Messages list')).get_lang('Messages list').'</a></li>';
  2204. $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
  2205. Display::return_icon('invitation_friend.png', get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
  2206. $links .= '<li><a href="group_members.php?id='.$group_id.'">'.
  2207. Display::return_icon('member_list.png', get_lang('Members list')).get_lang('Members list').'</a></li>';
  2208. $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
  2209. Display::return_icon('delete_data.gif', get_lang('Leave group')).get_lang('Leave group').'</a></li>';
  2210. break;
  2211. default:
  2212. //$links .= '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('Join group'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('Join group').'</a></span></li>';
  2213. break;
  2214. }
  2215. if (!empty($links)) {
  2216. $list = '<ul class="nav nav-pills">';
  2217. $list .= $links;
  2218. $list .= '</ul>';
  2219. $html .= Display::panelCollapse(
  2220. get_lang('Social groups'),
  2221. $list,
  2222. 'sm-groups',
  2223. [],
  2224. 'groups-acordeon',
  2225. 'groups-collapse'
  2226. );
  2227. }
  2228. return $html;
  2229. }
  2230. /**
  2231. * @param int $group_id
  2232. * @param int $topic_id
  2233. */
  2234. public function delete_topic($group_id, $topic_id)
  2235. {
  2236. $table_message = Database::get_main_table(TABLE_MESSAGE);
  2237. $topic_id = (int) $topic_id;
  2238. $group_id = (int) $group_id;
  2239. $sql = "UPDATE $table_message SET
  2240. msg_status = 3
  2241. WHERE
  2242. group_id = $group_id AND
  2243. (id = '$topic_id' OR parent_id = $topic_id)
  2244. ";
  2245. Database::query($sql);
  2246. }
  2247. /**
  2248. * @param string $user_id
  2249. * @param string $relation_type
  2250. * @param bool $with_image
  2251. *
  2252. * @deprecated
  2253. *
  2254. * @return int
  2255. */
  2256. public function get_groups_by_user_count(
  2257. $user_id = '',
  2258. $relation_type = GROUP_USER_PERMISSION_READER,
  2259. $with_image = false
  2260. ) {
  2261. $table_group_rel_user = $this->usergroup_rel_user_table;
  2262. $tbl_group = $this->table;
  2263. $user_id = intval($user_id);
  2264. if ($relation_type == 0) {
  2265. $where_relation_condition = '';
  2266. } else {
  2267. $relation_type = intval($relation_type);
  2268. $where_relation_condition = "AND gu.relation_type = $relation_type ";
  2269. }
  2270. $sql = "SELECT count(g.id) as count
  2271. FROM $tbl_group g
  2272. INNER JOIN $table_group_rel_user gu
  2273. ON gu.usergroup_id = g.id
  2274. WHERE gu.user_id = $user_id $where_relation_condition ";
  2275. $result = Database::query($sql);
  2276. if (Database::num_rows($result) > 0) {
  2277. $row = Database::fetch_array($result, 'ASSOC');
  2278. return $row['count'];
  2279. }
  2280. return 0;
  2281. }
  2282. /**
  2283. * @param string $tag
  2284. * @param int $from
  2285. * @param int $number_of_items
  2286. *
  2287. * @return array
  2288. */
  2289. public function get_all_group_tags($tag, $from = 0, $number_of_items = 10, $getCount = false)
  2290. {
  2291. $group_table = $this->table;
  2292. $tag = Database::escape_string($tag);
  2293. $from = (int) $from;
  2294. $number_of_items = (int) $number_of_items;
  2295. $return = [];
  2296. $keyword = $tag;
  2297. $sql = 'SELECT g.id, g.name, g.description, g.url, g.picture ';
  2298. $urlCondition = '';
  2299. if ($this->getUseMultipleUrl()) {
  2300. $urlId = api_get_current_access_url_id();
  2301. $sql .= " FROM $this->table g
  2302. INNER JOIN $this->access_url_rel_usergroup a
  2303. ON (g.id = a.usergroup_id)";
  2304. $urlCondition = " AND access_url_id = $urlId ";
  2305. } else {
  2306. $sql .= " FROM $group_table g";
  2307. }
  2308. if (isset($keyword)) {
  2309. $sql .= " WHERE (
  2310. g.name LIKE '%".$keyword."%' OR
  2311. g.description LIKE '%".$keyword."%' OR
  2312. g.url LIKE '%".$keyword."%'
  2313. ) $urlCondition
  2314. ";
  2315. } else {
  2316. $sql .= " WHERE 1 = 1 $urlCondition ";
  2317. }
  2318. $direction = 'ASC';
  2319. if (!in_array($direction, ['ASC', 'DESC'])) {
  2320. $direction = 'ASC';
  2321. }
  2322. $from = (int) $from;
  2323. $number_of_items = (int) $number_of_items;
  2324. $sql .= " LIMIT $from, $number_of_items";
  2325. $res = Database::query($sql);
  2326. if (Database::num_rows($res) > 0) {
  2327. while ($row = Database::fetch_array($res, 'ASSOC')) {
  2328. if (!in_array($row['id'], $return)) {
  2329. $return[$row['id']] = $row;
  2330. }
  2331. }
  2332. }
  2333. return $return;
  2334. }
  2335. /**
  2336. * @param int $group_id
  2337. *
  2338. * @return array
  2339. */
  2340. public static function get_parent_groups($group_id)
  2341. {
  2342. $t_rel_group = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
  2343. $group_id = (int) $group_id;
  2344. $max_level = 10;
  2345. $select_part = 'SELECT ';
  2346. $cond_part = '';
  2347. for ($i = 1; $i <= $max_level; $i++) {
  2348. $rg_number = $i - 1;
  2349. if ($i == $max_level) {
  2350. $select_part .= "rg$rg_number.group_id as id_$rg_number ";
  2351. } else {
  2352. $select_part .= "rg$rg_number.group_id as id_$rg_number, ";
  2353. }
  2354. if ($i == 1) {
  2355. $cond_part .= "FROM $t_rel_group rg0
  2356. LEFT JOIN $t_rel_group rg$i
  2357. ON rg$rg_number.group_id = rg$i.subgroup_id ";
  2358. } else {
  2359. $cond_part .= " LEFT JOIN $t_rel_group rg$i
  2360. ON rg$rg_number.group_id = rg$i.subgroup_id ";
  2361. }
  2362. }
  2363. $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
  2364. $res = Database::query($sql);
  2365. $temp_arr = Database::fetch_array($res, 'NUM');
  2366. $toReturn = [];
  2367. if (is_array($temp_arr)) {
  2368. foreach ($temp_arr as $elt) {
  2369. if (isset($elt)) {
  2370. $toReturn[] = $elt;
  2371. }
  2372. }
  2373. }
  2374. return $toReturn;
  2375. }
  2376. /**
  2377. * Get the group member list by a user and his group role.
  2378. *
  2379. * @param int $userId The user ID
  2380. * @param int $relationType Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
  2381. * @param bool $includeSubgroupsUsers Optional. Whether include the users from subgroups
  2382. *
  2383. * @return array
  2384. */
  2385. public function getGroupUsersByUser(
  2386. $userId,
  2387. $relationType = GROUP_USER_PERMISSION_ADMIN,
  2388. $includeSubgroupsUsers = true
  2389. ) {
  2390. $userId = (int) $userId;
  2391. $groups = $this->get_groups_by_user($userId, $relationType);
  2392. $groupsId = array_keys($groups);
  2393. $subgroupsId = [];
  2394. $userIdList = [];
  2395. if ($includeSubgroupsUsers) {
  2396. foreach ($groupsId as $groupId) {
  2397. $subgroupsId = array_merge($subgroupsId, self::getGroupsByDepthLevel($groupId));
  2398. }
  2399. $groupsId = array_merge($groupsId, $subgroupsId);
  2400. }
  2401. $groupsId = array_unique($groupsId);
  2402. if (empty($groupsId)) {
  2403. return [];
  2404. }
  2405. foreach ($groupsId as $groupId) {
  2406. $groupUsers = $this->get_users_by_group($groupId);
  2407. if (empty($groupUsers)) {
  2408. continue;
  2409. }
  2410. foreach ($groupUsers as $member) {
  2411. if ($member['user_id'] == $userId) {
  2412. continue;
  2413. }
  2414. $userIdList[] = (int) $member['user_id'];
  2415. }
  2416. }
  2417. return array_unique($userIdList);
  2418. }
  2419. /**
  2420. * Get the subgroups ID from a group.
  2421. * The default $levels value is 10 considering it as a extensive level of depth.
  2422. *
  2423. * @param int $groupId The parent group ID
  2424. * @param int $levels The depth levels
  2425. *
  2426. * @return array The list of ID
  2427. */
  2428. public static function getGroupsByDepthLevel($groupId, $levels = 10)
  2429. {
  2430. $groups = [];
  2431. $groupId = (int) $groupId;
  2432. $groupTable = Database::get_main_table(TABLE_USERGROUP);
  2433. $groupRelGroupTable = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
  2434. $select = 'SELECT ';
  2435. $from = "FROM $groupTable g1 ";
  2436. for ($i = 1; $i <= $levels; $i++) {
  2437. $tableIndexNumber = $i;
  2438. $tableIndexJoinNumber = $i - 1;
  2439. $select .= "g$i.id as id_$i ";
  2440. $select .= $i != $levels ? ', ' : null;
  2441. if ($i == 1) {
  2442. $from .= " INNER JOIN $groupRelGroupTable gg0
  2443. ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
  2444. } else {
  2445. $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
  2446. $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
  2447. $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
  2448. $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
  2449. }
  2450. }
  2451. $result = Database::query("$select $from");
  2452. while ($item = Database::fetch_assoc($result)) {
  2453. foreach ($item as $myGroupId) {
  2454. if (!empty($myGroupId)) {
  2455. $groups[] = $myGroupId;
  2456. }
  2457. }
  2458. }
  2459. return array_map('intval', $groups);
  2460. }
  2461. /**
  2462. * Set a parent group.
  2463. *
  2464. * @param int $group_id
  2465. * @param int $parent_group_id if 0, we delete the parent_group association
  2466. * @param int $relation_type
  2467. *
  2468. * @return \Doctrine\DBAL\Statement
  2469. */
  2470. public function setParentGroup($group_id, $parent_group_id, $relation_type = 1)
  2471. {
  2472. $table = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
  2473. $group_id = (int) $group_id;
  2474. $parent_group_id = (int) $parent_group_id;
  2475. if ($parent_group_id == 0) {
  2476. $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
  2477. } else {
  2478. $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
  2479. $res = Database::query($sql);
  2480. if (Database::num_rows($res) == 0) {
  2481. $sql = "INSERT INTO $table SET
  2482. group_id = $parent_group_id,
  2483. subgroup_id = $group_id,
  2484. relation_type = $relation_type";
  2485. } else {
  2486. $sql = "UPDATE $table SET
  2487. group_id = $parent_group_id,
  2488. relation_type = $relation_type
  2489. WHERE subgroup_id = $group_id";
  2490. }
  2491. }
  2492. $res = Database::query($sql);
  2493. return $res;
  2494. }
  2495. /**
  2496. * Filter the groups/classes info to get a name list only.
  2497. *
  2498. * @param int $userId The user ID
  2499. * @param int $filterByType Optional. The type of group
  2500. *
  2501. * @return array
  2502. */
  2503. public function getNameListByUser($userId, $filterByType = null)
  2504. {
  2505. $userClasses = $this->getUserGroupListByUser($userId, $filterByType);
  2506. return array_column($userClasses, 'name');
  2507. }
  2508. /**
  2509. * Get the HTML necessary for display the groups/classes name list.
  2510. *
  2511. * @param int $userId The user ID
  2512. * @param int $filterByType Optional. The type of group
  2513. *
  2514. * @return string
  2515. */
  2516. public function getLabelsFromNameList($userId, $filterByType = null)
  2517. {
  2518. $groupsNameListParsed = $this->getNameListByUser($userId, $filterByType);
  2519. if (empty($groupsNameListParsed)) {
  2520. return '';
  2521. }
  2522. $nameList = '<ul class="list-unstyled">';
  2523. foreach ($groupsNameListParsed as $name) {
  2524. $nameList .= '<li>'.Display::span($name, ['class' => 'label label-info']).'</li>';
  2525. }
  2526. $nameList .= '</ul>';
  2527. return $nameList;
  2528. }
  2529. /**
  2530. * @param array $groupInfo
  2531. *
  2532. * @return bool
  2533. */
  2534. public static function canLeave($groupInfo)
  2535. {
  2536. return $groupInfo['allow_members_leave_group'] == 1 ? true : false;
  2537. }
  2538. /**
  2539. * Check permissions and blocks the page.
  2540. *
  2541. * @param array $userGroupInfo
  2542. * @param bool $checkAuthor
  2543. * @param bool $checkCourseIsAllow
  2544. */
  2545. public function protectScript($userGroupInfo = [], $checkAuthor = true, $checkCourseIsAllow = false)
  2546. {
  2547. api_block_anonymous_users();
  2548. if (api_is_platform_admin()) {
  2549. return true;
  2550. }
  2551. if ($checkCourseIsAllow) {
  2552. if (api_is_allowed_to_edit()) {
  2553. return true;
  2554. }
  2555. }
  2556. if ($this->allowTeachers() && api_is_teacher()) {
  2557. if ($checkAuthor && !empty($userGroupInfo)) {
  2558. if (isset($userGroupInfo['author_id']) && $userGroupInfo['author_id'] != api_get_user_id()) {
  2559. api_not_allowed(true);
  2560. }
  2561. }
  2562. return true;
  2563. } else {
  2564. api_protect_admin_script(true);
  2565. api_protect_limit_for_session_admin();
  2566. }
  2567. }
  2568. }