usergroup.lib.php 95 KB

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