usergroup.lib.php 97 KB

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