usergroup.lib.php 93 KB

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