usergroup.lib.php 86 KB

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