usergroup.lib.php 84 KB

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