usergroup.lib.php 84 KB

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