usergroup.lib.php 97 KB

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