usergroup.lib.php 85 KB

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