usergroup.lib.php 93 KB

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