usergroup.lib.php 83 KB

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