usergroup.lib.php 84 KB

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