usergroup.lib.php 94 KB

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