groupmanager.lib.php 110 KB

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