usergroup.lib.php 96 KB

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