usergroup.lib.php 83 KB

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