groupmanager.lib.php 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142
  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. *
  1998. * @return array
  1999. */
  2000. public static function getAllGroupPerUserSubscription($user_id)
  2001. {
  2002. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  2003. $table_tutor_user = Database::get_course_table(TABLE_GROUP_TUTOR);
  2004. $table_group = Database::get_course_table(TABLE_GROUP);
  2005. $user_id = intval($user_id);
  2006. $course_id = api_get_course_int_id();
  2007. $sql = "SELECT DISTINCT g.*
  2008. FROM $table_group g
  2009. LEFT JOIN $table_group_user gu
  2010. ON (gu.group_id = g.iid AND g.c_id = gu.c_id)
  2011. LEFT JOIN $table_tutor_user tu
  2012. ON (tu.group_id = g.iid AND g.c_id = tu.c_id)
  2013. WHERE
  2014. g.c_id = $course_id AND
  2015. (gu.user_id = $user_id OR tu.user_id = $user_id) ";
  2016. $res = Database::query($sql);
  2017. $groups = [];
  2018. while ($group = Database::fetch_array($res, 'ASSOC')) {
  2019. $groups[] = $group;
  2020. }
  2021. return $groups;
  2022. }
  2023. /**
  2024. * @param array $group_list
  2025. * @param int $category_id
  2026. *
  2027. * @return string
  2028. */
  2029. public static function process_groups($group_list, $category_id = 0)
  2030. {
  2031. global $charset;
  2032. $category_id = (int) $category_id;
  2033. $totalRegistered = 0;
  2034. $group_data = [];
  2035. $user_info = api_get_user_info();
  2036. $session_id = api_get_session_id();
  2037. $user_id = $user_info['user_id'];
  2038. $hideGroup = api_get_setting('hide_course_group_if_no_tools_available');
  2039. foreach ($group_list as $this_group) {
  2040. // Validation when belongs to a session
  2041. $session_img = api_get_session_image($this_group['session_id'], $user_info['status']);
  2042. // All the tutors of this group
  2043. $tutorsids_of_group = self::get_subscribed_tutors($this_group, true);
  2044. $isMember = self::is_subscribed($user_id, $this_group);
  2045. // Create a new table-row
  2046. $row = [];
  2047. // Checkbox
  2048. if (api_is_allowed_to_edit(false, true) && count($group_list) > 1) {
  2049. $row[] = $this_group['id'];
  2050. }
  2051. if (self::userHasAccessToBrowse($user_id, $this_group, $session_id)) {
  2052. // Group name
  2053. $groupNameClass = null;
  2054. if ($this_group['status'] == 0) {
  2055. $groupNameClass = 'muted';
  2056. }
  2057. $group_name = '<a class="'.$groupNameClass.'" href="group_space.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'">'.
  2058. Security::remove_XSS($this_group['name']).'</a> ';
  2059. $group_name2 = '';
  2060. if (api_get_configuration_value('extra')) {
  2061. $group_name2 = '<a href="group_space_tracking.php?cidReq='.api_get_course_id().'&gidReq='
  2062. .$this_group['id'].'">'.get_lang('suivi_de').''.stripslashes($this_group['name']).'</a>';
  2063. }
  2064. if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
  2065. $group_name .= Display::label(get_lang('OneMyGroups'), 'success');
  2066. } elseif ($isMember) {
  2067. $group_name .= Display::label(get_lang('MyGroup'), 'success');
  2068. }
  2069. if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
  2070. $group_name .= ' ('.$this_group['session_name'].')';
  2071. }
  2072. $group_name .= $session_img;
  2073. $row[] = $group_name.$group_name2.'<br />'.stripslashes(trim($this_group['description']));
  2074. } else {
  2075. if ($hideGroup === 'true') {
  2076. continue;
  2077. }
  2078. $row[] = $this_group['name'].'<br />'.stripslashes(trim($this_group['description']));
  2079. }
  2080. // Tutor name
  2081. $tutor_info = '';
  2082. if (count($tutorsids_of_group) > 0) {
  2083. foreach ($tutorsids_of_group as $tutor_id) {
  2084. $tutor = api_get_user_info($tutor_id);
  2085. $username = api_htmlentities(
  2086. sprintf(get_lang('LoginX'), $tutor['username']),
  2087. ENT_QUOTES
  2088. );
  2089. if (api_get_setting('show_email_addresses') === 'true') {
  2090. $tutor_info .= Display::tag(
  2091. 'span',
  2092. Display::encrypted_mailto_link(
  2093. $tutor['mail'],
  2094. $tutor['complete_name']
  2095. ),
  2096. ['title' => $username]
  2097. ).', ';
  2098. } else {
  2099. if (api_is_allowed_to_edit()) {
  2100. $tutor_info .= Display::tag(
  2101. 'span',
  2102. Display::encrypted_mailto_link(
  2103. $tutor['mail'],
  2104. $tutor['complete_name_with_username']
  2105. ),
  2106. ['title' => $username]
  2107. ).', ';
  2108. } else {
  2109. $tutor_info .= Display::tag(
  2110. 'span',
  2111. $tutor['complete_name'],
  2112. ['title' => $username]
  2113. ).', ';
  2114. }
  2115. }
  2116. }
  2117. }
  2118. $tutor_info = api_substr(
  2119. $tutor_info,
  2120. 0,
  2121. api_strlen($tutor_info) - 2
  2122. );
  2123. $row[] = $tutor_info;
  2124. // Max number of members in group
  2125. $max_members = $this_group['maximum_number_of_members'] == self::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / '.$this_group['maximum_number_of_members'];
  2126. // Number of members in group
  2127. $row[] = $this_group['number_of_members'].$max_members;
  2128. // Self-registration / unregistration
  2129. if (!api_is_allowed_to_edit(false, true)) {
  2130. if (self::is_self_registration_allowed($user_id, $this_group)) {
  2131. $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>';
  2132. } elseif (self::is_self_unregistration_allowed($user_id, $this_group)) {
  2133. $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>';
  2134. } else {
  2135. $row[] = '-';
  2136. }
  2137. }
  2138. $url = api_get_path(WEB_CODE_PATH).'group/';
  2139. // Edit-links
  2140. if (api_is_allowed_to_edit(false, true) &&
  2141. !(api_is_session_general_coach() && intval($this_group['session_id']) != $session_id)
  2142. ) {
  2143. $edit_actions = '<a href="'.$url.'settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('Edit').'">'.
  2144. Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2145. if ($this_group['status'] == 1) {
  2146. $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').'">'.
  2147. Display::return_icon('visible.png', get_lang('Hide'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2148. } else {
  2149. $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').'">'.
  2150. Display::return_icon('invisible.png', get_lang('Show'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2151. }
  2152. $edit_actions .= '<a href="'.$url.'member_settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('GroupMembers').'">'.
  2153. Display::return_icon('user.png', get_lang('GroupMembers'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2154. $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').'">'.
  2155. Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2156. $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').'">'.
  2157. Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2158. $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').'">'.
  2159. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2160. $row[] = $edit_actions;
  2161. }
  2162. if (!empty($this_group['nbMember'])) {
  2163. $totalRegistered = $totalRegistered + $this_group['nbMember'];
  2164. }
  2165. $group_data[] = $row;
  2166. } // end loop
  2167. // If no groups then don't show the table (only for students)
  2168. if (!api_is_allowed_to_edit(true, false)) {
  2169. if (empty($group_data)) {
  2170. return '';
  2171. }
  2172. }
  2173. $table = new SortableTableFromArrayConfig(
  2174. $group_data,
  2175. 1,
  2176. 20,
  2177. 'group_category_'.$category_id
  2178. );
  2179. $table->set_additional_parameters(['category' => $category_id]);
  2180. $column = 0;
  2181. if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
  2182. $table->set_header($column++, '', false);
  2183. }
  2184. $table->set_header($column++, get_lang('Groups'));
  2185. $table->set_header($column++, get_lang('GroupTutor'));
  2186. $table->set_header($column++, get_lang('Registered'), false);
  2187. if (!api_is_allowed_to_edit(false, true)) {
  2188. // If self-registration allowed
  2189. $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
  2190. }
  2191. if (api_is_allowed_to_edit(false, true)) {
  2192. // Only for course administrator
  2193. $table->set_header($column++, get_lang('Modify'), false);
  2194. $form_actions = [];
  2195. $form_actions['fill_selected'] = get_lang('FillGroup');
  2196. $form_actions['empty_selected'] = get_lang('EmptyGroup');
  2197. $form_actions['delete_selected'] = get_lang('Delete');
  2198. if (count($group_list) > 1) {
  2199. $table->set_form_actions($form_actions, 'group');
  2200. }
  2201. }
  2202. return $table->return_table();
  2203. }
  2204. /**
  2205. * @param array $groupData
  2206. * @param bool $deleteNotInArray
  2207. *
  2208. * @return array
  2209. */
  2210. public static function importCategoriesAndGroupsFromArray(
  2211. $groupData,
  2212. $deleteNotInArray = false
  2213. ) {
  2214. $result = [];
  2215. $elementsFound = [
  2216. 'categories' => [],
  2217. 'groups' => [],
  2218. ];
  2219. $courseCode = api_get_course_id();
  2220. $sessionId = api_get_session_id();
  2221. $groupCategories = self::get_categories();
  2222. if (empty($groupCategories)) {
  2223. $result['error'][] = get_lang('CreateACategory');
  2224. return $result;
  2225. }
  2226. foreach ($groupData as $data) {
  2227. $isCategory = empty($data['group']) ? true : false;
  2228. if ($isCategory) {
  2229. $categoryInfo = self::getCategoryByTitle($data['category']);
  2230. $categoryId = $categoryInfo['id'];
  2231. if (!empty($categoryInfo)) {
  2232. // Update
  2233. self::update_category(
  2234. $categoryId,
  2235. $data['category'],
  2236. $data['description'],
  2237. $data['doc_state'],
  2238. $data['work_state'],
  2239. $data['calendar_state'],
  2240. $data['announcements_state'],
  2241. $data['forum_state'],
  2242. $data['wiki_state'],
  2243. $data['chat_state'],
  2244. $data['self_reg_allowed'],
  2245. $data['self_unreg_allowed'],
  2246. $data['max_student'],
  2247. $data['groups_per_user']
  2248. );
  2249. $data['category_id'] = $categoryId;
  2250. $result['updated']['category'][] = $data;
  2251. } else {
  2252. // Add
  2253. $categoryId = self::create_category(
  2254. $data['category'],
  2255. $data['description'],
  2256. $data['doc_state'],
  2257. $data['work_state'],
  2258. $data['calendar_state'],
  2259. $data['announcements_state'],
  2260. $data['forum_state'],
  2261. $data['wiki_state'],
  2262. $data['chat_state'],
  2263. $data['self_reg_allowed'],
  2264. $data['self_unreg_allowed'],
  2265. $data['max_student'],
  2266. $data['groups_per_user']
  2267. );
  2268. if ($categoryId) {
  2269. $data['category_id'] = $categoryId;
  2270. $result['added']['category'][] = $data;
  2271. }
  2272. }
  2273. $elementsFound['categories'][] = $categoryId;
  2274. } else {
  2275. $groupInfo = self::getGroupByName($data['group']);
  2276. $categoryInfo = [];
  2277. if (isset($data['category'])) {
  2278. $categoryInfo = self::getCategoryByTitle($data['category']);
  2279. }
  2280. $categoryId = null;
  2281. if (!empty($categoryInfo)) {
  2282. $categoryId = $categoryInfo['id'];
  2283. } else {
  2284. if (!empty($groupCategories) && isset($groupCategories[0])) {
  2285. $defaultGroupCategory = $groupCategories[0];
  2286. $categoryId = $defaultGroupCategory['id'];
  2287. }
  2288. }
  2289. if (empty($groupInfo)) {
  2290. // Add
  2291. $groupId = self::create_group(
  2292. $data['group'],
  2293. $categoryId,
  2294. null,
  2295. $data['max_student']
  2296. );
  2297. if ($groupId) {
  2298. self::set_group_properties(
  2299. $groupId,
  2300. $data['group'],
  2301. $data['description'],
  2302. $data['max_student'],
  2303. $data['doc_state'],
  2304. $data['work_state'],
  2305. $data['calendar_state'],
  2306. $data['announcements_state'],
  2307. $data['forum_state'],
  2308. $data['wiki_state'],
  2309. $data['chat_state'],
  2310. $data['self_reg_allowed'],
  2311. $data['self_unreg_allowed'],
  2312. $categoryId
  2313. );
  2314. $data['group_id'] = $groupId;
  2315. $result['added']['group'][] = $data;
  2316. }
  2317. $groupInfo = self::get_group_properties($groupId, true);
  2318. } else {
  2319. // Update
  2320. $groupId = $groupInfo['id'];
  2321. self::set_group_properties(
  2322. $groupId,
  2323. $data['group'],
  2324. $data['description'],
  2325. $data['max_student'],
  2326. $data['doc_state'],
  2327. $data['work_state'],
  2328. $data['calendar_state'],
  2329. $data['announcements_state'],
  2330. $data['forum_state'],
  2331. $data['wiki_state'],
  2332. $data['chat_state'],
  2333. $data['self_reg_allowed'],
  2334. $data['self_unreg_allowed'],
  2335. $categoryId
  2336. );
  2337. $data['group_id'] = $groupId;
  2338. $result['updated']['group'][] = $data;
  2339. $groupInfo = self::get_group_properties($groupId);
  2340. }
  2341. $students = isset($data['students']) ? explode(',', $data['students']) : [];
  2342. if (!empty($students)) {
  2343. $studentUserIdList = [];
  2344. foreach ($students as $student) {
  2345. $userInfo = api_get_user_info_from_username($student);
  2346. if (!$userInfo) {
  2347. continue;
  2348. }
  2349. if (!CourseManager::is_user_subscribed_in_course(
  2350. $userInfo['user_id'],
  2351. $courseCode,
  2352. !empty($sessionId),
  2353. $sessionId
  2354. )
  2355. ) {
  2356. Display::addFlash(
  2357. Display::return_message(
  2358. sprintf(
  2359. get_lang('StudentXIsNotSubscribedToCourse'),
  2360. $userInfo['complete_name']
  2361. ),
  2362. 'warning'
  2363. )
  2364. );
  2365. continue;
  2366. }
  2367. $studentUserIdList[] = $userInfo['user_id'];
  2368. }
  2369. self::subscribe_users($studentUserIdList, $groupInfo);
  2370. }
  2371. $tutors = isset($data['tutors']) ? explode(',', $data['tutors']) : [];
  2372. if (!empty($tutors)) {
  2373. $tutorIdList = [];
  2374. foreach ($tutors as $tutor) {
  2375. $userInfo = api_get_user_info_from_username($tutor);
  2376. if (!$userInfo) {
  2377. continue;
  2378. }
  2379. if (!CourseManager::is_user_subscribed_in_course(
  2380. $userInfo['user_id'],
  2381. $courseCode,
  2382. !empty($sessionId),
  2383. $sessionId
  2384. )
  2385. ) {
  2386. Display::addFlash(
  2387. Display::return_message(
  2388. sprintf(get_lang('TutorXIsNotSubscribedToCourse'), $userInfo['complete_name']),
  2389. 'warning'
  2390. )
  2391. );
  2392. continue;
  2393. }
  2394. $tutorIdList[] = $userInfo['user_id'];
  2395. }
  2396. self::subscribe_tutors($tutorIdList, $groupInfo);
  2397. }
  2398. $elementsFound['groups'][] = $groupId;
  2399. }
  2400. }
  2401. if ($deleteNotInArray) {
  2402. // Check categories
  2403. $categories = self::get_categories();
  2404. foreach ($categories as $category) {
  2405. if (!in_array($category['id'], $elementsFound['categories'])) {
  2406. self::delete_category($category['id']);
  2407. $category['category'] = $category['title'];
  2408. $result['deleted']['category'][] = $category;
  2409. }
  2410. }
  2411. $groups = self::get_groups();
  2412. foreach ($groups as $group) {
  2413. if (!in_array($group['iid'], $elementsFound['groups'])) {
  2414. self::deleteGroup($group);
  2415. $group['group'] = $group['name'];
  2416. $result['deleted']['group'][] = $group;
  2417. }
  2418. }
  2419. }
  2420. return $result;
  2421. }
  2422. /**
  2423. * Export all categories/group from a course to an array.
  2424. * This function works only in a context of a course.
  2425. *
  2426. * @param int $groupId
  2427. * @param bool $loadUsers
  2428. *
  2429. * @return array
  2430. */
  2431. public static function exportCategoriesAndGroupsToArray($groupId = null, $loadUsers = false)
  2432. {
  2433. $data = [];
  2434. $data[] = [
  2435. 'category',
  2436. 'group',
  2437. 'description',
  2438. 'announcements_state',
  2439. 'calendar_state',
  2440. 'chat_state',
  2441. 'doc_state',
  2442. 'forum_state',
  2443. 'work_state',
  2444. 'wiki_state',
  2445. 'max_student',
  2446. 'self_reg_allowed',
  2447. 'self_unreg_allowed',
  2448. 'groups_per_user',
  2449. ];
  2450. $count = 1;
  2451. if ($loadUsers) {
  2452. $data[0][] = 'students';
  2453. $data[0][] = 'tutors';
  2454. }
  2455. if ($loadUsers == false) {
  2456. $categories = self::get_categories();
  2457. foreach ($categories as $categoryInfo) {
  2458. $data[$count] = [
  2459. $categoryInfo['title'],
  2460. null,
  2461. $categoryInfo['description'],
  2462. $categoryInfo['announcements_state'],
  2463. $categoryInfo['calendar_state'],
  2464. $categoryInfo['chat_state'],
  2465. $categoryInfo['doc_state'],
  2466. $categoryInfo['forum_state'],
  2467. $categoryInfo['work_state'],
  2468. $categoryInfo['wiki_state'],
  2469. $categoryInfo['max_student'],
  2470. $categoryInfo['self_reg_allowed'],
  2471. $categoryInfo['self_unreg_allowed'],
  2472. $categoryInfo['groups_per_user'],
  2473. ];
  2474. $count++;
  2475. }
  2476. }
  2477. $groups = self::get_group_list();
  2478. foreach ($groups as $groupInfo) {
  2479. $categoryTitle = null;
  2480. $categoryInfo = self::get_category($groupInfo['category_id']);
  2481. $groupSettings = self::get_group_properties($groupInfo['id']);
  2482. if (!empty($categoryInfo)) {
  2483. $categoryTitle = $categoryInfo['title'];
  2484. }
  2485. $users = self::getStudents($groupInfo['iid']);
  2486. $userList = [];
  2487. foreach ($users as $user) {
  2488. $user = api_get_user_info($user['user_id']);
  2489. $userList[] = $user['username'];
  2490. }
  2491. $tutors = self::getTutors($groupInfo);
  2492. $tutorList = [];
  2493. foreach ($tutors as $user) {
  2494. $user = api_get_user_info($user['user_id']);
  2495. $tutorList[] = $user['username'];
  2496. }
  2497. $userListToString = null;
  2498. if (!empty($userList)) {
  2499. $userListToString = implode(',', $userList);
  2500. }
  2501. $tutorListToString = null;
  2502. if (!empty($tutorList)) {
  2503. $tutorListToString = implode(',', $tutorList);
  2504. }
  2505. $data[$count] = [
  2506. $categoryTitle,
  2507. $groupSettings['name'],
  2508. $groupSettings['description'],
  2509. $groupSettings['announcements_state'],
  2510. $groupSettings['calendar_state'],
  2511. $groupSettings['chat_state'],
  2512. $groupSettings['doc_state'],
  2513. $groupSettings['forum_state'],
  2514. $groupSettings['work_state'],
  2515. $groupSettings['wiki_state'],
  2516. $groupSettings['maximum_number_of_students'],
  2517. $groupSettings['self_registration_allowed'],
  2518. $groupSettings['self_unregistration_allowed'],
  2519. null,
  2520. ];
  2521. if ($loadUsers) {
  2522. $data[$count][] = $userListToString;
  2523. $data[$count][] = $tutorListToString;
  2524. }
  2525. if (!empty($groupId)) {
  2526. if ($groupId == $groupInfo['id']) {
  2527. break;
  2528. }
  2529. }
  2530. $count++;
  2531. }
  2532. return $data;
  2533. }
  2534. /**
  2535. * @param string $default
  2536. */
  2537. public static function getSettingBar($default)
  2538. {
  2539. $activeSettings = null;
  2540. $activeTutor = null;
  2541. $activeMember = null;
  2542. switch ($default) {
  2543. case 'settings':
  2544. $activeSettings = 'active';
  2545. break;
  2546. case'tutor':
  2547. $activeTutor = 'active';
  2548. break;
  2549. case 'member':
  2550. $activeMember = 'active';
  2551. break;
  2552. }
  2553. $url = api_get_path(WEB_CODE_PATH).'group/%s?'.api_get_cidreq();
  2554. echo '
  2555. <ul class="toolbar-groups nav nav-tabs">
  2556. <li class="'.$activeSettings.'">
  2557. <a id="group_settings_tab" href="'.sprintf($url, 'settings.php').'">
  2558. '.Display::return_icon('settings.png').' '.get_lang('Settings').'
  2559. </a>
  2560. </li>
  2561. <li class="'.$activeMember.'">
  2562. <a id="group_members_tab" href="'.sprintf($url, 'member_settings.php').'">
  2563. '.Display::return_icon('user.png').' '.get_lang('GroupMembers').'</a>
  2564. </li>
  2565. <li class="'.$activeTutor.'">
  2566. <a id="group_tutors_tab" href="'.sprintf($url, 'tutor_settings.php').'">
  2567. '.Display::return_icon('teacher.png').' '.get_lang('GroupTutors').'
  2568. </a>
  2569. </li>
  2570. </ul>';
  2571. }
  2572. /**
  2573. * @param int $courseId
  2574. * @param string $keyword
  2575. *
  2576. * @return string
  2577. */
  2578. public static function getOverview($courseId, $keyword = null)
  2579. {
  2580. $content = null;
  2581. $categories = self::get_categories();
  2582. if (!empty($categories)) {
  2583. foreach ($categories as $category) {
  2584. if (api_get_setting('allow_group_categories') == 'true') {
  2585. $content .= '<h2>'.$category['title'].'</h2>';
  2586. }
  2587. if (!empty($keyword)) {
  2588. $groups = self::getGroupListFilterByName(
  2589. $keyword,
  2590. $category['id'],
  2591. $courseId
  2592. );
  2593. } else {
  2594. $groups = self::get_group_list($category['id']);
  2595. }
  2596. if (empty($groups)) {
  2597. $groups = self::get_group_list();
  2598. }
  2599. $content .= '<ul>';
  2600. if (!empty($groups)) {
  2601. foreach ($groups as $group) {
  2602. $content .= '<li>';
  2603. $content .= Display::tag(
  2604. 'h3',
  2605. Security::remove_XSS($group['name'])
  2606. );
  2607. $users = self::getTutors($group);
  2608. if (!empty($users)) {
  2609. $content .= '<ul>';
  2610. $content .= "<li>".Display::tag('h4', get_lang('Tutors'))."</li><ul>";
  2611. foreach ($users as $user) {
  2612. $user_info = api_get_user_info($user['user_id']);
  2613. $content .= '<li title="'.$user_info['username'].'">'.
  2614. $user_info['complete_name_with_username'].
  2615. '</li>';
  2616. }
  2617. $content .= '</ul>';
  2618. $content .= '</ul>';
  2619. }
  2620. $users = self::getStudents($group['id']);
  2621. if (!empty($users)) {
  2622. $content .= '<ul>';
  2623. $content .= "<li>".Display::tag('h4', get_lang('Students'))."</li><ul>";
  2624. foreach ($users as $user) {
  2625. $user_info = api_get_user_info($user['user_id']);
  2626. $content .= '<li title="'.$user_info['username'].'">'.
  2627. $user_info['complete_name_with_username'].
  2628. '</li>';
  2629. }
  2630. $content .= '</ul>';
  2631. $content .= '</ul>';
  2632. }
  2633. $content .= '</li>';
  2634. }
  2635. }
  2636. $content .= '</ul>';
  2637. }
  2638. }
  2639. return $content;
  2640. }
  2641. /**
  2642. * Returns the search form.
  2643. *
  2644. * @return string
  2645. */
  2646. public static function getSearchForm()
  2647. {
  2648. $url = api_get_path(WEB_CODE_PATH).'group/group_overview.php?'.api_get_cidreq();
  2649. $form = new FormValidator(
  2650. 'search_groups',
  2651. 'get',
  2652. $url,
  2653. null,
  2654. ['class' => 'form-search'],
  2655. FormValidator::LAYOUT_INLINE
  2656. );
  2657. $form->addElement('text', 'keyword');
  2658. $form->addButtonSearch();
  2659. return $form->toHtml();
  2660. }
  2661. /**
  2662. * @param int $groupId
  2663. * @param int $status
  2664. */
  2665. public static function setStatus($groupId, $status)
  2666. {
  2667. $groupInfo = self::get_group_properties($groupId);
  2668. $courseId = api_get_course_int_id();
  2669. if (!empty($groupInfo)) {
  2670. $table = Database::get_course_table(TABLE_GROUP);
  2671. $params = [
  2672. 'status' => intval($status),
  2673. ];
  2674. Database::update(
  2675. $table,
  2676. $params,
  2677. ['c_id = ? AND id = ?' => [$courseId, $groupId]]
  2678. );
  2679. }
  2680. }
  2681. /**
  2682. * @param int $groupId
  2683. */
  2684. public static function setVisible($groupId)
  2685. {
  2686. self::setStatus($groupId, 1);
  2687. }
  2688. /**
  2689. * @param int $groupId
  2690. */
  2691. public static function setInvisible($groupId)
  2692. {
  2693. self::setStatus($groupId, 0);
  2694. }
  2695. /**
  2696. * @param int $userId
  2697. * @param int $courseId
  2698. * @param array $groupInfo
  2699. * @param array $documentInfoToBeCheck
  2700. * @param bool $blockPage
  2701. *
  2702. * @return bool
  2703. */
  2704. public static function allowUploadEditDocument(
  2705. $userId,
  2706. $courseId,
  2707. $groupInfo,
  2708. $documentInfoToBeCheck = null,
  2709. $blockPage = false
  2710. ) {
  2711. // Admin and teachers can make any change no matter what
  2712. if (api_is_platform_admin() || api_is_allowed_to_edit(false, true)) {
  2713. return true;
  2714. }
  2715. if (empty($groupInfo) || !isset($groupInfo['id'])) {
  2716. if ($blockPage) {
  2717. api_not_allowed(true);
  2718. }
  2719. return false;
  2720. }
  2721. // Tutor can also make any change
  2722. $isTutor = self::is_tutor_of_group($userId, $groupInfo, $courseId);
  2723. if ($isTutor) {
  2724. return true;
  2725. }
  2726. // Just in case also check if document in group is available
  2727. if ($groupInfo['doc_state'] == 0) {
  2728. if ($blockPage) {
  2729. api_not_allowed(true);
  2730. }
  2731. return false;
  2732. }
  2733. // Default behaviour
  2734. $documentAccess = self::DOCUMENT_MODE_SHARE;
  2735. // Check category document access
  2736. /*$allowCategoryGroupDocumentAccess = api_get_configuration_value('group_category_document_access');
  2737. if ($allowCategoryGroupDocumentAccess) {
  2738. $category = GroupManager::get_category_from_group($groupInfo['iid']);
  2739. if (!empty($category) && isset($category['document_access'])) {
  2740. $documentAccess = (int) $category['document_access'];
  2741. }
  2742. }*/
  2743. // Check group document access
  2744. $allow = api_get_configuration_value('group_document_access');
  2745. if ($allow) {
  2746. if (isset($groupInfo['document_access'])) {
  2747. $documentAccess = (int) $groupInfo['document_access'];
  2748. }
  2749. }
  2750. // Check access for students
  2751. $result = false;
  2752. switch ($documentAccess) {
  2753. case self::DOCUMENT_MODE_SHARE:
  2754. // Default chamilo behaviour
  2755. // Student can upload his own content, cannot modify another content.
  2756. $isMember = self::is_subscribed($userId, $groupInfo);
  2757. if ($isMember) {
  2758. // No document to check, allow access to document feature.
  2759. if (empty($documentInfoToBeCheck)) {
  2760. $result = true;
  2761. } else {
  2762. // Member can only edit his own document
  2763. $authorId = isset($documentInfoToBeCheck['insert_user_id']) ? $documentInfoToBeCheck['insert_user_id'] : 0;
  2764. // If "insert_user_id" is not set, check the author id from c_item_property
  2765. if (empty($authorId) && isset($documentInfoToBeCheck['id'])) {
  2766. $documentInfo = api_get_item_property_info(
  2767. $courseId,
  2768. 'document',
  2769. $documentInfoToBeCheck['id'],
  2770. 0
  2771. );
  2772. // Try to find this document in the session
  2773. if (!empty($sessionId)) {
  2774. $documentInfo = api_get_item_property_info(
  2775. $courseId,
  2776. 'document',
  2777. $documentInfoToBeCheck['id'],
  2778. api_get_session_id()
  2779. );
  2780. }
  2781. if (!empty($documentInfo) && isset($documentInfo['insert_user_id'])) {
  2782. $authorId = $documentInfo['insert_user_id'];
  2783. }
  2784. }
  2785. if ($authorId == $userId) {
  2786. $result = true;
  2787. }
  2788. }
  2789. }
  2790. break;
  2791. case self::DOCUMENT_MODE_READ_ONLY:
  2792. // Student cannot upload content, cannot modify another content.
  2793. $result = false;
  2794. break;
  2795. case self::DOCUMENT_MODE_COLLABORATION:
  2796. // Student can upload content, can modify another content.
  2797. $isMember = self::is_subscribed($userId, $groupInfo);
  2798. if ($isMember) {
  2799. $result = true;
  2800. }
  2801. break;
  2802. }
  2803. if ($blockPage && $result == false) {
  2804. api_not_allowed(true);
  2805. }
  2806. return $result;
  2807. }
  2808. }