groupmanager.lib.php 109 KB

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