groupmanager.lib.php 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154
  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 = (int) $user_id;
  1762. $group_id = (int) $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. }
  1773. return false;
  1774. }
  1775. /**
  1776. * Is the user part of this group? This can be a tutor or a normal member
  1777. * you should use this function if the access to a tool or functionality is
  1778. * restricted to the people who are actually in the group
  1779. * before you had to check if the user was
  1780. * 1. a member of the group OR
  1781. * 2. a tutor of the group. This function combines both.
  1782. *
  1783. * @param int $user_id the id of the user
  1784. * @param array $groupInfo
  1785. *
  1786. * @return bool true/false
  1787. *
  1788. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1789. */
  1790. public static function is_user_in_group($user_id, $groupInfo)
  1791. {
  1792. $member = self::is_subscribed($user_id, $groupInfo);
  1793. if ($member) {
  1794. return true;
  1795. }
  1796. $tutor = self::is_tutor_of_group($user_id, $groupInfo);
  1797. if ($tutor) {
  1798. return true;
  1799. }
  1800. return false;
  1801. }
  1802. /**
  1803. * Get all group's from a given course in which a given user is unsubscribed.
  1804. *
  1805. * @author Patrick Cool
  1806. *
  1807. * @param int $course_id retrieve the groups for
  1808. * @param int $user_id the ID of the user you want to know all its group memberships
  1809. *
  1810. * @return array
  1811. */
  1812. public static function get_group_ids($course_id, $user_id)
  1813. {
  1814. $groups = [];
  1815. $tbl_group = Database::get_course_table(TABLE_GROUP_USER);
  1816. $tbl_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
  1817. $user_id = intval($user_id);
  1818. $course_id = intval($course_id);
  1819. $sql = "SELECT group_id FROM $tbl_group
  1820. WHERE c_id = $course_id AND user_id = '$user_id'";
  1821. $result = Database::query($sql);
  1822. if ($result) {
  1823. while ($row = Database::fetch_array($result)) {
  1824. $groups[] = $row['group_id'];
  1825. }
  1826. }
  1827. //Also loading if i'm the tutor
  1828. $sql = "SELECT group_id FROM $tbl_group_tutor
  1829. WHERE c_id = $course_id AND user_id = '$user_id'";
  1830. $result = Database::query($sql);
  1831. if ($result) {
  1832. while ($row = Database::fetch_array($result)) {
  1833. $groups[] = $row['group_id'];
  1834. }
  1835. }
  1836. if (!empty($groups)) {
  1837. array_filter($groups);
  1838. }
  1839. return $groups;
  1840. }
  1841. /**
  1842. * Check if a user has access to a certain group tool.
  1843. *
  1844. * @param int $user_id The user id
  1845. * @param int $group_id The group iid
  1846. * @param string $tool The tool to check the access rights. This should be
  1847. * one of constants: GROUP_TOOL_DOCUMENTS
  1848. *
  1849. * @return bool true if the given user has access to the given tool in the
  1850. * given course
  1851. */
  1852. public static function user_has_access($user_id, $group_id, $tool)
  1853. {
  1854. // Admin have access everywhere
  1855. if (api_is_platform_admin()) {
  1856. return true;
  1857. }
  1858. // Course admin also have access to everything
  1859. if (api_is_allowed_to_edit(false, true, true)) {
  1860. return true;
  1861. }
  1862. switch ($tool) {
  1863. case self::GROUP_TOOL_FORUM:
  1864. $key = 'forum_state';
  1865. break;
  1866. case self::GROUP_TOOL_DOCUMENTS:
  1867. $key = 'doc_state';
  1868. break;
  1869. case self::GROUP_TOOL_CALENDAR:
  1870. $key = 'calendar_state';
  1871. break;
  1872. case self::GROUP_TOOL_ANNOUNCEMENT:
  1873. $key = 'announcements_state';
  1874. break;
  1875. case self::GROUP_TOOL_WORK:
  1876. $key = 'work_state';
  1877. break;
  1878. case self::GROUP_TOOL_WIKI:
  1879. $key = 'wiki_state';
  1880. break;
  1881. case self::GROUP_TOOL_CHAT:
  1882. $key = 'chat_state';
  1883. break;
  1884. default:
  1885. return false;
  1886. }
  1887. // Check group properties
  1888. $groupInfo = self::get_group_properties($group_id, true);
  1889. if (empty($groupInfo)) {
  1890. return false;
  1891. }
  1892. if ($groupInfo['status'] == 0) {
  1893. return false;
  1894. }
  1895. if (!isset($groupInfo[$key])) {
  1896. return false;
  1897. }
  1898. $status = $groupInfo[$key];
  1899. switch ($status) {
  1900. case self::TOOL_NOT_AVAILABLE:
  1901. return false;
  1902. break;
  1903. case self::TOOL_PUBLIC:
  1904. return true;
  1905. break;
  1906. case self::TOOL_PRIVATE:
  1907. $userIsInGroup = self::is_user_in_group($user_id, $groupInfo);
  1908. if ($userIsInGroup) {
  1909. return true;
  1910. }
  1911. break;
  1912. case self::TOOL_PRIVATE_BETWEEN_USERS:
  1913. // Only works for announcements for now
  1914. $userIsInGroup = self::is_user_in_group($user_id, $groupInfo);
  1915. if ($userIsInGroup && $tool == self::GROUP_TOOL_ANNOUNCEMENT) {
  1916. return true;
  1917. }
  1918. break;
  1919. }
  1920. return false;
  1921. }
  1922. /**
  1923. * @param int $userId
  1924. * @param array $groupInfo
  1925. * @param int $sessionId
  1926. *
  1927. * @return bool
  1928. */
  1929. public static function userHasAccessToBrowse($userId, $groupInfo, $sessionId = 0)
  1930. {
  1931. if (empty($groupInfo)) {
  1932. return false;
  1933. }
  1934. if (api_is_platform_admin()) {
  1935. return true;
  1936. }
  1937. if (api_is_allowed_to_edit(false, true, true)) {
  1938. return true;
  1939. }
  1940. if (!empty($sessionId)) {
  1941. if (api_is_coach($sessionId, api_get_course_int_id())) {
  1942. return true;
  1943. }
  1944. if (api_is_drh()) {
  1945. if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
  1946. return true;
  1947. }
  1948. }
  1949. }
  1950. $groupId = $groupInfo['iid'];
  1951. if (self::is_tutor_of_group($userId, $groupInfo)) {
  1952. return true;
  1953. }
  1954. if ($groupInfo['status'] == 0) {
  1955. return false;
  1956. }
  1957. if (self::user_has_access($userId, $groupId, self::GROUP_TOOL_FORUM) ||
  1958. self::user_has_access($userId, $groupId, self::GROUP_TOOL_DOCUMENTS) ||
  1959. self::user_has_access($userId, $groupId, self::GROUP_TOOL_CALENDAR) ||
  1960. self::user_has_access($userId, $groupId, self::GROUP_TOOL_ANNOUNCEMENT) ||
  1961. self::user_has_access($userId, $groupId, self::GROUP_TOOL_WORK) ||
  1962. self::user_has_access($userId, $groupId, self::GROUP_TOOL_WIKI) ||
  1963. self::user_has_access($userId, $groupId, self::GROUP_TOOL_CHAT)
  1964. ) {
  1965. return true;
  1966. }
  1967. if (api_is_session_general_coach() && $groupInfo['session_id'] == $sessionId) {
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972. /**
  1973. * Get all groups where a specific user is subscribed.
  1974. *
  1975. * @param int $user_id
  1976. *
  1977. * @return array
  1978. */
  1979. public static function get_user_group_name($user_id)
  1980. {
  1981. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  1982. $table_group = Database::get_course_table(TABLE_GROUP);
  1983. $user_id = intval($user_id);
  1984. $course_id = api_get_course_int_id();
  1985. $sql = "SELECT name
  1986. FROM $table_group g
  1987. INNER JOIN $table_group_user gu
  1988. ON (gu.group_id = g.iid)
  1989. WHERE
  1990. gu.c_id= $course_id AND
  1991. g.c_id= $course_id AND
  1992. gu.user_id = $user_id";
  1993. $res = Database::query($sql);
  1994. $groups = [];
  1995. while ($group = Database::fetch_array($res)) {
  1996. $groups[] .= $group['name'];
  1997. }
  1998. return $groups;
  1999. }
  2000. /**
  2001. * Get all groups where a specific user is subscribed.
  2002. *
  2003. * @param int $user_id
  2004. * @param int $courseId
  2005. *
  2006. * @return array
  2007. */
  2008. public static function getAllGroupPerUserSubscription($user_id, $courseId = 0)
  2009. {
  2010. $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
  2011. $table_tutor_user = Database::get_course_table(TABLE_GROUP_TUTOR);
  2012. $table_group = Database::get_course_table(TABLE_GROUP);
  2013. $user_id = (int) $user_id;
  2014. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  2015. $sql = "SELECT DISTINCT g.*
  2016. FROM $table_group g
  2017. LEFT JOIN $table_group_user gu
  2018. ON (gu.group_id = g.iid AND g.c_id = gu.c_id)
  2019. LEFT JOIN $table_tutor_user tu
  2020. ON (tu.group_id = g.iid AND g.c_id = tu.c_id)
  2021. WHERE
  2022. g.c_id = $courseId AND
  2023. (gu.user_id = $user_id OR tu.user_id = $user_id) ";
  2024. $res = Database::query($sql);
  2025. $groups = [];
  2026. while ($group = Database::fetch_array($res, 'ASSOC')) {
  2027. $groups[] = $group;
  2028. }
  2029. return $groups;
  2030. }
  2031. /**
  2032. * @param array $group_list
  2033. * @param int $category_id
  2034. *
  2035. * @return string
  2036. */
  2037. public static function process_groups($group_list, $category_id = 0)
  2038. {
  2039. global $charset;
  2040. $category_id = (int) $category_id;
  2041. $totalRegistered = 0;
  2042. $group_data = [];
  2043. $user_info = api_get_user_info();
  2044. $session_id = api_get_session_id();
  2045. $user_id = $user_info['user_id'];
  2046. $hideGroup = api_get_setting('hide_course_group_if_no_tools_available');
  2047. foreach ($group_list as $this_group) {
  2048. // Validation when belongs to a session
  2049. $session_img = api_get_session_image($this_group['session_id'], $user_info['status']);
  2050. // All the tutors of this group
  2051. $tutorsids_of_group = self::get_subscribed_tutors($this_group, true);
  2052. $isMember = self::is_subscribed($user_id, $this_group);
  2053. // Create a new table-row
  2054. $row = [];
  2055. // Checkbox
  2056. if (api_is_allowed_to_edit(false, true) && count($group_list) > 1) {
  2057. $row[] = $this_group['id'];
  2058. }
  2059. if (self::userHasAccessToBrowse($user_id, $this_group, $session_id)) {
  2060. // Group name
  2061. $groupNameClass = null;
  2062. if ($this_group['status'] == 0) {
  2063. $groupNameClass = 'muted';
  2064. }
  2065. $group_name = '<a class="'.$groupNameClass.'" href="group_space.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'">'.
  2066. Security::remove_XSS($this_group['name']).'</a> ';
  2067. $group_name2 = '';
  2068. if (api_get_configuration_value('extra')) {
  2069. $group_name2 = '<a href="group_space_tracking.php?cidReq='.api_get_course_id().'&gidReq='
  2070. .$this_group['id'].'">'.get_lang('suivi_de').''.stripslashes($this_group['name']).'</a>';
  2071. }
  2072. if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
  2073. $group_name .= Display::label(get_lang('OneMyGroups'), 'success');
  2074. } elseif ($isMember) {
  2075. $group_name .= Display::label(get_lang('MyGroup'), 'success');
  2076. }
  2077. if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
  2078. $group_name .= ' ('.$this_group['session_name'].')';
  2079. }
  2080. $group_name .= $session_img;
  2081. $row[] = $group_name.$group_name2.'<br />'.stripslashes(trim($this_group['description']));
  2082. } else {
  2083. if ($hideGroup === 'true') {
  2084. continue;
  2085. }
  2086. $row[] = $this_group['name'].'<br />'.stripslashes(trim($this_group['description']));
  2087. }
  2088. // Tutor name
  2089. $tutor_info = '';
  2090. if (count($tutorsids_of_group) > 0) {
  2091. foreach ($tutorsids_of_group as $tutor_id) {
  2092. $tutor = api_get_user_info($tutor_id);
  2093. $username = api_htmlentities(
  2094. sprintf(get_lang('LoginX'), $tutor['username']),
  2095. ENT_QUOTES
  2096. );
  2097. if (api_get_setting('show_email_addresses') === 'true') {
  2098. $tutor_info .= Display::tag(
  2099. 'span',
  2100. Display::encrypted_mailto_link(
  2101. $tutor['mail'],
  2102. $tutor['complete_name']
  2103. ),
  2104. ['title' => $username]
  2105. ).', ';
  2106. } else {
  2107. if (api_is_allowed_to_edit()) {
  2108. $tutor_info .= Display::tag(
  2109. 'span',
  2110. Display::encrypted_mailto_link(
  2111. $tutor['mail'],
  2112. $tutor['complete_name_with_username']
  2113. ),
  2114. ['title' => $username]
  2115. ).', ';
  2116. } else {
  2117. $tutor_info .= Display::tag(
  2118. 'span',
  2119. $tutor['complete_name'],
  2120. ['title' => $username]
  2121. ).', ';
  2122. }
  2123. }
  2124. }
  2125. }
  2126. $tutor_info = api_substr(
  2127. $tutor_info,
  2128. 0,
  2129. api_strlen($tutor_info) - 2
  2130. );
  2131. $row[] = $tutor_info;
  2132. // Max number of members in group
  2133. $max_members = $this_group['maximum_number_of_members'] == self::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / '.$this_group['maximum_number_of_members'];
  2134. // Number of members in group
  2135. $row[] = $this_group['number_of_members'].$max_members;
  2136. // Self-registration / unregistration
  2137. if (!api_is_allowed_to_edit(false, true)) {
  2138. if (self::is_self_registration_allowed($user_id, $this_group)) {
  2139. $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>';
  2140. } elseif (self::is_self_unregistration_allowed($user_id, $this_group)) {
  2141. $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>';
  2142. } else {
  2143. $row[] = '-';
  2144. }
  2145. }
  2146. $url = api_get_path(WEB_CODE_PATH).'group/';
  2147. // Edit-links
  2148. if (api_is_allowed_to_edit(false, true) &&
  2149. !(api_is_session_general_coach() && intval($this_group['session_id']) != $session_id)
  2150. ) {
  2151. $edit_actions = '<a href="'.$url.'settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('Edit').'">'.
  2152. Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2153. if ($this_group['status'] == 1) {
  2154. $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').'">'.
  2155. Display::return_icon('visible.png', get_lang('Hide'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2156. } else {
  2157. $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').'">'.
  2158. Display::return_icon('invisible.png', get_lang('Show'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2159. }
  2160. $edit_actions .= '<a href="'.$url.'member_settings.php?'.api_get_cidreq(true, false).'&gidReq='.$this_group['id'].'" title="'.get_lang('GroupMembers').'">'.
  2161. Display::return_icon('user.png', get_lang('GroupMembers'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2162. $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').'">'.
  2163. Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2164. $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').'">'.
  2165. Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2166. $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').'">'.
  2167. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
  2168. $row[] = $edit_actions;
  2169. }
  2170. if (!empty($this_group['nbMember'])) {
  2171. $totalRegistered = $totalRegistered + $this_group['nbMember'];
  2172. }
  2173. $group_data[] = $row;
  2174. } // end loop
  2175. // If no groups then don't show the table (only for students)
  2176. if (!api_is_allowed_to_edit(true, false)) {
  2177. if (empty($group_data)) {
  2178. return '';
  2179. }
  2180. }
  2181. $table = new SortableTableFromArrayConfig(
  2182. $group_data,
  2183. 1,
  2184. 20,
  2185. 'group_category_'.$category_id
  2186. );
  2187. $table->set_additional_parameters(['category' => $category_id]);
  2188. $column = 0;
  2189. if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) {
  2190. $table->set_header($column++, '', false);
  2191. }
  2192. $table->set_header($column++, get_lang('Groups'));
  2193. $table->set_header($column++, get_lang('GroupTutor'));
  2194. $table->set_header($column++, get_lang('Registered'), false);
  2195. if (!api_is_allowed_to_edit(false, true)) {
  2196. // If self-registration allowed
  2197. $table->set_header($column++, get_lang('GroupSelfRegistration'), false);
  2198. }
  2199. if (api_is_allowed_to_edit(false, true)) {
  2200. // Only for course administrator
  2201. $table->set_header($column++, get_lang('Modify'), false);
  2202. $form_actions = [];
  2203. $form_actions['fill_selected'] = get_lang('FillGroup');
  2204. $form_actions['empty_selected'] = get_lang('EmptyGroup');
  2205. $form_actions['delete_selected'] = get_lang('Delete');
  2206. if (count($group_list) > 1) {
  2207. $table->set_form_actions($form_actions, 'group');
  2208. }
  2209. }
  2210. return $table->return_table();
  2211. }
  2212. /**
  2213. * @param array $groupData
  2214. * @param bool $deleteNotInArray
  2215. *
  2216. * @return array
  2217. */
  2218. public static function importCategoriesAndGroupsFromArray(
  2219. $groupData,
  2220. $deleteNotInArray = false
  2221. ) {
  2222. $result = [];
  2223. $elementsFound = [
  2224. 'categories' => [],
  2225. 'groups' => [],
  2226. ];
  2227. $courseCode = api_get_course_id();
  2228. $sessionId = api_get_session_id();
  2229. $groupCategories = self::get_categories();
  2230. if (empty($groupCategories)) {
  2231. $result['error'][] = get_lang('CreateACategory');
  2232. return $result;
  2233. }
  2234. foreach ($groupData as $data) {
  2235. $isCategory = empty($data['group']) ? true : false;
  2236. if ($isCategory) {
  2237. $categoryInfo = self::getCategoryByTitle($data['category']);
  2238. $categoryId = $categoryInfo['id'];
  2239. if (!empty($categoryInfo)) {
  2240. // Update
  2241. self::update_category(
  2242. $categoryId,
  2243. $data['category'],
  2244. $data['description'],
  2245. $data['doc_state'],
  2246. $data['work_state'],
  2247. $data['calendar_state'],
  2248. $data['announcements_state'],
  2249. $data['forum_state'],
  2250. $data['wiki_state'],
  2251. $data['chat_state'],
  2252. $data['self_reg_allowed'],
  2253. $data['self_unreg_allowed'],
  2254. $data['max_student'],
  2255. $data['groups_per_user']
  2256. );
  2257. $data['category_id'] = $categoryId;
  2258. $result['updated']['category'][] = $data;
  2259. } else {
  2260. // Add
  2261. $categoryId = self::create_category(
  2262. $data['category'],
  2263. $data['description'],
  2264. $data['doc_state'],
  2265. $data['work_state'],
  2266. $data['calendar_state'],
  2267. $data['announcements_state'],
  2268. $data['forum_state'],
  2269. $data['wiki_state'],
  2270. $data['chat_state'],
  2271. $data['self_reg_allowed'],
  2272. $data['self_unreg_allowed'],
  2273. $data['max_student'],
  2274. $data['groups_per_user']
  2275. );
  2276. if ($categoryId) {
  2277. $data['category_id'] = $categoryId;
  2278. $result['added']['category'][] = $data;
  2279. }
  2280. }
  2281. $elementsFound['categories'][] = $categoryId;
  2282. } else {
  2283. $groupInfo = self::getGroupByName($data['group']);
  2284. $categoryInfo = [];
  2285. if (isset($data['category'])) {
  2286. $categoryInfo = self::getCategoryByTitle($data['category']);
  2287. }
  2288. $categoryId = null;
  2289. if (!empty($categoryInfo)) {
  2290. $categoryId = $categoryInfo['id'];
  2291. } else {
  2292. if (!empty($groupCategories) && isset($groupCategories[0])) {
  2293. $defaultGroupCategory = $groupCategories[0];
  2294. $categoryId = $defaultGroupCategory['id'];
  2295. }
  2296. }
  2297. if (empty($groupInfo)) {
  2298. // Add
  2299. $groupId = self::create_group(
  2300. $data['group'],
  2301. $categoryId,
  2302. null,
  2303. $data['max_student']
  2304. );
  2305. if ($groupId) {
  2306. self::set_group_properties(
  2307. $groupId,
  2308. $data['group'],
  2309. $data['description'],
  2310. $data['max_student'],
  2311. $data['doc_state'],
  2312. $data['work_state'],
  2313. $data['calendar_state'],
  2314. $data['announcements_state'],
  2315. $data['forum_state'],
  2316. $data['wiki_state'],
  2317. $data['chat_state'],
  2318. $data['self_reg_allowed'],
  2319. $data['self_unreg_allowed'],
  2320. $categoryId
  2321. );
  2322. $data['group_id'] = $groupId;
  2323. $result['added']['group'][] = $data;
  2324. }
  2325. $groupInfo = self::get_group_properties($groupId, true);
  2326. } else {
  2327. // Update
  2328. $groupId = $groupInfo['id'];
  2329. self::set_group_properties(
  2330. $groupId,
  2331. $data['group'],
  2332. $data['description'],
  2333. $data['max_student'],
  2334. $data['doc_state'],
  2335. $data['work_state'],
  2336. $data['calendar_state'],
  2337. $data['announcements_state'],
  2338. $data['forum_state'],
  2339. $data['wiki_state'],
  2340. $data['chat_state'],
  2341. $data['self_reg_allowed'],
  2342. $data['self_unreg_allowed'],
  2343. $categoryId
  2344. );
  2345. $data['group_id'] = $groupId;
  2346. $result['updated']['group'][] = $data;
  2347. $groupInfo = self::get_group_properties($groupId);
  2348. }
  2349. $students = isset($data['students']) ? explode(',', $data['students']) : [];
  2350. if (!empty($students)) {
  2351. $studentUserIdList = [];
  2352. foreach ($students as $student) {
  2353. $userInfo = api_get_user_info_from_username($student);
  2354. if (!$userInfo) {
  2355. continue;
  2356. }
  2357. if (!CourseManager::is_user_subscribed_in_course(
  2358. $userInfo['user_id'],
  2359. $courseCode,
  2360. !empty($sessionId),
  2361. $sessionId
  2362. )
  2363. ) {
  2364. Display::addFlash(
  2365. Display::return_message(
  2366. sprintf(
  2367. get_lang('StudentXIsNotSubscribedToCourse'),
  2368. $userInfo['complete_name']
  2369. ),
  2370. 'warning'
  2371. )
  2372. );
  2373. continue;
  2374. }
  2375. $studentUserIdList[] = $userInfo['user_id'];
  2376. }
  2377. self::subscribe_users($studentUserIdList, $groupInfo);
  2378. }
  2379. $tutors = isset($data['tutors']) ? explode(',', $data['tutors']) : [];
  2380. if (!empty($tutors)) {
  2381. $tutorIdList = [];
  2382. foreach ($tutors as $tutor) {
  2383. $userInfo = api_get_user_info_from_username($tutor);
  2384. if (!$userInfo) {
  2385. continue;
  2386. }
  2387. if (!CourseManager::is_user_subscribed_in_course(
  2388. $userInfo['user_id'],
  2389. $courseCode,
  2390. !empty($sessionId),
  2391. $sessionId
  2392. )
  2393. ) {
  2394. Display::addFlash(
  2395. Display::return_message(
  2396. sprintf(get_lang('TutorXIsNotSubscribedToCourse'), $userInfo['complete_name']),
  2397. 'warning'
  2398. )
  2399. );
  2400. continue;
  2401. }
  2402. $tutorIdList[] = $userInfo['user_id'];
  2403. }
  2404. self::subscribe_tutors($tutorIdList, $groupInfo);
  2405. }
  2406. $elementsFound['groups'][] = $groupId;
  2407. }
  2408. }
  2409. if ($deleteNotInArray) {
  2410. // Check categories
  2411. $categories = self::get_categories();
  2412. foreach ($categories as $category) {
  2413. if (!in_array($category['id'], $elementsFound['categories'])) {
  2414. self::delete_category($category['id']);
  2415. $category['category'] = $category['title'];
  2416. $result['deleted']['category'][] = $category;
  2417. }
  2418. }
  2419. $groups = self::get_groups();
  2420. foreach ($groups as $group) {
  2421. if (!in_array($group['iid'], $elementsFound['groups'])) {
  2422. self::deleteGroup($group);
  2423. $group['group'] = $group['name'];
  2424. $result['deleted']['group'][] = $group;
  2425. }
  2426. }
  2427. }
  2428. return $result;
  2429. }
  2430. /**
  2431. * Export all categories/group from a course to an array.
  2432. * This function works only in a context of a course.
  2433. *
  2434. * @param int $groupId
  2435. * @param bool $loadUsers
  2436. *
  2437. * @return array
  2438. */
  2439. public static function exportCategoriesAndGroupsToArray($groupId = null, $loadUsers = false)
  2440. {
  2441. $data = [];
  2442. $data[] = [
  2443. 'category',
  2444. 'group',
  2445. 'description',
  2446. 'announcements_state',
  2447. 'calendar_state',
  2448. 'chat_state',
  2449. 'doc_state',
  2450. 'forum_state',
  2451. 'work_state',
  2452. 'wiki_state',
  2453. 'max_student',
  2454. 'self_reg_allowed',
  2455. 'self_unreg_allowed',
  2456. 'groups_per_user',
  2457. ];
  2458. $count = 1;
  2459. if ($loadUsers) {
  2460. $data[0][] = 'students';
  2461. $data[0][] = 'tutors';
  2462. }
  2463. if ($loadUsers == false) {
  2464. $categories = self::get_categories();
  2465. foreach ($categories as $categoryInfo) {
  2466. $data[$count] = [
  2467. $categoryInfo['title'],
  2468. null,
  2469. $categoryInfo['description'],
  2470. $categoryInfo['announcements_state'],
  2471. $categoryInfo['calendar_state'],
  2472. $categoryInfo['chat_state'],
  2473. $categoryInfo['doc_state'],
  2474. $categoryInfo['forum_state'],
  2475. $categoryInfo['work_state'],
  2476. $categoryInfo['wiki_state'],
  2477. $categoryInfo['max_student'],
  2478. $categoryInfo['self_reg_allowed'],
  2479. $categoryInfo['self_unreg_allowed'],
  2480. $categoryInfo['groups_per_user'],
  2481. ];
  2482. $count++;
  2483. }
  2484. }
  2485. $groups = self::get_group_list();
  2486. foreach ($groups as $groupInfo) {
  2487. $categoryTitle = null;
  2488. $categoryInfo = self::get_category($groupInfo['category_id']);
  2489. $groupSettings = self::get_group_properties($groupInfo['id']);
  2490. if (!empty($categoryInfo)) {
  2491. $categoryTitle = $categoryInfo['title'];
  2492. }
  2493. $users = self::getStudents($groupInfo['iid']);
  2494. $userList = [];
  2495. foreach ($users as $user) {
  2496. $user = api_get_user_info($user['user_id']);
  2497. $userList[] = $user['username'];
  2498. }
  2499. $tutors = self::getTutors($groupInfo);
  2500. $tutorList = [];
  2501. foreach ($tutors as $user) {
  2502. $user = api_get_user_info($user['user_id']);
  2503. $tutorList[] = $user['username'];
  2504. }
  2505. $userListToString = null;
  2506. if (!empty($userList)) {
  2507. $userListToString = implode(',', $userList);
  2508. }
  2509. $tutorListToString = null;
  2510. if (!empty($tutorList)) {
  2511. $tutorListToString = implode(',', $tutorList);
  2512. }
  2513. $data[$count] = [
  2514. $categoryTitle,
  2515. $groupSettings['name'],
  2516. $groupSettings['description'],
  2517. $groupSettings['announcements_state'],
  2518. $groupSettings['calendar_state'],
  2519. $groupSettings['chat_state'],
  2520. $groupSettings['doc_state'],
  2521. $groupSettings['forum_state'],
  2522. $groupSettings['work_state'],
  2523. $groupSettings['wiki_state'],
  2524. $groupSettings['maximum_number_of_students'],
  2525. $groupSettings['self_registration_allowed'],
  2526. $groupSettings['self_unregistration_allowed'],
  2527. null,
  2528. ];
  2529. if ($loadUsers) {
  2530. $data[$count][] = $userListToString;
  2531. $data[$count][] = $tutorListToString;
  2532. }
  2533. if (!empty($groupId)) {
  2534. if ($groupId == $groupInfo['id']) {
  2535. break;
  2536. }
  2537. }
  2538. $count++;
  2539. }
  2540. return $data;
  2541. }
  2542. /**
  2543. * @param string $default
  2544. */
  2545. public static function getSettingBar($default)
  2546. {
  2547. $activeSettings = null;
  2548. $activeTutor = null;
  2549. $activeMember = null;
  2550. switch ($default) {
  2551. case 'settings':
  2552. $activeSettings = 'active';
  2553. break;
  2554. case'tutor':
  2555. $activeTutor = 'active';
  2556. break;
  2557. case 'member':
  2558. $activeMember = 'active';
  2559. break;
  2560. }
  2561. $url = api_get_path(WEB_CODE_PATH).'group/%s?'.api_get_cidreq();
  2562. echo '
  2563. <ul class="toolbar-groups nav nav-tabs">
  2564. <li class="'.$activeSettings.'">
  2565. <a id="group_settings_tab" href="'.sprintf($url, 'settings.php').'">
  2566. '.Display::return_icon('settings.png').' '.get_lang('Settings').'
  2567. </a>
  2568. </li>
  2569. <li class="'.$activeMember.'">
  2570. <a id="group_members_tab" href="'.sprintf($url, 'member_settings.php').'">
  2571. '.Display::return_icon('user.png').' '.get_lang('GroupMembers').'</a>
  2572. </li>
  2573. <li class="'.$activeTutor.'">
  2574. <a id="group_tutors_tab" href="'.sprintf($url, 'tutor_settings.php').'">
  2575. '.Display::return_icon('teacher.png').' '.get_lang('GroupTutors').'
  2576. </a>
  2577. </li>
  2578. </ul>';
  2579. }
  2580. /**
  2581. * @param int $courseId
  2582. * @param string $keyword
  2583. *
  2584. * @return string
  2585. */
  2586. public static function getOverview($courseId, $keyword = null)
  2587. {
  2588. $content = null;
  2589. $categories = self::get_categories();
  2590. if (!empty($categories)) {
  2591. foreach ($categories as $category) {
  2592. if (api_get_setting('allow_group_categories') == 'true') {
  2593. $content .= '<h2>'.$category['title'].'</h2>';
  2594. }
  2595. if (!empty($keyword)) {
  2596. $groups = self::getGroupListFilterByName(
  2597. $keyword,
  2598. $category['id'],
  2599. $courseId
  2600. );
  2601. } else {
  2602. $groups = self::get_group_list($category['id']);
  2603. }
  2604. if (empty($groups)) {
  2605. $groups = self::get_group_list();
  2606. }
  2607. $content .= '<ul>';
  2608. if (!empty($groups)) {
  2609. foreach ($groups as $group) {
  2610. $content .= '<li>';
  2611. $content .= Display::tag(
  2612. 'h3',
  2613. Security::remove_XSS($group['name'])
  2614. );
  2615. $users = self::getTutors($group);
  2616. if (!empty($users)) {
  2617. $content .= '<ul>';
  2618. $content .= "<li>".Display::tag('h4', get_lang('Tutors'))."</li><ul>";
  2619. foreach ($users as $user) {
  2620. $user_info = api_get_user_info($user['user_id']);
  2621. $content .= '<li title="'.$user_info['username'].'">'.
  2622. $user_info['complete_name_with_username'].
  2623. '</li>';
  2624. }
  2625. $content .= '</ul>';
  2626. $content .= '</ul>';
  2627. }
  2628. $users = self::getStudents($group['id']);
  2629. if (!empty($users)) {
  2630. $content .= '<ul>';
  2631. $content .= "<li>".Display::tag('h4', get_lang('Students'))."</li><ul>";
  2632. foreach ($users as $user) {
  2633. $user_info = api_get_user_info($user['user_id']);
  2634. $content .= '<li title="'.$user_info['username'].'">'.
  2635. $user_info['complete_name_with_username'].
  2636. '</li>';
  2637. }
  2638. $content .= '</ul>';
  2639. $content .= '</ul>';
  2640. }
  2641. $content .= '</li>';
  2642. }
  2643. }
  2644. $content .= '</ul>';
  2645. }
  2646. }
  2647. return $content;
  2648. }
  2649. /**
  2650. * Returns the search form.
  2651. *
  2652. * @return string
  2653. */
  2654. public static function getSearchForm()
  2655. {
  2656. $url = api_get_path(WEB_CODE_PATH).'group/group_overview.php?'.api_get_cidreq();
  2657. $form = new FormValidator(
  2658. 'search_groups',
  2659. 'get',
  2660. $url,
  2661. null,
  2662. ['class' => 'form-search'],
  2663. FormValidator::LAYOUT_INLINE
  2664. );
  2665. $form->addElement('text', 'keyword');
  2666. $form->addButtonSearch();
  2667. return $form->toHtml();
  2668. }
  2669. /**
  2670. * @param int $groupId
  2671. * @param int $status
  2672. */
  2673. public static function setStatus($groupId, $status)
  2674. {
  2675. $groupInfo = self::get_group_properties($groupId);
  2676. $courseId = api_get_course_int_id();
  2677. if (!empty($groupInfo)) {
  2678. $table = Database::get_course_table(TABLE_GROUP);
  2679. $params = [
  2680. 'status' => intval($status),
  2681. ];
  2682. Database::update(
  2683. $table,
  2684. $params,
  2685. ['c_id = ? AND id = ?' => [$courseId, $groupId]]
  2686. );
  2687. }
  2688. }
  2689. /**
  2690. * @param int $groupId
  2691. */
  2692. public static function setVisible($groupId)
  2693. {
  2694. self::setStatus($groupId, 1);
  2695. }
  2696. /**
  2697. * @param int $groupId
  2698. */
  2699. public static function setInvisible($groupId)
  2700. {
  2701. self::setStatus($groupId, 0);
  2702. }
  2703. /**
  2704. * @param int $userId
  2705. * @param int $courseId
  2706. * @param array $groupInfo
  2707. * @param array $documentInfoToBeCheck
  2708. * @param bool $blockPage
  2709. *
  2710. * @return bool
  2711. */
  2712. public static function allowUploadEditDocument(
  2713. $userId,
  2714. $courseId,
  2715. $groupInfo,
  2716. $documentInfoToBeCheck = null,
  2717. $blockPage = false
  2718. ) {
  2719. // Admin and teachers can make any change no matter what
  2720. if (api_is_platform_admin() || api_is_allowed_to_edit(false, true)) {
  2721. return true;
  2722. }
  2723. if (empty($groupInfo) || !isset($groupInfo['id'])) {
  2724. if ($blockPage) {
  2725. api_not_allowed(true);
  2726. }
  2727. return false;
  2728. }
  2729. // Tutor can also make any change
  2730. $isTutor = self::is_tutor_of_group($userId, $groupInfo, $courseId);
  2731. if ($isTutor) {
  2732. return true;
  2733. }
  2734. // Just in case also check if document in group is available
  2735. if ($groupInfo['doc_state'] == 0) {
  2736. if ($blockPage) {
  2737. api_not_allowed(true);
  2738. }
  2739. return false;
  2740. }
  2741. // Default behaviour
  2742. $documentAccess = self::DOCUMENT_MODE_SHARE;
  2743. // Check category document access
  2744. /*$allowCategoryGroupDocumentAccess = api_get_configuration_value('group_category_document_access');
  2745. if ($allowCategoryGroupDocumentAccess) {
  2746. $category = GroupManager::get_category_from_group($groupInfo['iid']);
  2747. if (!empty($category) && isset($category['document_access'])) {
  2748. $documentAccess = (int) $category['document_access'];
  2749. }
  2750. }*/
  2751. // Check group document access
  2752. $allow = api_get_configuration_value('group_document_access');
  2753. if ($allow) {
  2754. if (isset($groupInfo['document_access'])) {
  2755. $documentAccess = (int) $groupInfo['document_access'];
  2756. }
  2757. }
  2758. // Check access for students
  2759. $result = false;
  2760. switch ($documentAccess) {
  2761. case self::DOCUMENT_MODE_SHARE:
  2762. // Default chamilo behaviour
  2763. // Student can upload his own content, cannot modify another content.
  2764. $isMember = self::is_subscribed($userId, $groupInfo);
  2765. if ($isMember) {
  2766. // No document to check, allow access to document feature.
  2767. if (empty($documentInfoToBeCheck)) {
  2768. $result = true;
  2769. } else {
  2770. // Member can only edit his own document
  2771. $authorId = isset($documentInfoToBeCheck['insert_user_id']) ? $documentInfoToBeCheck['insert_user_id'] : 0;
  2772. // If "insert_user_id" is not set, check the author id from c_item_property
  2773. if (empty($authorId) && isset($documentInfoToBeCheck['id'])) {
  2774. $documentInfo = api_get_item_property_info(
  2775. $courseId,
  2776. 'document',
  2777. $documentInfoToBeCheck['id'],
  2778. 0
  2779. );
  2780. // Try to find this document in the session
  2781. if (!empty($sessionId)) {
  2782. $documentInfo = api_get_item_property_info(
  2783. $courseId,
  2784. 'document',
  2785. $documentInfoToBeCheck['id'],
  2786. api_get_session_id()
  2787. );
  2788. }
  2789. if (!empty($documentInfo) && isset($documentInfo['insert_user_id'])) {
  2790. $authorId = $documentInfo['insert_user_id'];
  2791. }
  2792. }
  2793. if ($authorId == $userId) {
  2794. $result = true;
  2795. }
  2796. }
  2797. }
  2798. break;
  2799. case self::DOCUMENT_MODE_READ_ONLY:
  2800. // Student cannot upload content, cannot modify another content.
  2801. $result = false;
  2802. break;
  2803. case self::DOCUMENT_MODE_COLLABORATION:
  2804. // Student can upload content, can modify another content.
  2805. $isMember = self::is_subscribed($userId, $groupInfo);
  2806. if ($isMember) {
  2807. $result = true;
  2808. }
  2809. break;
  2810. }
  2811. if ($blockPage && $result == false) {
  2812. api_not_allowed(true);
  2813. }
  2814. return $result;
  2815. }
  2816. }