groupmanager.lib.php 109 KB

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