groupmanager.lib.php 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CGroupRelUser;
  4. /**
  5. * This library contains some functions for group-management.
  6. *
  7. * @author Bart Mollet
  8. *
  9. * @package chamilo.library
  10. *
  11. * @todo Add $course_code parameter to all functions. So this GroupManager can
  12. * be used outside a session.
  13. */
  14. class GroupManager
  15. {
  16. /* DEFAULT_GROUP_CATEGORY:
  17. When group categories aren't available (platform-setting),
  18. all groups are created in this 'dummy'-category*/
  19. const DEFAULT_GROUP_CATEGORY = 2;
  20. /**
  21. * infinite.
  22. */
  23. const INFINITE = 99999;
  24. /**
  25. * No limit on the number of users in a group.
  26. */
  27. const MEMBER_PER_GROUP_NO_LIMIT = 0;
  28. /**
  29. * No limit on the number of groups per user.
  30. */
  31. const GROUP_PER_MEMBER_NO_LIMIT = 0;
  32. /**
  33. * The tools of a group can have 3 states
  34. * - not available
  35. * - public
  36. * - private.
  37. */
  38. const TOOL_NOT_AVAILABLE = 0;
  39. const TOOL_PUBLIC = 1;
  40. const TOOL_PRIVATE = 2;
  41. const TOOL_PRIVATE_BETWEEN_USERS = 3;
  42. /**
  43. * Constants for the available group tools.
  44. */
  45. const GROUP_TOOL_FORUM = 0;
  46. const GROUP_TOOL_DOCUMENTS = 1;
  47. const GROUP_TOOL_CALENDAR = 2;
  48. const GROUP_TOOL_ANNOUNCEMENT = 3;
  49. const GROUP_TOOL_WORK = 4;
  50. const GROUP_TOOL_WIKI = 5;
  51. const GROUP_TOOL_CHAT = 6;
  52. const DOCUMENT_MODE_SHARE = 0; // By default
  53. const DOCUMENT_MODE_READ_ONLY = 1;
  54. const DOCUMENT_MODE_COLLABORATION = 2;
  55. /**
  56. * GroupManager constructor.
  57. */
  58. public function __construct()
  59. {
  60. }
  61. /**
  62. * @param int $courseId
  63. *
  64. * @return array
  65. */
  66. public static function get_groups($courseId = 0)
  67. {
  68. $table_group = Database::get_course_table(TABLE_GROUP);
  69. $courseId = !empty($courseId) ? (int) $courseId : api_get_course_int_id();
  70. $sql = "SELECT * FROM $table_group WHERE c_id = $courseId ";
  71. $result = Database::query($sql);
  72. return Database::store_result($result, 'ASSOC');
  73. }
  74. /**
  75. * Get list of groups for current course.
  76. *
  77. * @param int $categoryId The id of the category from which the groups are
  78. * requested
  79. * @param array $course_info Default is current course
  80. * @param int $status group status
  81. * @param int $sessionId
  82. * @param bool $getCount
  83. *
  84. * @return array an array with all information about the groups
  85. */
  86. public static function get_group_list(
  87. $categoryId = null,
  88. $course_info = [],
  89. $status = null,
  90. $sessionId = 0,
  91. $getCount = false
  92. ) {
  93. $course_info = empty($course_info) ? api_get_course_info() : $course_info;
  94. if (empty($course_info)) {
  95. return [];
  96. }
  97. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  98. $course_id = $course_info['real_id'];
  99. $table_group = Database::get_course_table(TABLE_GROUP);
  100. $select = ' g.id,
  101. g.iid,
  102. g.name,
  103. g.description,
  104. g.category_id,
  105. g.max_student maximum_number_of_members,
  106. g.secret_directory,
  107. g.self_registration_allowed,
  108. g.self_unregistration_allowed,
  109. g.session_id,
  110. g.status';
  111. if ($getCount) {
  112. $select = ' DISTINCT count(g.iid) as count ';
  113. }
  114. $sql = "SELECT
  115. $select
  116. FROM $table_group g
  117. WHERE 1 = 1 ";
  118. if (!is_null($categoryId)) {
  119. $sql .= " AND g.category_id = '".intval($categoryId)."' ";
  120. $session_condition = api_get_session_condition($sessionId);
  121. if (!empty($session_condition)) {
  122. $sql .= $session_condition;
  123. }
  124. } else {
  125. $session_condition = api_get_session_condition($sessionId, true);
  126. }
  127. if (!is_null($status)) {
  128. $sql .= " AND g.status = '".intval($status)."' ";
  129. }
  130. $sql .= " AND g.c_id = $course_id ";
  131. if (!empty($session_condition)) {
  132. $sql .= $session_condition;
  133. }
  134. $sql .= ' ORDER BY UPPER(g.name)';
  135. $result = Database::query($sql);
  136. if ($getCount) {
  137. $row = Database::fetch_array($result);
  138. return $row['count'];
  139. }
  140. $groups = [];
  141. while ($thisGroup = Database::fetch_array($result)) {
  142. $thisGroup['number_of_members'] = count(self::get_subscribed_users($thisGroup));
  143. if ($thisGroup['session_id'] != 0) {
  144. $sql = 'SELECT name FROM '.Database::get_main_table(TABLE_MAIN_SESSION).'
  145. WHERE id='.$thisGroup['session_id'];
  146. $rs_session = Database::query($sql);
  147. if (Database::num_rows($rs_session) > 0) {
  148. $thisGroup['session_name'] = Database::result($rs_session, 0, 0);
  149. }
  150. }
  151. $groups[] = $thisGroup;
  152. }
  153. return $groups;
  154. }
  155. /**
  156. * Create a group.
  157. *
  158. * @param string $name The name for this group
  159. * @param int $category_id
  160. * @param int $tutor The user-id of the group's tutor
  161. * @param int $places How many people can subscribe to the new group
  162. *
  163. * @return int
  164. */
  165. public static function create_group($name, $category_id, $tutor, $places)
  166. {
  167. $_course = api_get_course_info();
  168. $session_id = api_get_session_id();
  169. $course_id = $_course['real_id'];
  170. $currentCourseRepository = $_course['path'];
  171. $category = self::get_category($category_id);
  172. $places = (int) $places;
  173. // Default values
  174. $docState = self::TOOL_PRIVATE;
  175. $calendarState = self::TOOL_PRIVATE;
  176. $workState = self::TOOL_PRIVATE;
  177. $anonuncementState = self::TOOL_PRIVATE;
  178. $forumState = self::TOOL_PRIVATE;
  179. $wikiState = self::TOOL_PRIVATE;
  180. $chatState = self::TOOL_PRIVATE;
  181. $selfRegAllowed = 0;
  182. $selfUnregAllwoed = 0;
  183. $documentAccess = 0;
  184. if ($category) {
  185. if ($places == 0) {
  186. //if the amount of users per group is not filled in, use the setting from the category
  187. $places = $category['max_student'];
  188. } else {
  189. if ($places > $category['max_student'] && $category['max_student'] != 0) {
  190. $places = $category['max_student'];
  191. }
  192. }
  193. $docState = $category['doc_state'];
  194. $calendarState = $category['calendar_state'];
  195. $workState = $category['work_state'];
  196. $anonuncementState = $category['announcements_state'];
  197. $forumState = $category['forum_state'];
  198. $wikiState = $category['wiki_state'];
  199. $chatState = $category['chat_state'];
  200. $selfRegAllowed = $category['self_reg_allowed'];
  201. $selfUnregAllwoed = $category['self_unreg_allowed'];
  202. $documentAccess = isset($category['document_access']) ? $category['document_access'] : 0;
  203. }
  204. $allowDocumentAccess = api_get_configuration_value('group_document_access');
  205. $documentCondition = '';
  206. if ($allowDocumentAccess) {
  207. $documentAccess = (int) $documentAccess;
  208. $documentCondition = " document_access = $documentAccess, ";
  209. }
  210. $table_group = Database::get_course_table(TABLE_GROUP);
  211. $sql = "INSERT INTO $table_group SET
  212. c_id = $course_id,
  213. status = 1,
  214. category_id='".Database::escape_string($category_id)."',
  215. max_student = '".$places."',
  216. doc_state = '".$docState."',
  217. calendar_state = '".$calendarState."',
  218. work_state = '".$workState."',
  219. announcements_state = '".$anonuncementState."',
  220. forum_state = '".$forumState."',
  221. wiki_state = '".$wikiState."',
  222. chat_state = '".$chatState."',
  223. self_registration_allowed = '".$selfRegAllowed."',
  224. self_unregistration_allowed = '".$selfUnregAllwoed."',
  225. $documentCondition
  226. session_id='".$session_id."'";
  227. Database::query($sql);
  228. $lastId = Database::insert_id();
  229. if ($lastId) {
  230. $sql = "UPDATE $table_group SET id = iid WHERE iid = $lastId";
  231. Database::query($sql);
  232. $desired_dir_name = '/'.api_replace_dangerous_char($name).'_groupdocs';
  233. $my_path = api_get_path(SYS_COURSE_PATH).$currentCourseRepository.'/document';
  234. $newFolderData = create_unexisting_directory(
  235. $_course,
  236. api_get_user_id(),
  237. $session_id,
  238. $lastId,
  239. null,
  240. $my_path,
  241. $desired_dir_name,
  242. null,
  243. 1
  244. );
  245. $unique_name = $newFolderData['path'];
  246. /* Stores the directory path into the group table */
  247. $sql = "UPDATE $table_group SET
  248. name = '".Database::escape_string($name)."',
  249. secret_directory = '".$unique_name."'
  250. WHERE c_id = $course_id AND id ='".$lastId."'";
  251. Database::query($sql);
  252. // create a forum if needed
  253. if ($forumState >= 0) {
  254. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  255. $forum_categories = get_forum_categories();
  256. if (empty($forum_categories)) {
  257. $categoryParam = [
  258. 'forum_category_title' => get_lang('GroupForums'),
  259. ];
  260. store_forumcategory($categoryParam);
  261. $forum_categories = get_forum_categories();
  262. }
  263. $counter = 0;
  264. foreach ($forum_categories as $key => $value) {
  265. if ($counter == 0) {
  266. $forum_category_id = $key;
  267. }
  268. $counter++;
  269. }
  270. // A sanity check.
  271. if (empty($forum_category_id)) {
  272. $forum_category_id = 0;
  273. }
  274. $values = [];
  275. $values['forum_title'] = $name;
  276. $values['group_id'] = $lastId;
  277. $values['forum_category'] = $forum_category_id;
  278. $values['allow_anonymous_group']['allow_anonymous'] = 0;
  279. $values['students_can_edit_group']['students_can_edit'] = 0;
  280. $values['approval_direct_group']['approval_direct'] = 0;
  281. $values['allow_attachments_group']['allow_attachments'] = 1;
  282. $values['allow_new_threads_group']['allow_new_threads'] = 1;
  283. $values['default_view_type_group']['default_view_type'] = api_get_setting('default_forum_view');
  284. $values['group_forum'] = $lastId;
  285. if ($forumState == '1') {
  286. $values['public_private_group_forum_group']['public_private_group_forum'] = 'public';
  287. } elseif ($forumState == '2') {
  288. $values['public_private_group_forum_group']['public_private_group_forum'] = 'private';
  289. } elseif ($forumState == '0') {
  290. $values['public_private_group_forum_group']['public_private_group_forum'] = 'unavailable';
  291. }
  292. store_forum($values);
  293. }
  294. }
  295. return $lastId;
  296. }
  297. /**
  298. * Create subgroups.
  299. * This function creates new groups based on an existing group. It will
  300. * create the specified number of groups and fill those groups with users
  301. * from the base group.
  302. *
  303. * @param int $group_id the group from which subgroups have to be created
  304. * @param int $number_of_groups The number of groups that have to be created
  305. */
  306. public static function create_subgroups($group_id, $number_of_groups)
  307. {
  308. $courseId = api_get_course_int_id();
  309. $table_group = Database::get_course_table(TABLE_GROUP);
  310. $category_id = self::create_category(
  311. get_lang('Subgroups'),
  312. '',
  313. self::TOOL_PRIVATE,
  314. self::TOOL_PRIVATE,
  315. 0,
  316. 0,
  317. 1,
  318. 1
  319. );
  320. $users = self::get_users($group_id);
  321. $group_ids = [];
  322. for ($group_nr = 1; $group_nr <= $number_of_groups; $group_nr++) {
  323. $group_ids[] = self::create_group(
  324. get_lang('Subgroup').' '.$group_nr,
  325. $category_id,
  326. 0,
  327. 0
  328. );
  329. }
  330. $members = [];
  331. foreach ($users as $index => $user_id) {
  332. $groupId = $group_ids[$index % $number_of_groups];
  333. $groupInfo = self::get_group_properties($groupId);
  334. self::subscribe_users(
  335. $user_id,
  336. $groupInfo
  337. );
  338. $members[$group_ids[$groupId]]++;
  339. }
  340. foreach ($members as $group_id => $places) {
  341. $sql = "UPDATE $table_group SET max_student = $places
  342. WHERE c_id = $courseId AND id = $group_id";
  343. Database::query($sql);
  344. }
  345. }
  346. /**
  347. * Create a group for every class subscribed to the current course.
  348. *
  349. * @param int $categoryId The category in which the groups should be created
  350. *
  351. * @return array
  352. */
  353. public static function create_class_groups($categoryId)
  354. {
  355. $options['where'] = [' usergroup.course_id = ? ' => api_get_course_int_id()];
  356. $obj = new UserGroup();
  357. $classes = $obj->getUserGroupInCourse($options);
  358. $group_ids = [];
  359. foreach ($classes as $class) {
  360. $userList = $obj->get_users_by_usergroup($class['id']);
  361. $groupId = self::create_group(
  362. $class['name'],
  363. $categoryId,
  364. 0,
  365. null
  366. );
  367. if ($groupId) {
  368. $groupInfo = self::get_group_properties($groupId);
  369. self::subscribe_users($userList, $groupInfo);
  370. $group_ids[] = $groupId;
  371. }
  372. }
  373. return $group_ids;
  374. }
  375. /**
  376. * Deletes groups and their data.
  377. *
  378. * @author Christophe Gesche <christophe.gesche@claroline.net>
  379. * @author Hugues Peeters <hugues.peeters@claroline.net>
  380. * @author Bart Mollet
  381. *
  382. * @param array $groupInfo iid
  383. * @param string $course_code Default is current course
  384. *
  385. * @return int - number of groups deleted
  386. */
  387. public static function deleteGroup($groupInfo, $course_code = null)
  388. {
  389. if (empty($groupInfo['iid'])) {
  390. return false;
  391. }
  392. $course_info = api_get_course_info($course_code);
  393. if (empty($course_info)) {
  394. return false;
  395. }
  396. $course_id = $course_info['real_id'];
  397. // Database table definitions
  398. $group_table = Database::get_course_table(TABLE_GROUP);
  399. $forum_table = Database::get_course_table(TABLE_FORUM);
  400. $groupInfo = self::get_group_properties($groupInfo['iid'], true);
  401. if ($groupInfo) {
  402. $groupIid = $groupInfo['iid'];
  403. $groupId = $groupInfo['id'];
  404. // Unsubscribe all users
  405. self::unsubscribe_all_users($groupInfo);
  406. self::unsubscribe_all_tutors($groupInfo);
  407. if (!empty($groupInfo['secret_directory'])) {
  408. $directory = $groupInfo['secret_directory'];
  409. // move group-documents to garbage
  410. $source_directory = api_get_path(SYS_COURSE_PATH).$course_info['path']."/document".$directory;
  411. // File to renamed
  412. $destination_dir = api_get_path(SYS_COURSE_PATH).$course_info['path']."/document".$directory.'_DELETED_'.$groupInfo['id'];
  413. //Deleting from document tool
  414. DocumentManager::delete_document(
  415. $course_info,
  416. $directory,
  417. $source_directory
  418. );
  419. if (file_exists($source_directory)) {
  420. if (api_get_setting('permanently_remove_deleted_files') === 'true') {
  421. // Delete
  422. my_delete($source_directory);
  423. } else {
  424. // Rename
  425. rename($source_directory, $destination_dir);
  426. }
  427. }
  428. }
  429. $sql = "DELETE FROM $forum_table
  430. WHERE c_id = $course_id AND forum_of_group = $groupId ";
  431. Database::query($sql);
  432. // Delete item properties of this group.
  433. // to_group_id is related to c_group_info.iid
  434. $itemPropertyTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
  435. $sql = "DELETE FROM $itemPropertyTable
  436. WHERE c_id = $course_id AND to_group_id = $groupIid ";
  437. Database::query($sql);
  438. // delete the groups
  439. $sql = "DELETE FROM $group_table
  440. WHERE c_id = $course_id AND iid = $groupIid ";
  441. Database::query($sql);
  442. }
  443. return true;
  444. }
  445. /**
  446. * Function needed only when deleting a course, in order to be sure that all group ids are deleted.
  447. *
  448. * @param int $courseId
  449. *
  450. * @return bool
  451. */
  452. public static function deleteAllGroupsFromCourse($courseId)
  453. {
  454. $courseId = (int) $courseId;
  455. if (empty($courseId)) {
  456. return false;
  457. }
  458. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  459. $sql = "SELECT iid FROM $table
  460. WHERE c_id = $courseId ";
  461. Database::query($sql);
  462. // Database table definitions
  463. $table = Database::get_course_table(TABLE_GROUP_USER);
  464. $sql = "DELETE FROM $table
  465. WHERE c_id = $courseId";
  466. Database::query($sql);
  467. $table = Database::get_course_table(TABLE_GROUP_TUTOR);
  468. $sql = "DELETE FROM $table
  469. WHERE c_id = $courseId";
  470. Database::query($sql);
  471. $groupTable = Database::get_course_table(TABLE_GROUP);
  472. $sql = "DELETE FROM $groupTable
  473. WHERE c_id = $courseId";
  474. Database::query($sql);
  475. return true;
  476. }
  477. /**
  478. * Get group properties.
  479. *
  480. * @param int $group_id the group from which properties are requested
  481. * @param bool $useIid
  482. *
  483. * @return array All properties. Array-keys are:
  484. * name, tutor_id, description, maximum_number_of_students,
  485. * directory and visibility of tools
  486. */
  487. public static function get_group_properties($group_id, $useIid = false)
  488. {
  489. $course_id = api_get_course_int_id();
  490. $group_id = (int) $group_id;
  491. if (empty($group_id)) {
  492. return null;
  493. }
  494. $table_group = Database::get_course_table(TABLE_GROUP);
  495. $sql = "SELECT * FROM $table_group
  496. WHERE c_id = $course_id AND id = ".$group_id;
  497. if ($useIid) {
  498. $sql = "SELECT * FROM $table_group
  499. WHERE c_id = $course_id AND iid = ".$group_id;
  500. }
  501. $db_result = Database::query($sql);
  502. $db_object = Database::fetch_object($db_result);
  503. $result = [];
  504. if ($db_object) {
  505. $result['id'] = $db_object->id;
  506. $result['iid'] = $db_object->iid;
  507. $result['name'] = $db_object->name;
  508. $result['status'] = $db_object->status;
  509. $result['description'] = $db_object->description;
  510. $result['maximum_number_of_students'] = $db_object->max_student;
  511. $result['max_student'] = $db_object->max_student;
  512. $result['doc_state'] = $db_object->doc_state;
  513. $result['work_state'] = $db_object->work_state;
  514. $result['calendar_state'] = $db_object->calendar_state;
  515. $result['announcements_state'] = $db_object->announcements_state;
  516. $result['forum_state'] = $db_object->forum_state;
  517. $result['wiki_state'] = $db_object->wiki_state;
  518. $result['chat_state'] = $db_object->chat_state;
  519. $result['directory'] = $db_object->secret_directory;
  520. $result['self_registration_allowed'] = $db_object->self_registration_allowed;
  521. $result['self_unregistration_allowed'] = $db_object->self_unregistration_allowed;
  522. $result['count_users'] = count(
  523. self::get_subscribed_users($result)
  524. );
  525. $result['count_tutor'] = count(
  526. self::get_subscribed_tutors($result)
  527. );
  528. $result['count_all'] = $result['count_users'] + $result['count_tutor'];
  529. $result['document_access'] = isset($db_object->document_access) ? $db_object->document_access : self::DOCUMENT_MODE_SHARE;
  530. }
  531. return $result;
  532. }
  533. /**
  534. * @param string $name
  535. * @param string $courseCode
  536. * @param int $sessionId
  537. *
  538. * @return array
  539. */
  540. public static function getGroupByName($name, $courseCode = null, $sessionId = 0)
  541. {
  542. $name = trim($name);
  543. if (empty($name)) {
  544. return [];
  545. }
  546. $course_info = api_get_course_info($courseCode);
  547. $course_id = $course_info['real_id'];
  548. $name = Database::escape_string($name);
  549. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  550. $sessionCondition = api_get_session_condition($sessionId);
  551. $table = Database::get_course_table(TABLE_GROUP);
  552. $sql = "SELECT * FROM $table
  553. WHERE
  554. c_id = $course_id AND
  555. name = '$name'
  556. $sessionCondition
  557. LIMIT 1";
  558. $res = Database::query($sql);
  559. $group = [];
  560. if (Database::num_rows($res)) {
  561. $group = Database::fetch_array($res, 'ASSOC');
  562. }
  563. return $group;
  564. }
  565. /**
  566. * @param int $courseId
  567. * @param int $categoryId
  568. * @param string $name
  569. *
  570. * @return array
  571. */
  572. public static function getGroupListFilterByName($name, $categoryId, $courseId)
  573. {
  574. $name = trim($name);
  575. if (empty($name)) {
  576. return [];
  577. }
  578. $name = Database::escape_string($name);
  579. $courseId = (int) $courseId;
  580. $table_group = Database::get_course_table(TABLE_GROUP);
  581. $sql = "SELECT * FROM $table_group
  582. WHERE c_id = $courseId AND name LIKE '%$name%'";
  583. if (!empty($categoryId)) {
  584. $categoryId = intval($categoryId);
  585. $sql .= " AND category_id = $categoryId";
  586. }
  587. $sql .= " ORDER BY name";
  588. $result = Database::query($sql);
  589. return Database::store_result($result, 'ASSOC');
  590. }
  591. /**
  592. * Set group properties
  593. * Changes the group's properties.
  594. *
  595. * @param int Group Id
  596. * @param string Group name
  597. * @param string Group description
  598. * @param int Max number of students in group
  599. * @param int Document tool's visibility (0=none,1=private,2=public)
  600. * @param int Work tool's visibility (0=none,1=private,2=public)
  601. * @param int Calendar tool's visibility (0=none,1=private,2=public)
  602. * @param int Announcement tool's visibility (0=none,1=private,2=public)
  603. * @param int Forum tool's visibility (0=none,1=private,2=public)
  604. * @param int Wiki tool's visibility (0=none,1=private,2=public)
  605. * @param int Chat tool's visibility (0=none,1=private,2=public)
  606. * @param bool Whether self registration is allowed or not
  607. * @param bool Whether self unregistration is allowed or not
  608. * @param int $categoryId
  609. * @param int $documentAccess
  610. *
  611. * @return bool TRUE if properties are successfully changed, false otherwise
  612. */
  613. public static function set_group_properties(
  614. $group_id,
  615. $name,
  616. $description,
  617. $maximum_number_of_students,
  618. $doc_state,
  619. $work_state,
  620. $calendar_state,
  621. $announcements_state,
  622. $forum_state,
  623. $wiki_state,
  624. $chat_state,
  625. $selfRegistrationAllowed,
  626. $selfUnRegistrationAllowed,
  627. $categoryId = null,
  628. $documentAccess = 0
  629. ) {
  630. $table_group = Database::get_course_table(TABLE_GROUP);
  631. $table_forum = Database::get_course_table(TABLE_FORUM);
  632. $categoryId = (int) $categoryId;
  633. $group_id = (int) $group_id;
  634. $courseId = api_get_course_int_id();
  635. $allowDocumentAccess = api_get_configuration_value('group_document_access');
  636. $documentCondition = '';
  637. if ($allowDocumentAccess) {
  638. $documentAccess = (int) $documentAccess;
  639. $documentCondition = " document_access = $documentAccess, ";
  640. }
  641. $sql = "UPDATE ".$table_group." SET
  642. name='".Database::escape_string(trim($name))."',
  643. doc_state = '".Database::escape_string($doc_state)."',
  644. work_state = '".Database::escape_string($work_state)."',
  645. calendar_state = '".Database::escape_string($calendar_state)."',
  646. announcements_state = '".Database::escape_string($announcements_state)."',
  647. forum_state = '".Database::escape_string($forum_state)."',
  648. wiki_state = '".Database::escape_string($wiki_state)."',
  649. chat_state = '".Database::escape_string($chat_state)."',
  650. description ='".Database::escape_string(trim($description))."',
  651. max_student = '".Database::escape_string($maximum_number_of_students)."',
  652. self_registration_allowed = '".Database::escape_string($selfRegistrationAllowed)."',
  653. self_unregistration_allowed = '".Database::escape_string($selfUnRegistrationAllowed)."',
  654. $documentCondition
  655. category_id = ".$categoryId."
  656. WHERE c_id = $courseId AND id=".$group_id;
  657. $result = Database::query($sql);
  658. /* Here we are updating a field in the table forum_forum that perhaps
  659. duplicates the table group_info.forum_state cvargas*/
  660. $forum_state = (int) $forum_state;
  661. $sql2 = "UPDATE ".$table_forum." SET ";
  662. if ($forum_state === 1) {
  663. $sql2 .= " forum_group_public_private='public' ";
  664. } elseif ($forum_state === 2) {
  665. $sql2 .= " forum_group_public_private='private' ";
  666. } elseif ($forum_state === 0) {
  667. $sql2 .= " forum_group_public_private='unavailable' ";
  668. }
  669. $sql2 .= " WHERE c_id = $courseId AND forum_of_group=".$group_id;
  670. Database::query($sql2);
  671. return $result;
  672. }
  673. /**
  674. * Get the total number of groups for the current course.
  675. *
  676. * @return int the number of groups for the current course
  677. */
  678. public static function get_number_of_groups()
  679. {
  680. $courseId = api_get_course_int_id();
  681. $table = Database::get_course_table(TABLE_GROUP);
  682. $sql = "SELECT COUNT(id) AS number_of_groups
  683. FROM $table
  684. WHERE c_id = $courseId ";
  685. $res = Database::query($sql);
  686. $obj = Database::fetch_object($res);
  687. return $obj->number_of_groups;
  688. }
  689. /**
  690. * Get all categories.
  691. *
  692. * @param string $course_code The course (default = current course)
  693. *
  694. * @return array
  695. */
  696. public static function get_categories($course_code = null)
  697. {
  698. $course_info = api_get_course_info($course_code);
  699. $courseId = $course_info['real_id'];
  700. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  701. $sql = "SELECT * FROM $table
  702. WHERE c_id = $courseId
  703. ORDER BY display_order";
  704. $res = Database::query($sql);
  705. $cats = [];
  706. while ($cat = Database::fetch_array($res)) {
  707. $cats[] = $cat;
  708. }
  709. return $cats;
  710. }
  711. /**
  712. * Get a group category.
  713. *
  714. * @param int $id The category id
  715. * @param string $course_code The course (default = current course)
  716. *
  717. * @return array
  718. */
  719. public static function get_category($id, $course_code = null)
  720. {
  721. if (empty($id)) {
  722. return [];
  723. }
  724. $courseInfo = api_get_course_info($course_code);
  725. $courseId = $courseInfo['real_id'];
  726. $id = intval($id);
  727. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  728. $sql = "SELECT * FROM $table
  729. WHERE c_id = $courseId AND id = $id
  730. LIMIT 1";
  731. $res = Database::query($sql);
  732. return Database::fetch_array($res);
  733. }
  734. /**
  735. * Get a group category.
  736. *
  737. * @param string $title
  738. * @param string $course_code The course (default = current course)
  739. *
  740. * @return array
  741. */
  742. public static function getCategoryByTitle($title, $course_code = null)
  743. {
  744. $title = trim($title);
  745. if (empty($title)) {
  746. return [];
  747. }
  748. $course_info = api_get_course_info($course_code);
  749. $courseId = $course_info['real_id'];
  750. $title = Database::escape_string($title);
  751. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  752. $sql = "SELECT * FROM $table
  753. WHERE c_id = $courseId AND title = '$title'
  754. LIMIT 1";
  755. $res = Database::query($sql);
  756. $category = [];
  757. if (Database::num_rows($res)) {
  758. $category = Database::fetch_array($res, 'ASSOC');
  759. }
  760. return $category;
  761. }
  762. /**
  763. * Get the unique category of a given group.
  764. *
  765. * @param int $group_id The iid of the group
  766. * @param string $course_code The course in which the group is (default =
  767. * current course)
  768. *
  769. * @return array The category
  770. */
  771. public static function get_category_from_group($group_id, $course_code = '')
  772. {
  773. $table_group = Database::get_course_table(TABLE_GROUP);
  774. $table_group_cat = Database::get_course_table(TABLE_GROUP_CATEGORY);
  775. $group_id = intval($group_id);
  776. if (empty($group_id)) {
  777. return [];
  778. }
  779. $course_info = api_get_course_info($course_code);
  780. if (empty($course_info)) {
  781. return false;
  782. }
  783. $courseId = $course_info['real_id'];
  784. $sql = "SELECT gc.* FROM $table_group_cat gc, $table_group g
  785. WHERE
  786. gc.c_id = $courseId AND
  787. g.c_id = $courseId AND
  788. gc.id = g.category_id AND
  789. g.iid = $group_id
  790. LIMIT 1";
  791. $res = Database::query($sql);
  792. $cat = [];
  793. if (Database::num_rows($res)) {
  794. $cat = Database::fetch_array($res);
  795. }
  796. return $cat;
  797. }
  798. /**
  799. * Delete a group category.
  800. *
  801. * @param int $cat_id The id of the category to delete
  802. * @param string $course_code The code in which the category should be
  803. * deleted (default = current course)
  804. *
  805. * @return bool
  806. */
  807. public static function delete_category($cat_id, $course_code = '')
  808. {
  809. $course_info = api_get_course_info($course_code);
  810. if (empty($course_info)) {
  811. return false;
  812. }
  813. $course_id = $course_info['real_id'];
  814. $table_group = Database::get_course_table(TABLE_GROUP);
  815. $table_group_cat = Database::get_course_table(TABLE_GROUP_CATEGORY);
  816. $cat_id = intval($cat_id);
  817. $sql = "SELECT iid FROM $table_group
  818. WHERE c_id = $course_id AND category_id='".$cat_id."'";
  819. $res = Database::query($sql);
  820. if (Database::num_rows($res) > 0) {
  821. while ($group = Database::fetch_object($res)) {
  822. // Delete all groups in category
  823. /*$groupInfo = self::get_group_properties($group->iid, true);
  824. self::deleteGroup($groupInfo, $course_code);
  825. */
  826. // Set the category to NULL to avoid losing groups in sessions.
  827. $sql = "UPDATE $table_group SET category_id = NULL WHERE iid = ".$group->iid;
  828. Database::query($sql);
  829. }
  830. }
  831. $sql = "DELETE FROM $table_group_cat
  832. WHERE c_id = $course_id AND id='".$cat_id."'";
  833. Database::query($sql);
  834. return true;
  835. }
  836. /**
  837. * Create group category.
  838. *
  839. * @param string $title The title of the new category
  840. * @param string $description The description of the new category
  841. * @param int $doc_state
  842. * @param int $work_state
  843. * @param int $calendar_state
  844. * @param int $announcements_state
  845. * @param int $forum_state
  846. * @param int $wiki_state
  847. * @param int $chat_state
  848. * @param int $selfRegistrationAllowed allow users to self register
  849. * @param int $selfUnRegistrationAllowed allow user to self unregister
  850. * @param int $maximum_number_of_students
  851. * @param int $groups_per_user
  852. * @param int $documentAccess document access
  853. *
  854. * @return mixed
  855. */
  856. public static function create_category(
  857. $title,
  858. $description,
  859. $doc_state,
  860. $work_state,
  861. $calendar_state,
  862. $announcements_state,
  863. $forum_state,
  864. $wiki_state,
  865. $chat_state = 1,
  866. $selfRegistrationAllowed = 0,
  867. $selfUnRegistrationAllowed = 0,
  868. $maximum_number_of_students = 8,
  869. $groups_per_user = 0,
  870. $documentAccess = 0
  871. ) {
  872. if (empty($title)) {
  873. return false;
  874. }
  875. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  876. $course_id = api_get_course_int_id();
  877. $sql = "SELECT MAX(display_order)+1 as new_order
  878. FROM $table
  879. WHERE c_id = $course_id ";
  880. $res = Database::query($sql);
  881. $obj = Database::fetch_object($res);
  882. if (!isset($obj->new_order)) {
  883. $obj->new_order = 1;
  884. }
  885. $params = [
  886. 'c_id' => $course_id,
  887. 'title' => $title,
  888. 'display_order' => $obj->new_order,
  889. 'description' => $description,
  890. 'doc_state' => $doc_state,
  891. 'work_state' => $work_state,
  892. 'calendar_state' => $calendar_state,
  893. 'announcements_state' => $announcements_state,
  894. 'forum_state' => $forum_state,
  895. 'wiki_state' => $wiki_state,
  896. 'chat_state' => $chat_state,
  897. 'groups_per_user' => $groups_per_user,
  898. 'self_reg_allowed' => $selfRegistrationAllowed,
  899. 'self_unreg_allowed' => $selfUnRegistrationAllowed,
  900. 'max_student' => $maximum_number_of_students,
  901. ];
  902. $allowDocumentAccess = api_get_configuration_value('group_category_document_access');
  903. if ($allowDocumentAccess) {
  904. $params['document_access'] = $documentAccess;
  905. }
  906. $categoryId = Database::insert($table, $params);
  907. if ($categoryId) {
  908. $sql = "UPDATE $table SET id = iid
  909. WHERE iid = $categoryId";
  910. Database::query($sql);
  911. return $categoryId;
  912. }
  913. return false;
  914. }
  915. /**
  916. * Update group category.
  917. *
  918. * @param int $id
  919. * @param string $title
  920. * @param string $description
  921. * @param $doc_state
  922. * @param $work_state
  923. * @param $calendar_state
  924. * @param $announcements_state
  925. * @param $forum_state
  926. * @param $wiki_state
  927. * @param $chat_state
  928. * @param $selfRegistrationAllowed
  929. * @param $selfUnRegistrationAllowed
  930. * @param $maximum_number_of_students
  931. * @param $groups_per_user
  932. * @param $documentAccess
  933. */
  934. public static function update_category(
  935. $id,
  936. $title,
  937. $description,
  938. $doc_state,
  939. $work_state,
  940. $calendar_state,
  941. $announcements_state,
  942. $forum_state,
  943. $wiki_state,
  944. $chat_state,
  945. $selfRegistrationAllowed,
  946. $selfUnRegistrationAllowed,
  947. $maximum_number_of_students,
  948. $groups_per_user,
  949. $documentAccess
  950. ) {
  951. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  952. $id = (int) $id;
  953. $courseId = api_get_course_int_id();
  954. $allowDocumentAccess = api_get_configuration_value('group_category_document_access');
  955. $documentCondition = '';
  956. if ($allowDocumentAccess) {
  957. $documentAccess = (int) $documentAccess;
  958. $documentCondition = " document_access = $documentAccess, ";
  959. }
  960. $sql = "UPDATE ".$table." SET
  961. title='".Database::escape_string($title)."',
  962. description='".Database::escape_string($description)."',
  963. doc_state = '".Database::escape_string($doc_state)."',
  964. work_state = '".Database::escape_string($work_state)."',
  965. calendar_state = '".Database::escape_string($calendar_state)."',
  966. announcements_state = '".Database::escape_string($announcements_state)."',
  967. forum_state = '".Database::escape_string($forum_state)."',
  968. wiki_state = '".Database::escape_string($wiki_state)."',
  969. chat_state = '".Database::escape_string($chat_state)."',
  970. groups_per_user = '".Database::escape_string($groups_per_user)."',
  971. self_reg_allowed = '".Database::escape_string($selfRegistrationAllowed)."',
  972. self_unreg_allowed = '".Database::escape_string($selfUnRegistrationAllowed)."',
  973. $documentCondition
  974. max_student = ".intval($maximum_number_of_students)."
  975. WHERE c_id = $courseId AND id = $id";
  976. Database::query($sql);
  977. // Updating all groups inside this category
  978. $groups = self::get_group_list($id);
  979. if (!empty($groups)) {
  980. foreach ($groups as $group) {
  981. self::set_group_properties(
  982. $group['id'],
  983. $group['name'],
  984. $group['description'],
  985. $maximum_number_of_students,
  986. $doc_state,
  987. $work_state,
  988. $calendar_state,
  989. $announcements_state,
  990. $forum_state,
  991. $wiki_state,
  992. $chat_state,
  993. $selfRegistrationAllowed,
  994. $selfUnRegistrationAllowed,
  995. $id,
  996. $documentAccess
  997. );
  998. }
  999. }
  1000. }
  1001. /**
  1002. * Returns the number of groups of the user with the greatest number of
  1003. * subscriptions in the given category.
  1004. */
  1005. public static function get_current_max_groups_per_user(
  1006. $category_id = null,
  1007. $course_code = null
  1008. ) {
  1009. $course_info = api_get_course_info($course_code);
  1010. $group_table = Database::get_course_table(TABLE_GROUP);
  1011. $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
  1012. $sql = 'SELECT COUNT(gu.group_id) AS current_max
  1013. FROM '.$group_user_table.' gu, '.$group_table.' g
  1014. WHERE g.c_id = '.$course_info['real_id'].'
  1015. AND gu.c_id = g.c_id
  1016. AND gu.group_id = g.iid ';
  1017. if ($category_id != null) {
  1018. $category_id = intval($category_id);
  1019. $sql .= ' AND g.category_id = '.$category_id;
  1020. }
  1021. $sql .= ' GROUP BY gu.user_id ORDER BY current_max DESC LIMIT 1';
  1022. $res = Database::query($sql);
  1023. $obj = Database::fetch_object($res);
  1024. return $obj->current_max;
  1025. }
  1026. /**
  1027. * Swaps the display-order of two categories.
  1028. *
  1029. * @param int $id1 The id of the first category
  1030. * @param int $id2 The id of the second category
  1031. */
  1032. public static function swap_category_order($id1, $id2)
  1033. {
  1034. $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
  1035. $id1 = intval($id1);
  1036. $id2 = intval($id2);
  1037. $course_id = api_get_course_int_id();
  1038. $sql = "SELECT id, display_order FROM $table
  1039. WHERE id IN ($id1,$id2) AND c_id = $course_id ";
  1040. $res = Database::query($sql);
  1041. $cat1 = Database::fetch_object($res);
  1042. $cat2 = Database::fetch_object($res);
  1043. if ($cat1 && $cat2) {
  1044. $sql = "UPDATE $table SET display_order=$cat2->display_order
  1045. WHERE id = $cat1->id AND c_id = $course_id ";
  1046. Database::query($sql);
  1047. $sql = "UPDATE $table SET display_order=$cat1->display_order
  1048. WHERE id = $cat2->id AND c_id = $course_id ";
  1049. Database::query($sql);
  1050. }
  1051. }
  1052. /**
  1053. * Get all users from a given group.
  1054. *
  1055. * @param int $group_id The group
  1056. * @param bool $load_extra_info
  1057. * @param int $start
  1058. * @param int $limit
  1059. * @param bool $getCount
  1060. * @param int $courseId
  1061. * @param $column
  1062. * @param $direction
  1063. *
  1064. * @return array list of user id
  1065. */
  1066. public static function get_users(
  1067. $group_id,
  1068. $load_extra_info = false,
  1069. $start = null,
  1070. $limit = null,
  1071. $getCount = false,
  1072. $courseId = null,
  1073. $column = null,
  1074. $direction = null
  1075. ) {
  1076. $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
  1077. $groupTable = Database::get_course_table(TABLE_GROUP);
  1078. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1079. $group_id = intval($group_id);
  1080. if (empty($courseId)) {
  1081. $courseId = api_get_course_int_id();
  1082. } else {
  1083. $courseId = intval($courseId);
  1084. }
  1085. $select = " SELECT u.id, firstname, lastname ";
  1086. if ($getCount) {
  1087. $select = " SELECT count(u.id) count";
  1088. }
  1089. $sql = "$select
  1090. FROM $group_user_table gu
  1091. INNER JOIN $groupTable g
  1092. ON (gu.group_id = g.id and g.c_id = gu.c_id)
  1093. INNER JOIN $user_table u
  1094. ON (u.id = gu.user_id)
  1095. WHERE
  1096. gu.c_id = $courseId AND
  1097. g.id = $group_id";
  1098. if (!empty($column) && !empty($direction)) {
  1099. $column = Database::escape_string($column, null, false);
  1100. $direction = ($direction == 'ASC' ? 'ASC' : 'DESC');
  1101. $sql .= " ORDER BY $column $direction";
  1102. }
  1103. if (!empty($start) && !empty($limit)) {
  1104. $start = intval($start);
  1105. $limit = intval($limit);
  1106. $sql .= " LIMIT $start, $limit";
  1107. }
  1108. $res = Database::query($sql);
  1109. $users = [];
  1110. while ($obj = Database::fetch_object($res)) {
  1111. if ($getCount) {
  1112. return $obj->count;
  1113. break;
  1114. }
  1115. if ($load_extra_info) {
  1116. $users[] = api_get_user_info($obj->id);
  1117. } else {
  1118. $users[] = $obj->id;
  1119. }
  1120. }
  1121. return $users;
  1122. }
  1123. /**
  1124. * @param int $group_id id
  1125. *
  1126. * @return array
  1127. */
  1128. public static function getStudentsAndTutors($group_id)
  1129. {
  1130. $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
  1131. $tutor_user_table = Database::get_course_table(TABLE_GROUP_TUTOR);
  1132. $groupTable = Database::get_course_table(TABLE_GROUP);
  1133. $course_id = api_get_course_int_id();
  1134. $group_id = intval($group_id);
  1135. $sql = "SELECT user_id
  1136. FROM $group_user_table gu
  1137. INNER JOIN $groupTable g
  1138. ON (gu.group_id = g.iid and g.c_id = gu.c_id)
  1139. WHERE gu.c_id = $course_id AND g.id = $group_id";
  1140. $res = Database::query($sql);
  1141. $users = [];
  1142. while ($obj = Database::fetch_object($res)) {
  1143. $users[] = api_get_user_info($obj->user_id);
  1144. }
  1145. $sql = "SELECT user_id
  1146. FROM $tutor_user_table gu
  1147. INNER JOIN $groupTable g
  1148. ON (gu.group_id = g.id and g.c_id = gu.c_id)
  1149. WHERE gu.c_id = $course_id AND g.id = $group_id";
  1150. $res = Database::query($sql);
  1151. while ($obj = Database::fetch_object($res)) {
  1152. $users[] = api_get_user_info($obj->user_id);
  1153. }
  1154. return $users;
  1155. }
  1156. /**
  1157. * Get only tutors from a group.
  1158. *
  1159. * @param array $groupInfo
  1160. *
  1161. * @return array
  1162. */
  1163. public static function getTutors($groupInfo)
  1164. {
  1165. $groupTable = Database::get_course_table(TABLE_GROUP);
  1166. $tutor_user_table = Database::get_course_table(TABLE_GROUP_TUTOR);
  1167. $course_id = api_get_course_int_id();
  1168. $group_id = intval($groupInfo['iid']);
  1169. $sql = "SELECT user_id
  1170. FROM $tutor_user_table gu
  1171. INNER JOIN $groupTable g
  1172. ON (gu.group_id = g.id and g.c_id = gu.c_id)
  1173. WHERE gu.c_id = $course_id AND g.iid = $group_id";
  1174. $res = Database::query($sql);
  1175. $users = [];
  1176. while ($obj = Database::fetch_object($res)) {
  1177. $users[] = api_get_user_info($obj->user_id);
  1178. }
  1179. return $users;
  1180. }
  1181. /**
  1182. * Get only students from a group (not tutors).
  1183. *
  1184. * @param int $group_id iid
  1185. * @param bool $filterOnlyActive
  1186. *
  1187. * @return array
  1188. */
  1189. public static function getStudents($group_id, $filterOnlyActive = false)
  1190. {
  1191. $activeCondition = $filterOnlyActive ? 'AND u.active = 1' : '';
  1192. $em = Database::getManager();
  1193. $subscriptions = $em
  1194. ->createQuery("
  1195. SELECT u.id FROM ChamiloUserBundle:User u
  1196. INNER JOIN ChamiloCourseBundle:CGroupRelUser gu
  1197. WITH u.id = gu.userId
  1198. INNER JOIN ChamiloCourseBundle:CGroupInfo g
  1199. WITH gu.groupId = g.id AND g.cId = gu.cId
  1200. WHERE gu.cId = :course AND g.id = :group
  1201. $activeCondition
  1202. ")
  1203. ->setParameters([
  1204. 'course' => api_get_course_int_id(),
  1205. 'group' => intval($group_id),
  1206. ])
  1207. ->getResult();
  1208. $users = [];
  1209. /** @var CGroupRelUser $subscription */
  1210. foreach ($subscriptions as $subscription) {
  1211. $users[] = api_get_user_info($subscription['id']);
  1212. }
  1213. return $users;
  1214. }
  1215. /**
  1216. * Returns users belonging to any of the group.
  1217. *
  1218. * @param array $groups list of group ids
  1219. *
  1220. * @return array list of user ids
  1221. */
  1222. public static function get_groups_users($groups = [])
  1223. {
  1224. $result = [];
  1225. $table = Database::get_course_table(TABLE_GROUP_USER);
  1226. $course_id = api_get_course_int_id();
  1227. $groups = array_map('intval', $groups);
  1228. // protect individual elements with surrounding quotes
  1229. $groups = implode(', ', $groups);
  1230. $sql = "SELECT DISTINCT user_id
  1231. FROM $table gu
  1232. WHERE c_id = $course_id AND gu.group_id IN ($groups)";
  1233. $rs = Database::query($sql);
  1234. while ($row = Database::fetch_array($rs)) {
  1235. $result[] = $row['user_id'];
  1236. }
  1237. return $result;
  1238. }
  1239. /**
  1240. * Fill the groups with students.
  1241. * The algorithm takes care to first fill the groups with the least # of users.
  1242. * Analysis
  1243. * There was a problem with the "ALL" setting.
  1244. * When max # of groups is set to all, the value is sometimes NULL and sometimes ALL
  1245. * and in both cased the query does not work as expected.
  1246. * Stupid solution (currently implemented: set ALL to a big number (INFINITE) and things are solved :)
  1247. * Better solution: that's up to you.
  1248. *
  1249. * Note
  1250. * Throughout Dokeos there is some confusion about "course id" and "course code"
  1251. * The code is e.g. TEST101, but sometimes a variable that is called courseID also contains a course code string.
  1252. * However, there is also a integer course_id that uniquely identifies the course.
  1253. * ywarnier:> Now the course_id has been removed (25/1/2005)
  1254. * The databases are als very inconsistent in this.
  1255. *
  1256. * @param array $groupInfo
  1257. *
  1258. * @author Chrisptophe Gesche <christophe.geshe@claroline.net>,
  1259. * Hugues Peeters <hugues.peeters@claroline.net> - original version
  1260. * @author Roan Embrechts - virtual course support, code cleaning
  1261. * @author Bart Mollet - code cleaning, use other GroupManager-functions
  1262. *
  1263. * @return bool
  1264. */
  1265. public static function fillGroupWithUsers($groupInfo)
  1266. {
  1267. $_course = api_get_course_info();
  1268. if (empty($_course) || empty($groupInfo)) {
  1269. return false;
  1270. }
  1271. $session_id = api_get_session_id();
  1272. $complete_user_list = CourseManager::get_user_list_from_course_code(
  1273. $_course['code'],
  1274. $session_id
  1275. );
  1276. $groupIid = $groupInfo['iid'];
  1277. $category = self::get_category_from_group($groupIid);
  1278. // Getting max numbers of user from group
  1279. $maxNumberStudents = empty($groupInfo['maximum_number_of_students']) ? self::INFINITE : $groupInfo['maximum_number_of_students'];
  1280. $groupsPerUser = self::INFINITE;
  1281. $categoryId = 0;
  1282. if ($category) {
  1283. $groupsPerUser = empty($category['groups_per_user']) ? self::INFINITE : $category['groups_per_user'];
  1284. $maxNumberStudentsCategory = empty($category['max_student']) ? self::INFINITE : $category['max_student'];
  1285. $categoryId = $category['id'];
  1286. if ($maxNumberStudentsCategory < $maxNumberStudents) {
  1287. $maxNumberStudents = $maxNumberStudentsCategory;
  1288. }
  1289. }
  1290. $usersToAdd = [];
  1291. foreach ($complete_user_list as $userInfo) {
  1292. $isSubscribed = self::is_subscribed($userInfo['user_id'], $groupInfo);
  1293. if ($isSubscribed) {
  1294. continue;
  1295. }
  1296. $numberOfGroups = self::user_in_number_of_groups(
  1297. $userInfo['user_id'],
  1298. $categoryId
  1299. );
  1300. if ($groupsPerUser > $numberOfGroups) {
  1301. $usersToAdd[] = $userInfo['user_id'];
  1302. }
  1303. if (count($usersToAdd) == $maxNumberStudents) {
  1304. break;
  1305. }
  1306. }
  1307. foreach ($usersToAdd as $userId) {
  1308. self::subscribe_users($userId, $groupInfo);
  1309. }
  1310. }
  1311. /**
  1312. * Get the number of students in a group.
  1313. *
  1314. * @param int $group_id id
  1315. *
  1316. * @return int number of students in the given group
  1317. */
  1318. public static function number_of_students($group_id, $course_id = null)
  1319. {
  1320. $table = Database::get_course_table(TABLE_GROUP_USER);
  1321. $group_id = intval($group_id);
  1322. if (empty($course_id)) {
  1323. $course_id = api_get_course_int_id();
  1324. } else {
  1325. $course_id = intval($course_id);
  1326. }
  1327. $sql = "SELECT COUNT(*) AS number_of_students
  1328. FROM $table
  1329. WHERE c_id = $course_id AND group_id = $group_id";
  1330. $result = Database::query($sql);
  1331. $db_object = Database::fetch_object($result);
  1332. return $db_object->number_of_students;
  1333. }
  1334. /**
  1335. * Maximum number of students in a group.
  1336. *
  1337. * @param int $group_id iid
  1338. *
  1339. * @return int maximum number of students in the given group
  1340. */
  1341. public static function maximum_number_of_students($group_id)
  1342. {
  1343. $table = Database::get_course_table(TABLE_GROUP);
  1344. $group_id = intval($group_id);
  1345. $course_id = api_get_course_int_id();
  1346. $sql = "SELECT max_student FROM $table
  1347. WHERE c_id = $course_id AND iid = $group_id";
  1348. $db_result = Database::query($sql);
  1349. $db_object = Database::fetch_object($db_result);
  1350. if ($db_object->max_student == 0) {
  1351. return self::INFINITE;
  1352. }
  1353. return $db_object->max_student;
  1354. }
  1355. /**
  1356. * Number of groups of a user.
  1357. *
  1358. * @param int $user_id
  1359. * @param int $cat_id
  1360. *
  1361. * @return int the number of groups the user is subscribed in
  1362. */
  1363. public static function user_in_number_of_groups($user_id, $cat_id = 0)
  1364. {
  1365. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1366. $table_group = Database::get_course_table(TABLE_GROUP);
  1367. $user_id = (int) $user_id;
  1368. $cat_id = (int) $cat_id;
  1369. $course_id = api_get_course_int_id();
  1370. $cat_condition = '';
  1371. if (!empty($cat_id)) {
  1372. $cat_condition = " AND g.category_id = $cat_id ";
  1373. }
  1374. $sql = "SELECT COUNT(*) AS number_of_groups
  1375. FROM $table_group_user gu
  1376. INNER JOIN $table_group g
  1377. ON (g.iid = gu.group_id AND gu.c_id = g.c_id)
  1378. WHERE
  1379. gu.c_id = $course_id AND
  1380. g.c_id = $course_id AND
  1381. gu.user_id = $user_id
  1382. $cat_condition";
  1383. $result = Database::query($sql);
  1384. $db_object = Database::fetch_object($result);
  1385. return $db_object->number_of_groups;
  1386. }
  1387. /**
  1388. * Is sef-registration allowed?
  1389. *
  1390. * @param int $user_id
  1391. * @param array $groupInfo
  1392. *
  1393. * @return bool TRUE if self-registration is allowed in the given group
  1394. */
  1395. public static function is_self_registration_allowed($user_id, $groupInfo)
  1396. {
  1397. $course_id = api_get_course_int_id();
  1398. if (empty($user_id)) {
  1399. return false;
  1400. }
  1401. $groupIid = $groupInfo['iid'];
  1402. $table = Database::get_course_table(TABLE_GROUP);
  1403. if (isset($groupIid)) {
  1404. $sql = "SELECT status, self_registration_allowed
  1405. FROM $table
  1406. WHERE c_id = $course_id AND iid = $groupIid";
  1407. $result = Database::query($sql);
  1408. $group = Database::fetch_object($result);
  1409. if ($group->status == 0 || $group->self_registration_allowed != 1) {
  1410. return false;
  1411. }
  1412. return self::canUserSubscribe($user_id, $groupInfo);
  1413. } else {
  1414. return false;
  1415. }
  1416. }
  1417. /**
  1418. * Is sef-unregistration allowed?
  1419. *
  1420. * @param int $user_id
  1421. * @param array $groupInfo
  1422. *
  1423. * @return bool TRUE if self-unregistration is allowed in the given group
  1424. */
  1425. public static function is_self_unregistration_allowed($user_id, $groupInfo)
  1426. {
  1427. if (empty($user_id) || empty($groupInfo)) {
  1428. return false;
  1429. }
  1430. $groupIid = $groupInfo['iid'];
  1431. $table = Database::get_course_table(TABLE_GROUP);
  1432. $course_id = api_get_course_int_id();
  1433. $sql = "SELECT status, self_unregistration_allowed
  1434. FROM $table
  1435. WHERE c_id = $course_id AND iid = $groupIid";
  1436. $result = Database::query($sql);
  1437. $group = Database::fetch_object($result);
  1438. if ($group->status == 0 || $group->self_unregistration_allowed != 1) {
  1439. return false;
  1440. }
  1441. return self::is_subscribed($user_id, $groupInfo);
  1442. }
  1443. /**
  1444. * Is user subscribed in group?
  1445. *
  1446. * @param int $user_id
  1447. * @param array $groupInfo
  1448. *
  1449. * @return bool TRUE if given user is subscribed in given group
  1450. */
  1451. public static function is_subscribed($user_id, $groupInfo)
  1452. {
  1453. $course_id = api_get_course_int_id();
  1454. if (empty($user_id) || empty($groupInfo) || empty($course_id)) {
  1455. return false;
  1456. }
  1457. $table = Database::get_course_table(TABLE_GROUP_USER);
  1458. $group_id = intval($groupInfo['id']);
  1459. $user_id = intval($user_id);
  1460. $sql = "SELECT 1 FROM $table
  1461. WHERE
  1462. c_id = $course_id AND
  1463. group_id = $group_id AND
  1464. user_id = $user_id
  1465. ";
  1466. $result = Database::query($sql);
  1467. return Database::num_rows($result) > 0;
  1468. }
  1469. /**
  1470. * Can a user subscribe to a specified group in a course.
  1471. *
  1472. * @param int $user_id
  1473. * @param array $groupInfo
  1474. * @param bool $checkMaxNumberStudents
  1475. *
  1476. * @return bool TRUE if given user can be subscribed in given group
  1477. */
  1478. public static function canUserSubscribe(
  1479. $user_id,
  1480. $groupInfo,
  1481. $checkMaxNumberStudents = true
  1482. ) {
  1483. $group_id = $groupInfo['id'];
  1484. $groupIid = $groupInfo['iid'];
  1485. if ($checkMaxNumberStudents) {
  1486. $category = self::get_category_from_group($groupIid);
  1487. if ($category) {
  1488. if ($category['groups_per_user'] == self::GROUP_PER_MEMBER_NO_LIMIT) {
  1489. $category['groups_per_user'] = self::INFINITE;
  1490. }
  1491. $result = self::user_in_number_of_groups($user_id, $category['id']) < $category['groups_per_user'];
  1492. if ($result == false) {
  1493. return false;
  1494. }
  1495. }
  1496. $result = self::number_of_students($group_id) < self::maximum_number_of_students($groupIid);
  1497. if ($result == false) {
  1498. return false;
  1499. }
  1500. }
  1501. $result = self::is_tutor_of_group($user_id, $groupInfo);
  1502. if ($result) {
  1503. return false;
  1504. }
  1505. $result = self::is_subscribed($user_id, $groupInfo);
  1506. if ($result) {
  1507. return false;
  1508. }
  1509. return true;
  1510. }
  1511. /**
  1512. * Get all subscribed users (members) from a group.
  1513. *
  1514. * @param array $groupInfo
  1515. *
  1516. * @return array An array with information of all users from the given group.
  1517. * (user_id, firstname, lastname, email)
  1518. */
  1519. public static function get_subscribed_users($groupInfo)
  1520. {
  1521. if (empty($groupInfo)) {
  1522. return [];
  1523. }
  1524. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1525. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1526. $order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
  1527. $orderListByOfficialCode = api_get_setting('order_user_list_by_official_code');
  1528. if ($orderListByOfficialCode === 'true') {
  1529. $order_clause = ' ORDER BY u.official_code, u.firstname, u.lastname';
  1530. }
  1531. $group_id = (int) $groupInfo['iid'];
  1532. if (empty($group_id)) {
  1533. return [];
  1534. }
  1535. $course_id = api_get_course_int_id();
  1536. $sql = "SELECT
  1537. ug.id,
  1538. u.user_id,
  1539. u.lastname,
  1540. u.firstname,
  1541. u.email,
  1542. u.username
  1543. FROM $table_user u
  1544. INNER JOIN $table_group_user ug
  1545. ON (ug.user_id = u.user_id)
  1546. WHERE ug.c_id = $course_id AND
  1547. ug.group_id = $group_id
  1548. $order_clause";
  1549. $db_result = Database::query($sql);
  1550. $users = [];
  1551. while ($user = Database::fetch_object($db_result)) {
  1552. $users[$user->user_id] = [
  1553. 'user_id' => $user->user_id,
  1554. 'firstname' => $user->firstname,
  1555. 'lastname' => $user->lastname,
  1556. 'email' => $user->email,
  1557. 'username' => $user->username,
  1558. ];
  1559. }
  1560. return $users;
  1561. }
  1562. /**
  1563. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1564. * Get all subscribed tutors of a group
  1565. *
  1566. * @param array $groupInfo
  1567. *
  1568. * @return array An array with information of all users from the given group.
  1569. * (user_id, firstname, lastname, email)
  1570. */
  1571. public static function get_subscribed_tutors($groupInfo, $id_only = false)
  1572. {
  1573. if (empty($groupInfo)) {
  1574. return [];
  1575. }
  1576. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1577. $table_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
  1578. $order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
  1579. $orderListByOfficialCode = api_get_setting('order_user_list_by_official_code');
  1580. if ($orderListByOfficialCode === 'true') {
  1581. $order_clause = ' ORDER BY u.official_code, u.firstname, u.lastname';
  1582. }
  1583. $group_id = (int) $groupInfo['iid'];
  1584. $course_id = api_get_course_int_id();
  1585. $sql = "SELECT tg.id, u.user_id, u.lastname, u.firstname, u.email
  1586. FROM $table_user u, $table_group_tutor tg
  1587. WHERE
  1588. tg.c_id = $course_id AND
  1589. tg.group_id = $group_id AND
  1590. tg.user_id = u.user_id
  1591. $order_clause
  1592. ";
  1593. $db_result = Database::query($sql);
  1594. $users = [];
  1595. while ($user = Database::fetch_object($db_result)) {
  1596. if (!$id_only) {
  1597. $member['user_id'] = $user->user_id;
  1598. $member['firstname'] = $user->firstname;
  1599. $member['lastname'] = $user->lastname;
  1600. $member['email'] = $user->email;
  1601. $users[] = $member;
  1602. } else {
  1603. $users[] = $user->user_id;
  1604. }
  1605. }
  1606. return $users;
  1607. }
  1608. /**
  1609. * Subscribe user(s) to a specified group in current course (as a student).
  1610. *
  1611. * @param mixed $user_ids Can be an array with user-id's or a single user-id
  1612. * @param array $groupInfo
  1613. * @param int $course_id
  1614. *
  1615. * @return bool TRUE if successful
  1616. */
  1617. public static function subscribe_users($user_ids, $groupInfo, $course_id = null)
  1618. {
  1619. $user_ids = is_array($user_ids) ? $user_ids : [$user_ids];
  1620. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  1621. $group_id = $groupInfo['id'];
  1622. if (!empty($user_ids)) {
  1623. $table = Database::get_course_table(TABLE_GROUP_USER);
  1624. foreach ($user_ids as $user_id) {
  1625. if (self::canUserSubscribe($user_id, $groupInfo)) {
  1626. $user_id = (int) $user_id;
  1627. $sql = "INSERT INTO ".$table." (c_id, user_id, group_id)
  1628. VALUES ('$course_id', '".$user_id."', '".$group_id."')";
  1629. Database::query($sql);
  1630. }
  1631. }
  1632. }
  1633. return true;
  1634. }
  1635. /**
  1636. * Subscribe tutor(s) to a specified group in current course.
  1637. *
  1638. * @param mixed $user_ids Can be an array with user-id's or a single user-id
  1639. * @param array $groupInfo
  1640. * @param int $course_id
  1641. *
  1642. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1643. *
  1644. * @see subscribe_users. This function is almost an exact copy of that function.
  1645. *
  1646. * @return bool TRUE if successful
  1647. */
  1648. public static function subscribe_tutors($user_ids, $groupInfo, $course_id = 0)
  1649. {
  1650. $user_ids = is_array($user_ids) ? $user_ids : [$user_ids];
  1651. $result = true;
  1652. $course_id = isset($course_id) && !empty($course_id) ? intval($course_id) : api_get_course_int_id();
  1653. $table_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
  1654. $groupId = (int) $groupInfo['id'];
  1655. foreach ($user_ids as $user_id) {
  1656. $user_id = intval($user_id);
  1657. if (self::canUserSubscribe($user_id, $groupInfo, false)) {
  1658. $sql = "INSERT INTO ".$table_group_tutor." (c_id, user_id, group_id)
  1659. VALUES ('$course_id', '".$user_id."', '".$groupId."')";
  1660. $result = Database::query($sql);
  1661. }
  1662. }
  1663. return $result;
  1664. }
  1665. /**
  1666. * Unsubscribe user(s) from a specified group in current course.
  1667. *
  1668. * @param mixed $user_ids Can be an array with user-id's or a single user-id
  1669. * @param array $groupInfo
  1670. *
  1671. * @return bool TRUE if successful
  1672. */
  1673. public static function unsubscribe_users($user_ids, $groupInfo)
  1674. {
  1675. $user_ids = is_array($user_ids) ? $user_ids : [$user_ids];
  1676. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1677. $group_id = intval($groupInfo['id']);
  1678. $course_id = api_get_course_int_id();
  1679. $sql = 'DELETE FROM '.$table_group_user.'
  1680. WHERE
  1681. c_id = '.$course_id.' AND
  1682. group_id = '.$group_id.' AND
  1683. user_id IN ('.implode(',', $user_ids).')
  1684. ';
  1685. Database::query($sql);
  1686. }
  1687. /**
  1688. * Unsubscribe all users from one or more groups.
  1689. *
  1690. * @param array $groupInfo
  1691. *
  1692. * @return bool TRUE if successful
  1693. */
  1694. public static function unsubscribe_all_users($groupInfo)
  1695. {
  1696. $course_id = api_get_course_int_id();
  1697. $groupId = (int) $groupInfo['id'];
  1698. if (empty($course_id) || empty($groupId)) {
  1699. return false;
  1700. }
  1701. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1702. $sql = "DELETE FROM $table_group_user
  1703. WHERE
  1704. group_id = $groupId AND
  1705. c_id = $course_id";
  1706. $result = Database::query($sql);
  1707. return $result;
  1708. }
  1709. /**
  1710. * Unsubscribe all tutors from one or more groups.
  1711. *
  1712. * @param int $groupId iid
  1713. *
  1714. * @see unsubscribe_all_users. This function is almost an exact copy of that function.
  1715. *
  1716. * @return bool TRUE if successful
  1717. *
  1718. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1719. */
  1720. public static function unsubscribe_all_tutors($groupId)
  1721. {
  1722. $courseId = api_get_course_int_id();
  1723. $groupId = (int) $groupId;
  1724. if (empty($courseId) || empty($groupId)) {
  1725. return false;
  1726. }
  1727. if (!empty($groupId)) {
  1728. $table_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
  1729. $sql = "DELETE FROM $table_group_tutor
  1730. WHERE group_id = $groupId AND c_id = $courseId";
  1731. $result = Database::query($sql);
  1732. return $result;
  1733. }
  1734. return true;
  1735. }
  1736. /**
  1737. * Is the user a tutor of this group?
  1738. *
  1739. * @param int $user_id the id of the user
  1740. * @param array $groupInfo
  1741. * @param int $courseId
  1742. *
  1743. * @return bool true/false
  1744. *
  1745. * @todo use the function user_has_access that includes this function
  1746. *
  1747. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1748. */
  1749. public static function is_tutor_of_group($user_id, $groupInfo, $courseId = 0)
  1750. {
  1751. if (empty($groupInfo)) {
  1752. return false;
  1753. }
  1754. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  1755. if (empty($courseId)) {
  1756. return false;
  1757. }
  1758. $user_id = (int) $user_id;
  1759. $group_id = (int) $groupInfo['id'];
  1760. $table = Database::get_course_table(TABLE_GROUP_TUTOR);
  1761. $sql = "SELECT * FROM $table
  1762. WHERE
  1763. c_id = $courseId AND
  1764. user_id = $user_id AND
  1765. group_id = $group_id";
  1766. $result = Database::query($sql);
  1767. if (Database::num_rows($result) > 0) {
  1768. return true;
  1769. }
  1770. return false;
  1771. }
  1772. /**
  1773. * Is the user part of this group? This can be a tutor or a normal member
  1774. * you should use this function if the access to a tool or functionality is
  1775. * restricted to the people who are actually in the group
  1776. * before you had to check if the user was
  1777. * 1. a member of the group OR
  1778. * 2. a tutor of the group. This function combines both.
  1779. *
  1780. * @param int $user_id the id of the user
  1781. * @param array $groupInfo
  1782. *
  1783. * @return bool true/false
  1784. *
  1785. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1786. */
  1787. public static function is_user_in_group($user_id, $groupInfo)
  1788. {
  1789. $member = self::is_subscribed($user_id, $groupInfo);
  1790. if ($member) {
  1791. return true;
  1792. }
  1793. $tutor = self::is_tutor_of_group($user_id, $groupInfo);
  1794. if ($tutor) {
  1795. return true;
  1796. }
  1797. return false;
  1798. }
  1799. /**
  1800. * Get all group's from a given course in which a given user is unsubscribed.
  1801. *
  1802. * @author Patrick Cool
  1803. *
  1804. * @param int $course_id retrieve the groups for
  1805. * @param int $user_id the ID of the user you want to know all its group memberships
  1806. *
  1807. * @return array
  1808. */
  1809. public static function get_group_ids($course_id, $user_id)
  1810. {
  1811. $groups = [];
  1812. $tbl_group = Database::get_course_table(TABLE_GROUP_USER);
  1813. $tbl_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
  1814. $user_id = intval($user_id);
  1815. $course_id = intval($course_id);
  1816. $sql = "SELECT group_id FROM $tbl_group
  1817. WHERE c_id = $course_id AND user_id = '$user_id'";
  1818. $result = Database::query($sql);
  1819. if ($result) {
  1820. while ($row = Database::fetch_array($result)) {
  1821. $groups[] = $row['group_id'];
  1822. }
  1823. }
  1824. //Also loading if i'm the tutor
  1825. $sql = "SELECT group_id FROM $tbl_group_tutor
  1826. WHERE c_id = $course_id AND user_id = '$user_id'";
  1827. $result = Database::query($sql);
  1828. if ($result) {
  1829. while ($row = Database::fetch_array($result)) {
  1830. $groups[] = $row['group_id'];
  1831. }
  1832. }
  1833. if (!empty($groups)) {
  1834. array_filter($groups);
  1835. }
  1836. return $groups;
  1837. }
  1838. /**
  1839. * Check if a user has access to a certain group tool.
  1840. *
  1841. * @param int $user_id The user id
  1842. * @param int $group_id The group iid
  1843. * @param string $tool The tool to check the access rights. This should be
  1844. * one of constants: GROUP_TOOL_DOCUMENTS
  1845. *
  1846. * @return bool true if the given user has access to the given tool in the
  1847. * given course
  1848. */
  1849. public static function user_has_access($user_id, $group_id, $tool)
  1850. {
  1851. // Admin have access everywhere
  1852. if (api_is_platform_admin()) {
  1853. return true;
  1854. }
  1855. // Course admin also have access to everything
  1856. if (api_is_allowed_to_edit(false, true, true)) {
  1857. return true;
  1858. }
  1859. switch ($tool) {
  1860. case self::GROUP_TOOL_FORUM:
  1861. $key = 'forum_state';
  1862. break;
  1863. case self::GROUP_TOOL_DOCUMENTS:
  1864. $key = 'doc_state';
  1865. break;
  1866. case self::GROUP_TOOL_CALENDAR:
  1867. $key = 'calendar_state';
  1868. break;
  1869. case self::GROUP_TOOL_ANNOUNCEMENT:
  1870. $key = 'announcements_state';
  1871. break;
  1872. case self::GROUP_TOOL_WORK:
  1873. $key = 'work_state';
  1874. break;
  1875. case self::GROUP_TOOL_WIKI:
  1876. $key = 'wiki_state';
  1877. break;
  1878. case self::GROUP_TOOL_CHAT:
  1879. $key = 'chat_state';
  1880. break;
  1881. default:
  1882. return false;
  1883. }
  1884. // Check group properties
  1885. $groupInfo = self::get_group_properties($group_id, true);
  1886. if (empty($groupInfo)) {
  1887. return false;
  1888. }
  1889. if ($groupInfo['status'] == 0) {
  1890. return false;
  1891. }
  1892. if (!isset($groupInfo[$key])) {
  1893. return false;
  1894. }
  1895. $status = $groupInfo[$key];
  1896. switch ($status) {
  1897. case self::TOOL_NOT_AVAILABLE:
  1898. return false;
  1899. break;
  1900. case self::TOOL_PUBLIC:
  1901. return true;
  1902. break;
  1903. case self::TOOL_PRIVATE:
  1904. $userIsInGroup = self::is_user_in_group($user_id, $groupInfo);
  1905. if ($userIsInGroup) {
  1906. return true;
  1907. }
  1908. break;
  1909. case self::TOOL_PRIVATE_BETWEEN_USERS:
  1910. // Only works for announcements for now
  1911. $userIsInGroup = self::is_user_in_group($user_id, $groupInfo);
  1912. if ($userIsInGroup && $tool == self::GROUP_TOOL_ANNOUNCEMENT) {
  1913. return true;
  1914. }
  1915. break;
  1916. }
  1917. return false;
  1918. }
  1919. /**
  1920. * @param int $userId
  1921. * @param array $groupInfo
  1922. * @param int $sessionId
  1923. *
  1924. * @return bool
  1925. */
  1926. public static function userHasAccessToBrowse($userId, $groupInfo, $sessionId = 0)
  1927. {
  1928. if (empty($groupInfo)) {
  1929. return false;
  1930. }
  1931. if (api_is_platform_admin()) {
  1932. return true;
  1933. }
  1934. if (api_is_allowed_to_edit(false, true, true)) {
  1935. return true;
  1936. }
  1937. if (!empty($sessionId)) {
  1938. if (api_is_coach($sessionId, api_get_course_int_id())) {
  1939. return true;
  1940. }
  1941. if (api_is_drh()) {
  1942. if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
  1943. return true;
  1944. }
  1945. }
  1946. }
  1947. $groupId = $groupInfo['iid'];
  1948. if (self::is_tutor_of_group($userId, $groupInfo)) {
  1949. return true;
  1950. }
  1951. if ($groupInfo['status'] == 0) {
  1952. return false;
  1953. }
  1954. if (self::user_has_access($userId, $groupId, self::GROUP_TOOL_FORUM) ||
  1955. self::user_has_access($userId, $groupId, self::GROUP_TOOL_DOCUMENTS) ||
  1956. self::user_has_access($userId, $groupId, self::GROUP_TOOL_CALENDAR) ||
  1957. self::user_has_access($userId, $groupId, self::GROUP_TOOL_ANNOUNCEMENT) ||
  1958. self::user_has_access($userId, $groupId, self::GROUP_TOOL_WORK) ||
  1959. self::user_has_access($userId, $groupId, self::GROUP_TOOL_WIKI) ||
  1960. self::user_has_access($userId, $groupId, self::GROUP_TOOL_CHAT)
  1961. ) {
  1962. return true;
  1963. }
  1964. if (api_is_session_general_coach() && $groupInfo['session_id'] == $sessionId) {
  1965. return true;
  1966. }
  1967. return false;
  1968. }
  1969. /**
  1970. * Get all groups where a specific user is subscribed.
  1971. *
  1972. * @param int $user_id
  1973. *
  1974. * @return array
  1975. */
  1976. public static function get_user_group_name($user_id)
  1977. {
  1978. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1979. $table_group = Database::get_course_table(TABLE_GROUP);
  1980. $user_id = intval($user_id);
  1981. $course_id = api_get_course_int_id();
  1982. $sql = "SELECT name
  1983. FROM $table_group g
  1984. INNER JOIN $table_group_user gu
  1985. ON (gu.group_id = g.iid)
  1986. WHERE
  1987. gu.c_id= $course_id AND
  1988. g.c_id= $course_id AND
  1989. gu.user_id = $user_id";
  1990. $res = Database::query($sql);
  1991. $groups = [];
  1992. while ($group = Database::fetch_array($res)) {
  1993. $groups[] .= $group['name'];
  1994. }
  1995. return $groups;
  1996. }
  1997. /**
  1998. * Get all groups where a specific user is subscribed.
  1999. *
  2000. * @param int $user_id
  2001. * @param int $courseId
  2002. *
  2003. * @return array
  2004. */
  2005. public static function getAllGroupPerUserSubscription($user_id, $courseId = 0)
  2006. {
  2007. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  2008. $table_tutor_user = Database::get_course_table(TABLE_GROUP_TUTOR);
  2009. $table_group = Database::get_course_table(TABLE_GROUP);
  2010. $user_id = (int) $user_id;
  2011. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  2012. $sql = "SELECT DISTINCT g.*
  2013. FROM $table_group g
  2014. LEFT JOIN $table_group_user gu
  2015. ON (gu.group_id = g.iid AND g.c_id = gu.c_id)
  2016. LEFT JOIN $table_tutor_user tu
  2017. ON (tu.group_id = g.iid AND g.c_id = tu.c_id)
  2018. WHERE
  2019. g.c_id = $courseId AND
  2020. (gu.user_id = $user_id OR tu.user_id = $user_id) ";
  2021. $res = Database::query($sql);
  2022. $groups = [];
  2023. while ($group = Database::fetch_array($res, 'ASSOC')) {
  2024. $groups[] = $group;
  2025. }
  2026. return $groups;
  2027. }
  2028. /**
  2029. * @param array $group_list
  2030. * @param int $category_id
  2031. *
  2032. * @return string
  2033. */
  2034. public static function process_groups($group_list, $category_id = 0)
  2035. {
  2036. global $charset;
  2037. $category_id = (int) $category_id;
  2038. $totalRegistered = 0;
  2039. $group_data = [];
  2040. $user_info = api_get_user_info();
  2041. $session_id = api_get_session_id();
  2042. $user_id = $user_info['user_id'];
  2043. $hideGroup = api_get_setting('hide_course_group_if_no_tools_available');
  2044. foreach ($group_list as $this_group) {
  2045. // Validation when belongs to a session
  2046. $session_img = api_get_session_image($this_group['session_id'], $user_info['status']);
  2047. // All the tutors of this group
  2048. $tutorsids_of_group = self::get_subscribed_tutors($this_group, true);
  2049. $isMember = self::is_subscribed($user_id, $this_group);
  2050. // Create a new table-row
  2051. $row = [];
  2052. // Checkbox
  2053. if (api_is_allowed_to_edit(false, true) && count($group_list) > 1) {
  2054. $row[] = $this_group['id'];
  2055. }
  2056. if (self::userHasAccessToBrowse($user_id, $this_group, $session_id)) {
  2057. // Group name
  2058. $groupNameClass = null;
  2059. if ($this_group['status'] == 0) {
  2060. $groupNameClass = 'muted';
  2061. }
  2062. $group_name = '<a class="'.$groupNameClass.'" href="group_space.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'">'.
  2063. Security::remove_XSS($this_group['name']).'</a> ';
  2064. $group_name2 = '';
  2065. if (api_get_configuration_value('extra')) {
  2066. $group_name2 = '<a href="group_space_tracking.php?cidReq='.api_get_course_id().'&gidReq='
  2067. .$this_group['id'].'">'.get_lang('suivi_de').''.stripslashes($this_group['name']).'</a>';
  2068. }
  2069. if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
  2070. $group_name .= Display::label(get_lang('OneMyGroups'), 'success');
  2071. } elseif ($isMember) {
  2072. $group_name .= Display::label(get_lang('MyGroup'), 'success');
  2073. }
  2074. if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
  2075. $group_name .= ' ('.$this_group['session_name'].')';
  2076. }
  2077. $group_name .= $session_img;
  2078. $row[] = $group_name.$group_name2.'<br />'.stripslashes(trim($this_group['description']));
  2079. } else {
  2080. if ($hideGroup === 'true') {
  2081. continue;
  2082. }
  2083. $row[] = $this_group['name'].'<br />'.stripslashes(trim($this_group['description']));
  2084. }
  2085. // Tutor name
  2086. $tutor_info = '';
  2087. if (count($tutorsids_of_group) > 0) {
  2088. foreach ($tutorsids_of_group as $tutor_id) {
  2089. $tutor = api_get_user_info($tutor_id);
  2090. $username = api_htmlentities(
  2091. sprintf(get_lang('LoginX'), $tutor['username']),
  2092. ENT_QUOTES
  2093. );
  2094. if (api_get_setting('show_email_addresses') === 'true') {
  2095. $tutor_info .= Display::tag(
  2096. 'span',
  2097. Display::encrypted_mailto_link(
  2098. $tutor['mail'],
  2099. $tutor['complete_name']
  2100. ),
  2101. ['title' => $username]
  2102. ).', ';
  2103. } else {
  2104. if (api_is_allowed_to_edit()) {
  2105. $tutor_info .= Display::tag(
  2106. 'span',
  2107. Display::encrypted_mailto_link(
  2108. $tutor['mail'],
  2109. $tutor['complete_name_with_username']
  2110. ),
  2111. ['title' => $username]
  2112. ).', ';
  2113. } else {
  2114. $tutor_info .= Display::tag(
  2115. 'span',
  2116. $tutor['complete_name'],
  2117. ['title' => $username]
  2118. ).', ';
  2119. }
  2120. }
  2121. }
  2122. }
  2123. $tutor_info = api_substr(
  2124. $tutor_info,
  2125. 0,
  2126. api_strlen($tutor_info) - 2
  2127. );
  2128. $row[] = $tutor_info;
  2129. // Max number of members in group
  2130. $max_members = $this_group['maximum_number_of_members'] == self::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / '.$this_group['maximum_number_of_members'];
  2131. // Number of members in group
  2132. $row[] = $this_group['number_of_members'].$max_members;
  2133. // Self-registration / unregistration
  2134. if (!api_is_allowed_to_edit(false, true)) {
  2135. if (self::is_self_registration_allowed($user_id, $this_group)) {
  2136. $row[] = '<a class = "btn btn-default" href="group.php?'.api_get_cidreq().'&category='.$category_id.'&action=self_reg&group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfRegInf').'</a>';
  2137. } elseif (self::is_self_unregistration_allowed($user_id, $this_group)) {
  2138. $row[] = '<a class = "btn btn-default" href="group.php?'.api_get_cidreq().'&category='.$category_id.'&action=self_unreg&group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."'".')) return false;">'.get_lang('GroupSelfUnRegInf').'</a>';
  2139. } else {
  2140. $row[] = '-';
  2141. }
  2142. }
  2143. $url = api_get_path(WEB_CODE_PATH).'group/';
  2144. // Edit-links
  2145. if (api_is_allowed_to_edit(false, true) &&
  2146. !(api_is_session_general_coach() && intval($this_group['session_id']) != $session_id)
  2147. ) {
  2148. $edit_actions = '<a href="'.$url.'settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('Edit').'">'.
  2149. Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2150. if ($this_group['status'] == 1) {
  2151. $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=set_invisible&id='.$this_group['id'].'" title="'.get_lang('Hide').'">'.
  2152. Display::return_icon('visible.png', get_lang('Hide'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2153. } else {
  2154. $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=set_visible&id='.$this_group['id'].'" title="'.get_lang('Show').'">'.
  2155. Display::return_icon('invisible.png', get_lang('Show'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2156. }
  2157. $edit_actions .= '<a href="'.$url.'member_settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('GroupMembers').'">'.
  2158. Display::return_icon('user.png', get_lang('GroupMembers'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2159. $edit_actions .= '<a href="'.$url.'group_overview.php?action=export&type=xls&'.api_get_cidreq(true, false).'&id='.$this_group['id'].'" title="'.get_lang('ExportUsers').'">'.
  2160. Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2161. $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=fill_one&id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('FillGroup').'">'.
  2162. Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2163. $edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=delete_one&id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'">'.
  2164. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2165. $row[] = $edit_actions;
  2166. }
  2167. if (!empty($this_group['nbMember'])) {
  2168. $totalRegistered = $totalRegistered + $this_group['nbMember'];
  2169. }
  2170. $group_data[] = $row;
  2171. } // end loop
  2172. // If no groups then don't show the table (only for students)
  2173. if (!api_is_allowed_to_edit(true, false)) {
  2174. if (empty($group_data)) {
  2175. return '';
  2176. }
  2177. }
  2178. $table = new SortableTableFromArrayConfig(
  2179. $group_data,
  2180. 1,
  2181. 20,
  2182. 'group_category_'.$category_id
  2183. );
  2184. $table->set_additional_parameters(['category' => $category_id]);
  2185. $column = 0;
  2186. if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
  2187. $table->set_header($column++, '', false);
  2188. }
  2189. $table->set_header($column++, get_lang('Groups'));
  2190. $table->set_header($column++, get_lang('GroupTutor'));
  2191. $table->set_header($column++, get_lang('Registered'), false);
  2192. if (!api_is_allowed_to_edit(false, true)) {
  2193. // If self-registration allowed
  2194. $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
  2195. }
  2196. if (api_is_allowed_to_edit(false, true)) {
  2197. // Only for course administrator
  2198. $table->set_header($column++, get_lang('Modify'), false);
  2199. $form_actions = [];
  2200. $form_actions['fill_selected'] = get_lang('FillGroup');
  2201. $form_actions['empty_selected'] = get_lang('EmptyGroup');
  2202. $form_actions['delete_selected'] = get_lang('Delete');
  2203. if (count($group_list) > 1) {
  2204. $table->set_form_actions($form_actions, 'group');
  2205. }
  2206. }
  2207. return $table->return_table();
  2208. }
  2209. /**
  2210. * @param array $groupData
  2211. * @param bool $deleteNotInArray
  2212. *
  2213. * @return array
  2214. */
  2215. public static function importCategoriesAndGroupsFromArray(
  2216. $groupData,
  2217. $deleteNotInArray = false
  2218. ) {
  2219. $result = [];
  2220. $elementsFound = [
  2221. 'categories' => [],
  2222. 'groups' => [],
  2223. ];
  2224. $courseCode = api_get_course_id();
  2225. $sessionId = api_get_session_id();
  2226. $groupCategories = self::get_categories();
  2227. if (empty($groupCategories)) {
  2228. $result['error'][] = get_lang('CreateACategory');
  2229. return $result;
  2230. }
  2231. foreach ($groupData as $data) {
  2232. $isCategory = empty($data['group']) ? true : false;
  2233. if ($isCategory) {
  2234. $categoryInfo = self::getCategoryByTitle($data['category']);
  2235. $categoryId = $categoryInfo['id'];
  2236. if (!empty($categoryInfo)) {
  2237. // Update
  2238. self::update_category(
  2239. $categoryId,
  2240. $data['category'],
  2241. $data['description'],
  2242. $data['doc_state'],
  2243. $data['work_state'],
  2244. $data['calendar_state'],
  2245. $data['announcements_state'],
  2246. $data['forum_state'],
  2247. $data['wiki_state'],
  2248. $data['chat_state'],
  2249. $data['self_reg_allowed'],
  2250. $data['self_unreg_allowed'],
  2251. $data['max_student'],
  2252. $data['groups_per_user']
  2253. );
  2254. $data['category_id'] = $categoryId;
  2255. $result['updated']['category'][] = $data;
  2256. } else {
  2257. // Add
  2258. $categoryId = self::create_category(
  2259. $data['category'],
  2260. $data['description'],
  2261. $data['doc_state'],
  2262. $data['work_state'],
  2263. $data['calendar_state'],
  2264. $data['announcements_state'],
  2265. $data['forum_state'],
  2266. $data['wiki_state'],
  2267. $data['chat_state'],
  2268. $data['self_reg_allowed'],
  2269. $data['self_unreg_allowed'],
  2270. $data['max_student'],
  2271. $data['groups_per_user']
  2272. );
  2273. if ($categoryId) {
  2274. $data['category_id'] = $categoryId;
  2275. $result['added']['category'][] = $data;
  2276. }
  2277. }
  2278. $elementsFound['categories'][] = $categoryId;
  2279. } else {
  2280. $groupInfo = self::getGroupByName($data['group']);
  2281. $categoryInfo = [];
  2282. if (isset($data['category'])) {
  2283. $categoryInfo = self::getCategoryByTitle($data['category']);
  2284. }
  2285. $categoryId = null;
  2286. if (!empty($categoryInfo)) {
  2287. $categoryId = $categoryInfo['id'];
  2288. } else {
  2289. if (!empty($groupCategories) && isset($groupCategories[0])) {
  2290. $defaultGroupCategory = $groupCategories[0];
  2291. $categoryId = $defaultGroupCategory['id'];
  2292. }
  2293. }
  2294. if (empty($groupInfo)) {
  2295. // Add
  2296. $groupId = self::create_group(
  2297. $data['group'],
  2298. $categoryId,
  2299. null,
  2300. $data['max_student']
  2301. );
  2302. if ($groupId) {
  2303. self::set_group_properties(
  2304. $groupId,
  2305. $data['group'],
  2306. $data['description'],
  2307. $data['max_student'],
  2308. $data['doc_state'],
  2309. $data['work_state'],
  2310. $data['calendar_state'],
  2311. $data['announcements_state'],
  2312. $data['forum_state'],
  2313. $data['wiki_state'],
  2314. $data['chat_state'],
  2315. $data['self_reg_allowed'],
  2316. $data['self_unreg_allowed'],
  2317. $categoryId
  2318. );
  2319. $data['group_id'] = $groupId;
  2320. $result['added']['group'][] = $data;
  2321. }
  2322. $groupInfo = self::get_group_properties($groupId, true);
  2323. } else {
  2324. // Update
  2325. $groupId = $groupInfo['id'];
  2326. self::set_group_properties(
  2327. $groupId,
  2328. $data['group'],
  2329. $data['description'],
  2330. $data['max_student'],
  2331. $data['doc_state'],
  2332. $data['work_state'],
  2333. $data['calendar_state'],
  2334. $data['announcements_state'],
  2335. $data['forum_state'],
  2336. $data['wiki_state'],
  2337. $data['chat_state'],
  2338. $data['self_reg_allowed'],
  2339. $data['self_unreg_allowed'],
  2340. $categoryId
  2341. );
  2342. $data['group_id'] = $groupId;
  2343. $result['updated']['group'][] = $data;
  2344. $groupInfo = self::get_group_properties($groupId);
  2345. }
  2346. $students = isset($data['students']) ? explode(',', $data['students']) : [];
  2347. if (!empty($students)) {
  2348. $studentUserIdList = [];
  2349. foreach ($students as $student) {
  2350. $userInfo = api_get_user_info_from_username($student);
  2351. if (!$userInfo) {
  2352. continue;
  2353. }
  2354. if (!CourseManager::is_user_subscribed_in_course(
  2355. $userInfo['user_id'],
  2356. $courseCode,
  2357. !empty($sessionId),
  2358. $sessionId
  2359. )
  2360. ) {
  2361. Display::addFlash(
  2362. Display::return_message(
  2363. sprintf(
  2364. get_lang('StudentXIsNotSubscribedToCourse'),
  2365. $userInfo['complete_name']
  2366. ),
  2367. 'warning'
  2368. )
  2369. );
  2370. continue;
  2371. }
  2372. $studentUserIdList[] = $userInfo['user_id'];
  2373. }
  2374. self::subscribe_users($studentUserIdList, $groupInfo);
  2375. }
  2376. $tutors = isset($data['tutors']) ? explode(',', $data['tutors']) : [];
  2377. if (!empty($tutors)) {
  2378. $tutorIdList = [];
  2379. foreach ($tutors as $tutor) {
  2380. $userInfo = api_get_user_info_from_username($tutor);
  2381. if (!$userInfo) {
  2382. continue;
  2383. }
  2384. if (!CourseManager::is_user_subscribed_in_course(
  2385. $userInfo['user_id'],
  2386. $courseCode,
  2387. !empty($sessionId),
  2388. $sessionId
  2389. )
  2390. ) {
  2391. Display::addFlash(
  2392. Display::return_message(
  2393. sprintf(get_lang('TutorXIsNotSubscribedToCourse'), $userInfo['complete_name']),
  2394. 'warning'
  2395. )
  2396. );
  2397. continue;
  2398. }
  2399. $tutorIdList[] = $userInfo['user_id'];
  2400. }
  2401. self::subscribe_tutors($tutorIdList, $groupInfo);
  2402. }
  2403. $elementsFound['groups'][] = $groupId;
  2404. }
  2405. }
  2406. if ($deleteNotInArray) {
  2407. // Check categories
  2408. $categories = self::get_categories();
  2409. foreach ($categories as $category) {
  2410. if (!in_array($category['id'], $elementsFound['categories'])) {
  2411. self::delete_category($category['id']);
  2412. $category['category'] = $category['title'];
  2413. $result['deleted']['category'][] = $category;
  2414. }
  2415. }
  2416. $groups = self::get_groups();
  2417. foreach ($groups as $group) {
  2418. if (!in_array($group['iid'], $elementsFound['groups'])) {
  2419. self::deleteGroup($group);
  2420. $group['group'] = $group['name'];
  2421. $result['deleted']['group'][] = $group;
  2422. }
  2423. }
  2424. }
  2425. return $result;
  2426. }
  2427. /**
  2428. * Export all categories/group from a course to an array.
  2429. * This function works only in a context of a course.
  2430. *
  2431. * @param int $groupId
  2432. * @param bool $loadUsers
  2433. *
  2434. * @return array
  2435. */
  2436. public static function exportCategoriesAndGroupsToArray($groupId = null, $loadUsers = false)
  2437. {
  2438. $data = [];
  2439. $data[] = [
  2440. 'category',
  2441. 'group',
  2442. 'description',
  2443. 'announcements_state',
  2444. 'calendar_state',
  2445. 'chat_state',
  2446. 'doc_state',
  2447. 'forum_state',
  2448. 'work_state',
  2449. 'wiki_state',
  2450. 'max_student',
  2451. 'self_reg_allowed',
  2452. 'self_unreg_allowed',
  2453. 'groups_per_user',
  2454. ];
  2455. $count = 1;
  2456. if ($loadUsers) {
  2457. $data[0][] = 'students';
  2458. $data[0][] = 'tutors';
  2459. }
  2460. if ($loadUsers == false) {
  2461. $categories = self::get_categories();
  2462. foreach ($categories as $categoryInfo) {
  2463. $data[$count] = [
  2464. $categoryInfo['title'],
  2465. null,
  2466. $categoryInfo['description'],
  2467. $categoryInfo['announcements_state'],
  2468. $categoryInfo['calendar_state'],
  2469. $categoryInfo['chat_state'],
  2470. $categoryInfo['doc_state'],
  2471. $categoryInfo['forum_state'],
  2472. $categoryInfo['work_state'],
  2473. $categoryInfo['wiki_state'],
  2474. $categoryInfo['max_student'],
  2475. $categoryInfo['self_reg_allowed'],
  2476. $categoryInfo['self_unreg_allowed'],
  2477. $categoryInfo['groups_per_user'],
  2478. ];
  2479. $count++;
  2480. }
  2481. }
  2482. $groups = self::get_group_list();
  2483. foreach ($groups as $groupInfo) {
  2484. $categoryTitle = null;
  2485. $categoryInfo = self::get_category($groupInfo['category_id']);
  2486. $groupSettings = self::get_group_properties($groupInfo['id']);
  2487. if (!empty($categoryInfo)) {
  2488. $categoryTitle = $categoryInfo['title'];
  2489. }
  2490. $users = self::getStudents($groupInfo['iid']);
  2491. $userList = [];
  2492. foreach ($users as $user) {
  2493. $user = api_get_user_info($user['user_id']);
  2494. $userList[] = $user['username'];
  2495. }
  2496. $tutors = self::getTutors($groupInfo);
  2497. $tutorList = [];
  2498. foreach ($tutors as $user) {
  2499. $user = api_get_user_info($user['user_id']);
  2500. $tutorList[] = $user['username'];
  2501. }
  2502. $userListToString = null;
  2503. if (!empty($userList)) {
  2504. $userListToString = implode(',', $userList);
  2505. }
  2506. $tutorListToString = null;
  2507. if (!empty($tutorList)) {
  2508. $tutorListToString = implode(',', $tutorList);
  2509. }
  2510. $data[$count] = [
  2511. $categoryTitle,
  2512. $groupSettings['name'],
  2513. $groupSettings['description'],
  2514. $groupSettings['announcements_state'],
  2515. $groupSettings['calendar_state'],
  2516. $groupSettings['chat_state'],
  2517. $groupSettings['doc_state'],
  2518. $groupSettings['forum_state'],
  2519. $groupSettings['work_state'],
  2520. $groupSettings['wiki_state'],
  2521. $groupSettings['maximum_number_of_students'],
  2522. $groupSettings['self_registration_allowed'],
  2523. $groupSettings['self_unregistration_allowed'],
  2524. null,
  2525. ];
  2526. if ($loadUsers) {
  2527. $data[$count][] = $userListToString;
  2528. $data[$count][] = $tutorListToString;
  2529. }
  2530. if (!empty($groupId)) {
  2531. if ($groupId == $groupInfo['id']) {
  2532. break;
  2533. }
  2534. }
  2535. $count++;
  2536. }
  2537. return $data;
  2538. }
  2539. /**
  2540. * @param string $default
  2541. */
  2542. public static function getSettingBar($default)
  2543. {
  2544. $activeSettings = null;
  2545. $activeTutor = null;
  2546. $activeMember = null;
  2547. switch ($default) {
  2548. case 'settings':
  2549. $activeSettings = 'active';
  2550. break;
  2551. case'tutor':
  2552. $activeTutor = 'active';
  2553. break;
  2554. case 'member':
  2555. $activeMember = 'active';
  2556. break;
  2557. }
  2558. $url = api_get_path(WEB_CODE_PATH).'group/%s?'.api_get_cidreq();
  2559. echo '
  2560. <ul class="toolbar-groups nav nav-tabs">
  2561. <li class="'.$activeSettings.'">
  2562. <a id="group_settings_tab" href="'.sprintf($url, 'settings.php').'">
  2563. '.Display::return_icon('settings.png').' '.get_lang('Settings').'
  2564. </a>
  2565. </li>
  2566. <li class="'.$activeMember.'">
  2567. <a id="group_members_tab" href="'.sprintf($url, 'member_settings.php').'">
  2568. '.Display::return_icon('user.png').' '.get_lang('GroupMembers').'</a>
  2569. </li>
  2570. <li class="'.$activeTutor.'">
  2571. <a id="group_tutors_tab" href="'.sprintf($url, 'tutor_settings.php').'">
  2572. '.Display::return_icon('teacher.png').' '.get_lang('GroupTutors').'
  2573. </a>
  2574. </li>
  2575. </ul>';
  2576. }
  2577. /**
  2578. * @param int $courseId
  2579. * @param string $keyword
  2580. *
  2581. * @return string
  2582. */
  2583. public static function getOverview($courseId, $keyword = null)
  2584. {
  2585. $content = null;
  2586. $categories = self::get_categories();
  2587. if (!empty($categories)) {
  2588. foreach ($categories as $category) {
  2589. if (api_get_setting('allow_group_categories') == 'true') {
  2590. $content .= '<h2>'.$category['title'].'</h2>';
  2591. }
  2592. if (!empty($keyword)) {
  2593. $groups = self::getGroupListFilterByName(
  2594. $keyword,
  2595. $category['id'],
  2596. $courseId
  2597. );
  2598. } else {
  2599. $groups = self::get_group_list($category['id']);
  2600. }
  2601. if (empty($groups)) {
  2602. $groups = self::get_group_list();
  2603. }
  2604. $content .= '<ul>';
  2605. if (!empty($groups)) {
  2606. foreach ($groups as $group) {
  2607. $content .= '<li>';
  2608. $content .= Display::tag(
  2609. 'h3',
  2610. Security::remove_XSS($group['name'])
  2611. );
  2612. $users = self::getTutors($group);
  2613. if (!empty($users)) {
  2614. $content .= '<ul>';
  2615. $content .= "<li>".Display::tag('h4', get_lang('Tutors'))."</li><ul>";
  2616. foreach ($users as $user) {
  2617. $user_info = api_get_user_info($user['user_id']);
  2618. $content .= '<li title="'.$user_info['username'].'">'.
  2619. $user_info['complete_name_with_username'].
  2620. '</li>';
  2621. }
  2622. $content .= '</ul>';
  2623. $content .= '</ul>';
  2624. }
  2625. $users = self::getStudents($group['id']);
  2626. if (!empty($users)) {
  2627. $content .= '<ul>';
  2628. $content .= "<li>".Display::tag('h4', get_lang('Students'))."</li><ul>";
  2629. foreach ($users as $user) {
  2630. $user_info = api_get_user_info($user['user_id']);
  2631. $content .= '<li title="'.$user_info['username'].'">'.
  2632. $user_info['complete_name_with_username'].
  2633. '</li>';
  2634. }
  2635. $content .= '</ul>';
  2636. $content .= '</ul>';
  2637. }
  2638. $content .= '</li>';
  2639. }
  2640. }
  2641. $content .= '</ul>';
  2642. }
  2643. }
  2644. return $content;
  2645. }
  2646. /**
  2647. * Returns the search form.
  2648. *
  2649. * @return string
  2650. */
  2651. public static function getSearchForm()
  2652. {
  2653. $url = api_get_path(WEB_CODE_PATH).'group/group_overview.php?'.api_get_cidreq();
  2654. $form = new FormValidator(
  2655. 'search_groups',
  2656. 'get',
  2657. $url,
  2658. null,
  2659. ['class' => 'form-search'],
  2660. FormValidator::LAYOUT_INLINE
  2661. );
  2662. $form->addElement('text', 'keyword');
  2663. $form->addButtonSearch();
  2664. return $form->toHtml();
  2665. }
  2666. /**
  2667. * @param int $groupId
  2668. * @param int $status
  2669. */
  2670. public static function setStatus($groupId, $status)
  2671. {
  2672. $groupInfo = self::get_group_properties($groupId);
  2673. $courseId = api_get_course_int_id();
  2674. if (!empty($groupInfo)) {
  2675. $table = Database::get_course_table(TABLE_GROUP);
  2676. $params = [
  2677. 'status' => intval($status),
  2678. ];
  2679. Database::update(
  2680. $table,
  2681. $params,
  2682. ['c_id = ? AND id = ?' => [$courseId, $groupId]]
  2683. );
  2684. }
  2685. }
  2686. /**
  2687. * @param int $groupId
  2688. */
  2689. public static function setVisible($groupId)
  2690. {
  2691. self::setStatus($groupId, 1);
  2692. }
  2693. /**
  2694. * @param int $groupId
  2695. */
  2696. public static function setInvisible($groupId)
  2697. {
  2698. self::setStatus($groupId, 0);
  2699. }
  2700. /**
  2701. * @param int $userId
  2702. * @param int $courseId
  2703. * @param array $groupInfo
  2704. * @param array $documentInfoToBeCheck
  2705. * @param bool $blockPage
  2706. *
  2707. * @return bool
  2708. */
  2709. public static function allowUploadEditDocument(
  2710. $userId,
  2711. $courseId,
  2712. $groupInfo,
  2713. $documentInfoToBeCheck = null,
  2714. $blockPage = false
  2715. ) {
  2716. // Admin and teachers can make any change no matter what
  2717. if (api_is_platform_admin() || api_is_allowed_to_edit(false, true)) {
  2718. return true;
  2719. }
  2720. if (empty($groupInfo) || !isset($groupInfo['id'])) {
  2721. if ($blockPage) {
  2722. api_not_allowed(true);
  2723. }
  2724. return false;
  2725. }
  2726. // Tutor can also make any change
  2727. $isTutor = self::is_tutor_of_group($userId, $groupInfo, $courseId);
  2728. if ($isTutor) {
  2729. return true;
  2730. }
  2731. // Just in case also check if document in group is available
  2732. if ($groupInfo['doc_state'] == 0) {
  2733. if ($blockPage) {
  2734. api_not_allowed(true);
  2735. }
  2736. return false;
  2737. }
  2738. // Default behaviour
  2739. $documentAccess = self::DOCUMENT_MODE_SHARE;
  2740. // Check category document access
  2741. /*$allowCategoryGroupDocumentAccess = api_get_configuration_value('group_category_document_access');
  2742. if ($allowCategoryGroupDocumentAccess) {
  2743. $category = GroupManager::get_category_from_group($groupInfo['iid']);
  2744. if (!empty($category) && isset($category['document_access'])) {
  2745. $documentAccess = (int) $category['document_access'];
  2746. }
  2747. }*/
  2748. // Check group document access
  2749. $allow = api_get_configuration_value('group_document_access');
  2750. if ($allow) {
  2751. if (isset($groupInfo['document_access'])) {
  2752. $documentAccess = (int) $groupInfo['document_access'];
  2753. }
  2754. }
  2755. // Check access for students
  2756. $result = false;
  2757. switch ($documentAccess) {
  2758. case self::DOCUMENT_MODE_SHARE:
  2759. // Default chamilo behaviour
  2760. // Student can upload his own content, cannot modify another content.
  2761. $isMember = self::is_subscribed($userId, $groupInfo);
  2762. if ($isMember) {
  2763. // No document to check, allow access to document feature.
  2764. if (empty($documentInfoToBeCheck)) {
  2765. $result = true;
  2766. } else {
  2767. // Member can only edit his own document
  2768. $authorId = isset($documentInfoToBeCheck['insert_user_id']) ? $documentInfoToBeCheck['insert_user_id'] : 0;
  2769. // If "insert_user_id" is not set, check the author id from c_item_property
  2770. if (empty($authorId) && isset($documentInfoToBeCheck['id'])) {
  2771. $documentInfo = api_get_item_property_info(
  2772. $courseId,
  2773. 'document',
  2774. $documentInfoToBeCheck['id'],
  2775. 0
  2776. );
  2777. // Try to find this document in the session
  2778. if (!empty($sessionId)) {
  2779. $documentInfo = api_get_item_property_info(
  2780. $courseId,
  2781. 'document',
  2782. $documentInfoToBeCheck['id'],
  2783. api_get_session_id()
  2784. );
  2785. }
  2786. if (!empty($documentInfo) && isset($documentInfo['insert_user_id'])) {
  2787. $authorId = $documentInfo['insert_user_id'];
  2788. }
  2789. }
  2790. if ($authorId == $userId) {
  2791. $result = true;
  2792. }
  2793. }
  2794. }
  2795. break;
  2796. case self::DOCUMENT_MODE_READ_ONLY:
  2797. // Student cannot upload content, cannot modify another content.
  2798. $result = false;
  2799. break;
  2800. case self::DOCUMENT_MODE_COLLABORATION:
  2801. // Student can upload content, can modify another content.
  2802. $isMember = self::is_subscribed($userId, $groupInfo);
  2803. if ($isMember) {
  2804. $result = true;
  2805. }
  2806. break;
  2807. }
  2808. if ($blockPage && $result == false) {
  2809. api_not_allowed(true);
  2810. }
  2811. return $result;
  2812. }
  2813. }