sessionmanager.lib.php 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class SessionManager
  5. *
  6. * This is the session library for Chamilo.
  7. * All main sessions functions should be placed here.
  8. * This class provides methods for sessions management.
  9. * Include/require it in your code to use its features.
  10. *
  11. * @package chamilo.library
  12. *
  13. */
  14. class SessionManager
  15. {
  16. //See BT#4871
  17. CONST SESSION_CHANGE_USER_REASON_SCHEDULE = 1;
  18. CONST SESSION_CHANGE_USER_REASON_CLASSROOM = 2;
  19. CONST SESSION_CHANGE_USER_REASON_LOCATION = 3;
  20. CONST SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION = 4;
  21. CONST DEFAULT_VISIBILITY = 4; //SESSION_AVAILABLE
  22. /**
  23. * Fetches a session from the database
  24. * @param int Session ID
  25. * @return array Session details
  26. * @assert (-1) === array()
  27. */
  28. public static function fetch($id) {
  29. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  30. if ($id != strval(intval($id))) { return array(); }
  31. $s = "SELECT * FROM $t WHERE id = $id";
  32. $r = Database::query($s);
  33. if (Database::num_rows($r) != 1) { return array(); }
  34. return Database::fetch_array($r,'ASSOC');
  35. }
  36. /**
  37. * Creates a session
  38. * @param array Fields to use in the creation of the session
  39. * @param boolean Whether to allow for same-name sessions or not.
  40. * @assert (array()) === false
  41. */
  42. public static function add($params, $allow_homonyms=false) {
  43. global $_configuration;
  44. //just in case
  45. if (isset($params['id'])) {
  46. unset($params['id']);
  47. }
  48. //Check portal limits
  49. $access_url_id = 1;
  50. if (api_is_multiple_url_enabled()) {
  51. $access_url_id = api_get_current_access_url_id();
  52. }
  53. if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_sessions']) && $_configuration[$access_url_id]['hosting_limit_sessions'] > 0) {
  54. $num = self::count_sessions();
  55. if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
  56. return get_lang('PortalSessionsLimitReached');
  57. }
  58. }
  59. if (!$allow_homonyms) {
  60. $my_session_result = SessionManager::get_session_by_name($params['name']);
  61. $session_id = null;
  62. if ($my_session_result == false) {
  63. $session_model = new SessionModel();
  64. $session_id = $session_model->save($params);
  65. } else {
  66. error_log('Session already exists with name: '.$params['name']." session_id: ".$my_session_result['id']);
  67. }
  68. } else {
  69. //with the allow_homonyms option, two sessions can share names
  70. $session_model = new SessionModel();
  71. $session_id = $session_model->save($params);
  72. }
  73. if (!empty($session_id)) {
  74. /*
  75. Sends a message to the user_id = 1
  76. $user_info = api_get_user_info(1);
  77. $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
  78. $subject = api_get_setting('platform.site_name').' - '.get_lang('ANewSessionWasCreated');
  79. $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
  80. api_mail_html($complete_name, $user_info['email'], $subject, $message);
  81. *
  82. */
  83. //Saving extra fields
  84. $session_field_value = new SessionFieldValue();
  85. $params['session_id'] = $session_id;
  86. $session_field_value->save_field_values($params);
  87. //Adding to the correct URL
  88. $access_url_id = api_get_current_access_url_id();
  89. UrlManager::add_session_to_url($session_id, $access_url_id);
  90. // Add event to system log
  91. Event::addEvent(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), api_get_user_id());
  92. if (isset($params['course_code'])) {
  93. $courseInfo = api_get_course_info($params['course_code']);
  94. self::add_courses_to_session($session_id, array($courseInfo['real_id']));
  95. //Update default course gradebook to the session if exists
  96. $create_gradebook_evaluation = isset($params['create_gradebook_evaluation']) ? $params['create_gradebook_evaluation'] : false;
  97. if ($create_gradebook_evaluation) {
  98. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  99. $category_id = create_default_course_gradebook($params['course_code'], false, $session_id);
  100. /*
  101. if ($category_id && isset($params['gradebook_params'])) {
  102. $eval = new Evaluation();
  103. $eval->set_name($params['gradebook_params']['name']);
  104. $eval->set_user_id($params['gradebook_params']['user_id']);
  105. $eval->set_course_code($params['course_code']);
  106. $eval->set_category_id($category_id);
  107. $eval->set_weight($params['gradebook_params']['weight']);
  108. $eval->set_max($params['gradebook_params']['max']);
  109. $eval->set_visible(0);
  110. $eval->add();
  111. }*/
  112. /*$tbl_gradebook_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
  113. $sql = "SELECT id FROM $tbl_gradebook_category WHERE course_code = {$params['course_code']} AND session_id = 0 LIMIT 1";
  114. $result = Database::query($sql);
  115. if (Database::num_rows($result)) {
  116. $gradebook_data = Database::fetch_array($result, 'ASSOC');
  117. if (!empty($gradebook_data)) {
  118. $sql = "UPDATE SET session_id = $session_id WHERE id = {$gradebook_data['id']}";
  119. Database::query($sql);
  120. }
  121. }*/
  122. }
  123. }
  124. } else {
  125. if (isset($params['return_item_if_already_exists']) && $params['return_item_if_already_exists']) {
  126. $my_session_result = SessionManager::get_session_by_name($params['name']);
  127. $session_id = $my_session_result['id'];
  128. }
  129. }
  130. return $session_id;
  131. }
  132. /**
  133. * Updates a session with the given array of field values
  134. * @param array An array of fields values
  135. * @return void
  136. * @assert (null) === false
  137. */
  138. public static function update($params) {
  139. if (empty($params) || count($params)<1) {
  140. return false;
  141. }
  142. $session_model = new SessionModel();
  143. $session_model->update($params);
  144. if (!empty($params['id'])) {
  145. $session_field_value = new SessionFieldValue();
  146. $params['session_id'] = $params['id'];
  147. unset($params['id']);
  148. $session_field_value->save_field_values($params);
  149. }
  150. }
  151. /**
  152. * Checks whether a session already exists with the given name (used in
  153. * add() to avoid homonym sessions)
  154. * @param string A session name
  155. * @assert ('') === false
  156. */
  157. function session_name_exists($session_name) {
  158. $session_name = Database::escape_string($session_name);
  159. $result = Database::fetch_array(Database::query("SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." WHERE name = '$session_name' "));
  160. return $result['count'] > 0;
  161. }
  162. /**
  163. * Gets the admin session list callback of the session/session_list.php page
  164. * @param array order and limit keys
  165. * @param boolean Whether to get all the results or only the count
  166. * @return mixed Integer for number of rows, or array of results
  167. * @assert (array(),true) !== false
  168. */
  169. public static function get_sessions_admin($options = array(), $get_count = false)
  170. {
  171. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  172. $where = 'WHERE 1 = 1 ';
  173. $user_id = api_get_user_id();
  174. if (!api_is_platform_admin()) {
  175. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
  176. $where .=" AND s.session_admin_id = $user_id ";
  177. }
  178. }
  179. if (!api_is_platform_admin() && api_is_teacher() && api_get_setting('allow_teachers_to_create_sessions') == 'true') {
  180. $where .=" AND s.id_coach = $user_id ";
  181. }
  182. $extra_field = new ExtraField('session');
  183. $conditions = $extra_field->parseConditions($options);
  184. $inject_joins = $conditions['inject_joins'];
  185. $where .= $conditions['where'];
  186. $inject_where = $conditions['inject_where'];
  187. $inject_extra_fields = $conditions['inject_extra_fields'];
  188. $order = $conditions['order'];
  189. $limit = $conditions['limit'];
  190. if ($get_count == true) {
  191. $select = " SELECT count(*) as total_rows";
  192. } else {
  193. $select =
  194. "SELECT DISTINCT ".
  195. " s.name, ".
  196. " s.display_start_date, ".
  197. " s.display_end_date, ".
  198. " access_start_date, ".
  199. " access_end_date, ".
  200. " s.visibility, ".
  201. " $inject_extra_fields ".
  202. " s.id ";
  203. }
  204. $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
  205. if (api_is_multiple_url_enabled()) {
  206. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  207. $access_url_id = api_get_current_access_url_id();
  208. if ($access_url_id != -1) {
  209. $where.= " AND ar.access_url_id = $access_url_id ";
  210. $query = "$select FROM $tbl_session s $inject_joins INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id) $where";
  211. }
  212. }
  213. $query .= $order;
  214. $query .= $limit;
  215. $result = Database::query($query);
  216. $formatted_sessions = array();
  217. if (Database::num_rows($result)) {
  218. $sessions = Database::store_result($result, 'ASSOC');
  219. if ($get_count) {
  220. return $sessions[0]['total_rows'];
  221. }
  222. foreach ($sessions as $session) {
  223. $session_id = $session['id'];
  224. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  225. if (isset($session['session_active']) && $session['session_active'] == 1) {
  226. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  227. } else {
  228. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  229. }
  230. $session = self::convert_dates_to_local($session);
  231. switch ($session['visibility']) {
  232. case SESSION_VISIBLE_READ_ONLY: //1
  233. $session['visibility'] = get_lang('ReadOnly');
  234. break;
  235. case SESSION_VISIBLE: //2
  236. case SESSION_AVAILABLE: //4
  237. $session['visibility'] = get_lang('Visible');
  238. break;
  239. case SESSION_INVISIBLE: //3
  240. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  241. break;
  242. }
  243. // Cleaning double selects.
  244. foreach ($session as $key => &$value) {
  245. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  246. $options = explode('::', $value);
  247. }
  248. $original_key = $key;
  249. if (strpos($key, '_second') === false) {
  250. } else {
  251. $key = str_replace('_second', '', $key);
  252. }
  253. if (isset($options_by_double[$key])) {
  254. if (isset($options[0])) {
  255. if (isset($options_by_double[$key][$options[0]])) {
  256. if (strpos($original_key, '_second') === false) {
  257. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  258. } else {
  259. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  260. }
  261. }
  262. }
  263. }
  264. }
  265. $formatted_sessions[$session_id] = $session;
  266. }
  267. }
  268. return $formatted_sessions;
  269. }
  270. /**
  271. * Gets the admin session list callback of the session/session_list.php
  272. * page with all user/details in the right fomat
  273. * @param array
  274. * @result array Array of rows results
  275. * @asset ('a') === false
  276. */
  277. public static function get_sessions_admin_complete($options = array())
  278. {
  279. if (!is_array($options)) {
  280. return false;
  281. }
  282. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  283. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  284. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  285. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  286. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  287. $tbl_session_field_values = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  288. $tbl_session_field_options = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_OPTIONS);
  289. $where = 'WHERE 1 = 1 ';
  290. $user_id = api_get_user_id();
  291. if (!api_is_platform_admin()) {
  292. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
  293. $where.=" AND s.session_admin_id = $user_id ";
  294. }
  295. }
  296. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  297. if (api_is_western_name_order()) {
  298. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  299. }
  300. $today = api_get_utc_datetime();
  301. $inject_extra_fields = null;
  302. $extra_fields = array();
  303. $extra_fields_info = array();
  304. //for now only sessions
  305. $extra_field = new ExtraField('session');
  306. $double_fields = array();
  307. $extra_field_option = new ExtraFieldOption('session');
  308. if (isset($options['extra'])) {
  309. $extra_fields = $options['extra'];
  310. if (!empty($extra_fields)) {
  311. foreach ($extra_fields as $extra) {
  312. $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
  313. if (isset($extra_fields_info[$extra['id']])) {
  314. $info = $extra_fields_info[$extra['id']];
  315. } else {
  316. $info = $extra_field->get($extra['id']);
  317. $extra_fields_info[$extra['id']] = $info;
  318. }
  319. if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  320. $double_fields[$info['id']] = $info;
  321. }
  322. }
  323. }
  324. }
  325. $options_by_double = array();
  326. foreach ($double_fields as $double) {
  327. $my_options = $extra_field_option->get_field_options_by_field($double['id'], true);
  328. $options_by_double['extra_'.$double['field_variable']] = $my_options;
  329. }
  330. //sc.name as category_name,
  331. $select = "
  332. SELECT * FROM (
  333. SELECT DISTINCT
  334. IF (
  335. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  336. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  337. (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
  338. (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
  339. ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
  340. , 1, 0) as session_active,
  341. s.name,
  342. s.nbr_courses,
  343. s.nbr_users,
  344. s.display_start_date,
  345. s.display_end_date,
  346. $coach_name,
  347. access_start_date,
  348. access_end_date,
  349. s.visibility,
  350. u.user_id,
  351. $inject_extra_fields
  352. c.title as course_title,
  353. s.id ";
  354. if (!empty($options['where'])) {
  355. if (!empty($options['extra'])) {
  356. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  357. $options['where'] = str_replace('AND', 'OR', $options['where']);
  358. foreach ($options['extra'] as $extra) {
  359. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  360. }
  361. }
  362. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  363. $where .= ' AND '.$options['where'];
  364. }
  365. if (!empty($options['limit'])) {
  366. $where .= " LIMIT ".$options['limit'];
  367. }
  368. $query = "$select FROM $tbl_session s
  369. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  370. LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
  371. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  372. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  373. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  374. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id) ".
  375. $where;
  376. if (api_is_multiple_url_enabled()) {
  377. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  378. $access_url_id = api_get_current_access_url_id();
  379. if ($access_url_id != -1) {
  380. $where.= " AND ar.access_url_id = $access_url_id ";
  381. $query = "$select
  382. FROM $tbl_session s
  383. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  384. LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
  385. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  386. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  387. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  388. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
  389. INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
  390. $where";
  391. }
  392. }
  393. $query .= ") AS session_table";
  394. if (!empty($options['order'])) {
  395. $query .= " ORDER BY ".$options['order'];
  396. }
  397. //error_log($query);
  398. //echo $query;
  399. $result = Database::query($query);
  400. $formatted_sessions = array();
  401. if (Database::num_rows($result)) {
  402. $sessions = Database::store_result($result, 'ASSOC');
  403. foreach ($sessions as $session) {
  404. $session_id = $session['id'];
  405. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  406. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
  407. if ($session['session_active'] == 1) {
  408. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  409. } else {
  410. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  411. }
  412. $session = self::convert_dates_to_local($session);
  413. switch ($session['visibility']) {
  414. case SESSION_VISIBLE_READ_ONLY: //1
  415. $session['visibility'] = get_lang('ReadOnly');
  416. break;
  417. case SESSION_VISIBLE: //2
  418. case SESSION_AVAILABLE: //4
  419. $session['visibility'] = get_lang('Visible');
  420. break;
  421. case SESSION_INVISIBLE: //3
  422. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  423. break;
  424. }
  425. //Cleaning double selects
  426. foreach ($session as $key => &$value) {
  427. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  428. $options = explode('::', $value);
  429. }
  430. $original_key = $key;
  431. if (strpos($key, '_second') === false) {
  432. } else {
  433. $key = str_replace('_second', '', $key);
  434. }
  435. if (isset($options_by_double[$key])) {
  436. if (isset($options[0])) {
  437. if (isset($options_by_double[$key][$options[0]])) {
  438. if (strpos($original_key, '_second') === false) {
  439. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  440. } else {
  441. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  442. }
  443. }
  444. }
  445. }
  446. }
  447. //Magic filter
  448. if (isset($formatted_sessions[$session_id])) {
  449. $formatted_sessions[$session_id] = self::compare_arrays_to_merge($formatted_sessions[$session_id], $session);
  450. } else {
  451. $formatted_sessions[$session_id] = $session;
  452. }
  453. }
  454. }
  455. return $formatted_sessions;
  456. }
  457. /**
  458. * Gets the number of rows in the session table filtered through the given
  459. * array of parameters
  460. * @param array Array of options/filters/keys
  461. * @return integer The number of rows, or false on wrong param
  462. * @assert ('a') === false
  463. */
  464. static function get_count_admin_complete($options = array())
  465. {
  466. if (!is_array($options)) {
  467. return false;
  468. }
  469. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  470. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  471. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  472. $where = 'WHERE 1 = 1 ';
  473. $user_id = api_get_user_id();
  474. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_see_all_sessions') == 'false') {
  475. $where.=" WHERE s.session_admin_id = $user_id ";
  476. }
  477. if (!empty($options['where'])) {
  478. if (!empty($options['extra'])) {
  479. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  480. $options['where'] = str_replace('AND', 'OR', $options['where']);
  481. foreach ($options['extra'] as $extra) {
  482. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  483. }
  484. }
  485. $where .= ' AND '.$options['where'];
  486. }
  487. $query_rows = "SELECT count(*) as total_rows
  488. FROM $tbl_session s
  489. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  490. INNER JOIN $tbl_user u ON s.id_coach = u.user_id $where ";
  491. if (api_is_multiple_url_enabled()) {
  492. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  493. $access_url_id = api_get_current_access_url_id();
  494. if ($access_url_id != -1) {
  495. $where.= " AND ar.access_url_id = $access_url_id ";
  496. $query_rows = "SELECT count(*) as total_rows
  497. FROM $tbl_session s
  498. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  499. INNER JOIN $tbl_user u ON s.id_coach = u.user_id
  500. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id $where ";
  501. }
  502. }
  503. $result = Database::query($query_rows);
  504. $num = 0;
  505. if (Database::num_rows($result)) {
  506. $rows = Database::fetch_array($result);
  507. $num = $rows['total_rows'];
  508. }
  509. return $num;
  510. }
  511. /**
  512. *
  513. */
  514. static function compare_arrays_to_merge($array1, $array2)
  515. {
  516. if (empty($array2)) {
  517. return $array1;
  518. }
  519. foreach ($array1 as $key => $item) {
  520. if (!isset($array1[$key])) {
  521. //My string is empty try the other one
  522. if (isset($array2[$key]) && !empty($array2[$key])) {
  523. $array1[$key] = $array2[$key];
  524. }
  525. }
  526. }
  527. return $array1;
  528. }
  529. /**
  530. * Converts all dates sent through the param array (given form) to correct
  531. * dates with timezones
  532. * @param array The dates
  533. * @return array The same array, with times converted
  534. * @assert ('a') === false
  535. */
  536. static function convert_dates_to_local($params) {
  537. if (!is_array($params)) {
  538. return false;
  539. }
  540. $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
  541. $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
  542. $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
  543. $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
  544. $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
  545. $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
  546. return $params;
  547. }
  548. /**
  549. * Creates a new course code based in given code
  550. *
  551. * @param string wanted code
  552. * <code>
  553. * $wanted_code = 'sess' if there are names like sess, sess1, sess2 in the
  554. * database already, the function will return: sess3
  555. * if the session name doesn't exist in the DB the same name is returned
  556. * </code>
  557. * @return string wanted unused code
  558. */
  559. function generate_nice_next_session_name($session_name) {
  560. $session_name_ok = !self::session_name_exists($session_name);
  561. if (!$session_name_ok) {
  562. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  563. $session_name = Database::escape_string($session_name);
  564. $sql = "SELECT count(*) as count FROM $table WHERE name LIKE '$session_name%'";
  565. $result = Database::query($sql);
  566. if (Database::num_rows($result) > 0 ) {
  567. $row = Database::fetch_array($result);
  568. $count = $row['count'] + 1;
  569. $session_name = $session_name.'_'.$count;
  570. $result = self::session_name_exists($session_name);
  571. if (!$result) {
  572. return $session_name;
  573. }
  574. }
  575. return false;
  576. }
  577. return $session_name;
  578. }
  579. /**
  580. * Delete session
  581. * @author Carlos Vargas from existing code
  582. * @param array id_checked
  583. * @param boolean optional, true if the function is called by a webservice, false otherwise.
  584. * @return void Nothing, or false on error
  585. * The parameters is a array to delete sessions
  586. **/
  587. public static function delete_session ($id_checked, $from_ws = false) {
  588. $tbl_session= Database::get_main_table(TABLE_MAIN_SESSION);
  589. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  590. $tbl_session_rel_course_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  591. $tbl_session_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_USER);
  592. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  593. global $_user;
  594. if(is_array($id_checked)) {
  595. $id_checked = Database::escape_string(implode(',',$id_checked));
  596. } else {
  597. $id_checked = intval($id_checked);
  598. }
  599. if (!api_is_platform_admin() && !$from_ws) {
  600. $sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
  601. $rs = Database::query($sql);
  602. if (Database::result($rs,0,0)!=$_user['user_id']) {
  603. api_not_allowed(true);
  604. }
  605. }
  606. Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
  607. Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
  608. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
  609. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
  610. Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
  611. // delete extra session fields
  612. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  613. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  614. // Delete extra fields from session where field variable is "SECCION"
  615. $sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'SECCION' ";
  616. $rs_field = Database::query($sql);
  617. $field_id = 0;
  618. if (Database::num_rows($rs_field) == 1) {
  619. $row_field = Database::fetch_row($rs_field);
  620. $field_id = $row_field[0];
  621. $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
  622. $rs_delete_sfv = Database::query($sql_delete_sfv);
  623. }
  624. $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
  625. $rs_field_id = Database::query($sql);
  626. if (Database::num_rows($rs_field_id) == 0) {
  627. $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
  628. $rs_delete_sf = Database::query($sql_delete_sf);
  629. }
  630. /*
  631. $sql = "SELECT distinct field_id FROM $t_sfv WHERE session_id = '$id_checked'";
  632. $res_field_ids = @Database::query($sql);
  633. if (Database::num_rows($res_field_ids) > 0) {
  634. while($row_field_id = Database::fetch_row($res_field_ids)){
  635. $field_ids[] = $row_field_id[0];
  636. }
  637. }
  638. //delete from table_session_field_value from a given session id
  639. $sql_session_field_value = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
  640. @Database::query($sql_session_field_value);
  641. $sql = "SELECT distinct field_id FROM $t_sfv";
  642. $res_field_all_ids = @Database::query($sql);
  643. if (Database::num_rows($res_field_all_ids) > 0) {
  644. while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
  645. $field_all_ids[] = $row_field_all_id[0];
  646. }
  647. }
  648. if (count($field_ids) > 0 && count($field_all_ids) > 0) {
  649. foreach($field_ids as $field_id) {
  650. // check if field id is used into table field value
  651. if (in_array($field_id,$field_all_ids)) {
  652. continue;
  653. } else {
  654. $sql_session_field = "DELETE FROM $t_sf WHERE id = '$field_id'";
  655. Database::query($sql_session_field);
  656. }
  657. }
  658. }
  659. */
  660. // Add event to system log
  661. $user_id = api_get_user_id();
  662. Event::addEvent(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $user_id);
  663. }
  664. /**
  665. * Subscribes users (students) to the given session and optionally (default) unsubscribes previous users
  666. * @author Carlos Vargas from existing code
  667. * @param integer Session ID
  668. * @param array List of user IDs
  669. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  670. * @return void Nothing, or false on error
  671. **/
  672. public static function suscribe_users_to_session($id_session, $user_list, $session_visibility = SESSION_VISIBLE_READ_ONLY, $empty_users = true, $send_email = false) {
  673. if ($id_session!= strval(intval($id_session))) return false;
  674. foreach ($user_list as $intUser){
  675. if ($intUser!= strval(intval($intUser))) return false;
  676. }
  677. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  678. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  679. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  680. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  681. $session_info = api_get_session_info($id_session);
  682. if ($session_info) {
  683. $session_name = $session_info['name'];
  684. } else {
  685. return false;
  686. }
  687. //from function parameter
  688. if (empty($session_visibility)) {
  689. $session_visibility = $session_info['visibility']; //loaded from DB
  690. //default status loaded if empty
  691. if (empty($session_visibility))
  692. $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
  693. } else {
  694. if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
  695. $session_visibility = SESSION_VISIBLE_READ_ONLY;
  696. }
  697. }
  698. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$id_session' AND status = 0";
  699. $result = Database::query($sql);
  700. $existingUsers = array();
  701. while ($row = Database::fetch_array($result)) {
  702. $existingUsers[] = $row['id_user'];
  703. }
  704. $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE id_session = '$id_session'";
  705. $result = Database::query($sql);
  706. $course_list = array();
  707. while ($row = Database::fetch_array($result)) {
  708. $course_list[] = $row['c_id'];
  709. }
  710. if ($send_email) {
  711. //sending emails only
  712. if (is_array($user_list) && count($user_list)>0) {
  713. foreach ($user_list as $user_id) {
  714. if (!in_array($user_id, $existingUsers)) {
  715. $subject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
  716. $user_info = api_get_user_info($user_id);
  717. $content = get_lang('Dear')." ".stripslashes($user_info['complete_name']).",\n\n".sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) ." \n\n" .get_lang('Address') ." ". api_get_setting('platform.site_name') ." ". get_lang('Is') ." : ". api_get_path(WEB_PATH) ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
  718. MessageManager::send_message($user_id, $subject, $content, array(), array(), null, null, null, null, null);
  719. }
  720. }
  721. }
  722. }
  723. foreach ($course_list as $courseId) {
  724. // for each course in the session
  725. $nbr_users = 0;
  726. $courseId = Database::escape_string($courseId);
  727. // delete existing users
  728. if ($empty_users) {
  729. foreach ($existingUsers as $existing_user) {
  730. if (!in_array($existing_user, $user_list)) {
  731. $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id ='$courseId' AND id_user='$existing_user' AND status = 0";
  732. $result = Database::query($sql);
  733. if (Database::affected_rows($result)) {
  734. $nbr_users--;
  735. }
  736. }
  737. }
  738. }
  739. //Replace with this new function
  740. //
  741. // insert new users into session_rel_course_rel_user and ignore if they already exist
  742. foreach ($user_list as $enreg_user) {
  743. if(!in_array($enreg_user, $existingUsers)) {
  744. $enreg_user = Database::escape_string($enreg_user);
  745. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, visibility, status) VALUES('$id_session','$courseId','$enreg_user','$session_visibility', '0')";
  746. $result = Database::query($insert_sql);
  747. if (Database::affected_rows($result)) {
  748. $nbr_users++;
  749. }
  750. }
  751. }
  752. // count users in this session-course relation
  753. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id ='$courseId' AND status<>2";
  754. $rs = Database::query($sql);
  755. list($nbr_users) = Database::fetch_array($rs);
  756. // update the session-course relation to add the users total
  757. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users WHERE id_session='$id_session' AND c_id ='$courseId'";
  758. Database::query($update_sql);
  759. }
  760. // Delete users from the session
  761. if ($empty_users === true) {
  762. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session = $id_session AND relation_type<>".SESSION_RELATION_TYPE_RRHH."");
  763. }
  764. // Insert missing users into session
  765. $nbr_users = 0;
  766. foreach ($user_list as $enreg_user) {
  767. $enreg_user = Database::escape_string($enreg_user);
  768. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user) VALUES ('$id_session', '$enreg_user')";
  769. Database::query($insert_sql);
  770. //Reset moved_to just in case
  771. $update_sql = "UPDATE $tbl_session_rel_user SET moved_to = 0, moved_status = 0, moved_at ='0000-00-00 00:00:00'
  772. WHERE id_session = $id_session AND id_user = $enreg_user";
  773. Database::query($update_sql);
  774. $nbr_users++;
  775. }
  776. // update number of users in the session
  777. $nbr_users = count($user_list);
  778. if ($empty_users) {
  779. // update number of users in the session
  780. $update_sql = "UPDATE $tbl_session SET nbr_users = $nbr_users WHERE id='$id_session' ";
  781. Database::query($update_sql);
  782. } else {
  783. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users WHERE id='$id_session' ";
  784. Database::query($update_sql);
  785. }
  786. }
  787. /**
  788. * @param $user_list
  789. * @param $session_id
  790. * @param $courseId
  791. * @param int $session_visibility
  792. * @return bool
  793. */
  794. static function subscribe_users_to_session_course($user_list, $session_id, $courseId, $session_visibility = SESSION_VISIBLE_READ_ONLY ) {
  795. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  796. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  797. if (empty($user_list) || empty($session_id) || empty($course_code)) {
  798. return false;
  799. }
  800. $session_id = intval($session_id);
  801. $courseId = Database::escape_string($courseId);
  802. $session_visibility = intval($session_visibility);
  803. $nbr_users = 0;
  804. foreach ($user_list as $enreg_user) {
  805. //if (!in_array($enreg_user, $existingUsers)) {
  806. $enreg_user = intval($enreg_user);
  807. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, visibility)
  808. VALUES ('$session_id','$courseId','$enreg_user','$session_visibility')";
  809. $result = Database::query($insert_sql);
  810. if (Database::affected_rows($result)) {
  811. $nbr_users++;
  812. }
  813. //}
  814. }
  815. // count users in this session-course relation
  816. $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$session_id' AND c_id = '$courseId' AND status<>2";
  817. $rs = Database::query($sql);
  818. list($nbr_users) = Database::fetch_array($rs);
  819. // update the session-course relation to add the users total
  820. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users WHERE id_session='$session_id' AND c_id = '$courseId'";
  821. Database::query($update_sql);
  822. }
  823. /**
  824. * Unsubscribe user from session
  825. *
  826. * @param int session id
  827. * @param int user id
  828. * @param int reason of unsubscription see function get_session_change_user_reasons()
  829. * @return bool true in case of success, false in case of error
  830. */
  831. public static function unsubscribe_user_from_session($session_id, $user_id) {
  832. $session_id = intval($session_id);
  833. $user_id = intval($user_id);
  834. $reason_id = intval($reason_id);
  835. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  836. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  837. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  838. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  839. $user_status = SessionManager::get_user_status_in_session($session_id, $user_id);
  840. if ($user_status['moved_to'] != 0) {
  841. //You can't subscribe a user that was moved
  842. return false;
  843. }
  844. $delete_sql = "DELETE FROM $tbl_session_rel_user WHERE id_session = '$session_id' AND id_user ='$user_id' AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
  845. $result = Database::query($delete_sql);
  846. $return = Database::affected_rows($result);
  847. // Update number of users
  848. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users - $return WHERE id='$session_id' ";
  849. Database::query($update_sql);
  850. // Get the list of courses related to this session
  851. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  852. if (!empty($course_list)) {
  853. foreach($course_list as $course) {
  854. $courseId = $course['id'];
  855. // Delete user from course
  856. $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$session_id' AND c_id='$courseId' AND id_user='$user_id'");
  857. if (Database::affected_rows($result)) {
  858. // Update number of users in this relation
  859. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users - 1 WHERE id_session='$session_id' AND c_id ='$courseId'");
  860. }
  861. }
  862. }
  863. return true;
  864. }
  865. /**
  866. *
  867. * @param int $session_id
  868. * @param array user id list
  869. * @param int $courseId
  870. */
  871. static function unsubscribe_user_from_course_session($session_id, $user_list, $courseId) {
  872. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  873. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  874. if (is_array($user_list) && count($user_list)>0 ) {
  875. array_map('intval', $user_list);
  876. $user_list = implode(',', $user_list);
  877. }
  878. $session_id = intval($session_id);
  879. $courseId = Database::escape_string($courseId);
  880. if (!empty($user_list)) {
  881. $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$session_id' AND c_id='".$courseId."' AND id_user IN($user_list)");
  882. $nbr_affected_rows = Database::affected_rows($result);
  883. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$session_id' AND c_id='".$courseId."'");
  884. }
  885. }
  886. /** Subscribes courses to the given session and optionally (default) unsubscribes previous users
  887. * @author Carlos Vargas from existing code
  888. * @param int Session ID
  889. * @param array List of courses IDs
  890. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  891. * @return void Nothing, or false on error
  892. **/
  893. public static function add_courses_to_session($id_session, $course_list, $empty_courses = true) {
  894. // security checks
  895. if ($id_session!= strval(intval($id_session))) { return false; }
  896. // initialisation
  897. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  898. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  899. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  900. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  901. // get general coach ID
  902. $id_coach = Database::query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
  903. $id_coach = Database::fetch_array($id_coach);
  904. $id_coach = $id_coach[0];
  905. // get list of courses subscribed to this session
  906. $rs = Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE id_session=$id_session");
  907. $existingCourses = Database::store_result($rs, 'ASSOC');
  908. $nbr_courses=count($existingCourses);
  909. // get list of users subscribed to this session
  910. $sql="SELECT id_user
  911. FROM $tbl_session_rel_user
  912. WHERE id_session = $id_session AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
  913. $result=Database::query($sql);
  914. $user_list=Database::store_result($result, 'ASSOC');
  915. // Remove existing courses from the session
  916. if ($empty_courses === true) {
  917. foreach ($existingCourses as $existingCourse) {
  918. if (!in_array($existingCourse['c_id'], $course_list)){
  919. Database::query("DELETE FROM $tbl_session_rel_course WHERE c_id='".$existingCourse['c_id']."' AND id_session=$id_session");
  920. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id='".$existingCourse['c_id']."' AND id_session=$id_session");
  921. }
  922. }
  923. $nbr_courses=0;
  924. }
  925. // Pass through the courses list we want to add to the session
  926. foreach ($course_list as $courseId) {
  927. $courseId = Database::escape_string($courseId);
  928. $exists = false;
  929. // check if the course we want to add is already subscribed
  930. foreach ($existingCourses as $existingCourse) {
  931. if ($courseId == $existingCourse['c_id']) {
  932. $exists=true;
  933. }
  934. }
  935. if ($exists == false) {
  936. CourseManager::update_course_ranking($courseId, $id_session);
  937. //if the course isn't subscribed yet
  938. $sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course (id_session, c_id) VALUES ('$id_session','$courseId')";
  939. Database::query($sql_insert_rel_course);
  940. //We add the current course in the existing courses array, to avoid adding another time the current course
  941. $existingCourses[]=array('c_id' => $courseId);
  942. $nbr_courses++;
  943. // subscribe all the users from the session to this course inside the session
  944. $nbr_users=0;
  945. foreach ($user_list as $enreg_user) {
  946. $enreg_user_id = Database::escape_string($enreg_user['id_user']);
  947. $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, c_id, id_user) VALUES ('$id_session','$courseId','$enreg_user_id')";
  948. $result = Database::query($sql_insert);
  949. if (Database::affected_rows($result)) {
  950. $nbr_users++;
  951. }
  952. }
  953. SessionManager::subscribe_users_to_session_course($user_list, $id_session, $courseId);
  954. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND c_id = '$courseId'");
  955. }
  956. }
  957. Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'");
  958. }
  959. /**
  960. * Unsubscribe course from a session
  961. *
  962. * @param int Session id
  963. * @param int Course id
  964. * @return bool True in case of success, false otherwise
  965. */
  966. public static function unsubscribe_course_from_session($session_id, $course_id) {
  967. $session_id = (int)$session_id;
  968. $course_id = (int)$course_id;
  969. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  970. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  971. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  972. // Unsubscribe course
  973. $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE c_id ='$course_id' AND id_session='$session_id'");
  974. $nb_affected = Database::affected_rows($result);
  975. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id ='$course_id' AND id_session='$session_id'");
  976. if ($nb_affected > 0) {
  977. // Update number of courses in the session
  978. Database::query("UPDATE $tbl_session SET nbr_courses= nbr_courses + $nb_affected WHERE id='$session_id' ");
  979. return true;
  980. } else {
  981. return false;
  982. }
  983. }
  984. /**
  985. * Creates a new extra field for a given session
  986. * @param string Field's internal variable name
  987. * @param int Field's type
  988. * @param string Field's language var name
  989. * @return int new extra field id
  990. */
  991. public static function create_session_extra_field ($fieldvarname, $fieldtype, $fieldtitle) {
  992. // database table definition
  993. $params = array('field_variable' => $fieldvarname,
  994. 'field_type' => $fieldtype,
  995. 'field_display_text' => $fieldtitle
  996. );
  997. $session_field = new SessionField();
  998. $field_id = $session_field->save($params);
  999. return $field_id;
  1000. }
  1001. /**
  1002. * Update an extra field value for a given session
  1003. * @param integer Course ID
  1004. * @param string Field variable name
  1005. * @param string Field value
  1006. * @return boolean true if field updated, false otherwise
  1007. */
  1008. public static function update_session_extra_field_value($session_id, $fname, $fvalue = null) {
  1009. /*$session_field_value = new SessionFieldValue();
  1010. $session_field_value->update($params);*/
  1011. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1012. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1013. $fname = Database::escape_string($fname);
  1014. $session_id = (int)$session_id;
  1015. $tms = api_get_utc_datetime();
  1016. $fvalues = '';
  1017. if (is_array($fvalue)) {
  1018. foreach($fvalue as $val) {
  1019. $fvalues .= Database::escape_string($val).';';
  1020. }
  1021. if(!empty($fvalues)) {
  1022. $fvalues = substr($fvalues,0,-1);
  1023. }
  1024. } else {
  1025. $fvalues = Database::escape_string($fvalue);
  1026. }
  1027. $sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
  1028. $ressf = Database::query($sqlsf);
  1029. if (Database::num_rows($ressf)==1) {
  1030. // ok, the field exists
  1031. // Check if enumerated field, if the option is available
  1032. $rowsf = Database::fetch_array($ressf);
  1033. $sqlsfv = "SELECT * FROM $t_sfv WHERE session_id = '$session_id' AND field_id = '".$rowsf['id']."' ORDER BY id";
  1034. $ressfv = Database::query($sqlsfv);
  1035. $n = Database::num_rows($ressfv);
  1036. if ($n>1) {
  1037. //problem, we already have to values for this field and user combination - keep last one
  1038. while($rowsfv = Database::fetch_array($ressfv)) {
  1039. if($n > 1) {
  1040. $sqld = "DELETE FROM $t_sfv WHERE id = ".$rowsfv['id'];
  1041. $resd = Database::query($sqld);
  1042. $n--;
  1043. }
  1044. $rowsfv = Database::fetch_array($ressfv);
  1045. if ($rowsfv['field_value'] != $fvalues) {
  1046. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = '$tms' WHERE id = ".$rowsfv['id'];
  1047. $resu = Database::query($sqlu);
  1048. return($resu?true:false);
  1049. }
  1050. return true;
  1051. }
  1052. } else if ($n==1) {
  1053. //we need to update the current record
  1054. $rowsfv = Database::fetch_array($ressfv);
  1055. if($rowsfv['field_value'] != $fvalues) {
  1056. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = '$tms' WHERE id = ".$rowsfv['id'];
  1057. //error_log('UM::update_extra_field_value: '.$sqlu);
  1058. $resu = Database::query($sqlu);
  1059. return($resu?true:false);
  1060. }
  1061. return true;
  1062. } else {
  1063. $sqli = "INSERT INTO $t_sfv (session_id,field_id,field_value,tms) " .
  1064. "VALUES ('$session_id',".$rowsf['id'].",'$fvalues', '$tms')";
  1065. //error_log('UM::update_extra_field_value: '.$sqli);
  1066. $resi = Database::query($sqli);
  1067. return($resi?true:false);
  1068. }
  1069. } else {
  1070. return false; //field not found
  1071. }
  1072. }
  1073. /**
  1074. * Checks the relationship between a session and a course.
  1075. * @param int $session_id
  1076. * @param int $course_id
  1077. * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
  1078. * */
  1079. public static function relation_session_course_exist ($session_id, $courseId) {
  1080. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1081. $return_value = false;
  1082. $sql= "SELECT c_id FROM $tbl_session_course
  1083. WHERE id_session = ".Database::escape_string($session_id)." AND c_id = '".Database::escape_string($courseId)."'";
  1084. $result = Database::query($sql);
  1085. $num = Database::num_rows($result);
  1086. if ($num>0) {
  1087. $return_value = true;
  1088. }
  1089. return $return_value;
  1090. }
  1091. /**
  1092. * Get the session information by name
  1093. * @param string session name
  1094. * @return mixed false if the session does not exist, array if the session exist
  1095. * */
  1096. public static function get_session_by_name ($session_name) {
  1097. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1098. $sql = 'SELECT * FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name).'"';
  1099. $result = Database::query($sql);
  1100. $num = Database::num_rows($result);
  1101. if ($num) {
  1102. return Database::fetch_array($result, 'ASSOC');
  1103. } else {
  1104. return false;
  1105. }
  1106. }
  1107. /**
  1108. * Create a session category
  1109. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  1110. * @param string name
  1111. * @param integer year_start
  1112. * @param integer month_start
  1113. * @param integer day_start
  1114. * @param integer year_end
  1115. * @param integer month_end
  1116. * @param integer day_end
  1117. * @return $id_session;
  1118. **/
  1119. public static function create_category_session($sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end){
  1120. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1121. $name= trim($sname);
  1122. $year_start= intval($syear_start);
  1123. $month_start=intval($smonth_start);
  1124. $day_start=intval($sday_start);
  1125. $year_end=intval($syear_end);
  1126. $month_end=intval($smonth_end);
  1127. $day_end=intval($sday_end);
  1128. $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
  1129. $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
  1130. if (empty($name)) {
  1131. $msg=get_lang('SessionCategoryNameIsRequired');
  1132. return $msg;
  1133. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
  1134. $msg=get_lang('InvalidStartDate');
  1135. return $msg;
  1136. } elseif (!$month_end && !$day_end && !$year_end) {
  1137. $date_end = "null";
  1138. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
  1139. $msg=get_lang('InvalidEndDate');
  1140. return $msg;
  1141. } elseif($date_start >= $date_end) {
  1142. $msg=get_lang('StartDateShouldBeBeforeEndDate');
  1143. return $msg;
  1144. }
  1145. $access_url_id = api_get_current_access_url_id();
  1146. $sql = "INSERT INTO $tbl_session_category (name, date_start, date_end, access_url_id)
  1147. VALUES('".Database::escape_string($name)."','$date_start','$date_end', '$access_url_id')";
  1148. Database::query($sql);
  1149. $id_session = Database::insert_id();
  1150. // Add event to system log
  1151. $user_id = api_get_user_id();
  1152. Event::addEvent(LOG_SESSION_CATEGORY_CREATE, LOG_SESSION_CATEGORY_ID, $id_session, api_get_utc_datetime(), $user_id);
  1153. return $id_session;
  1154. }
  1155. /**
  1156. * Edit a sessions categories
  1157. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
  1158. * @param integer id
  1159. * @param string name
  1160. * @param integer year_start
  1161. * @param integer month_start
  1162. * @param integer day_start
  1163. * @param integer year_end
  1164. * @param integer month_end
  1165. * @param integer day_end
  1166. * @return $id;
  1167. * The parameter id is a primary key
  1168. **/
  1169. public static function edit_category_session($id, $sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end){
  1170. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1171. $name= trim($sname);
  1172. $year_start= intval($syear_start);
  1173. $month_start=intval($smonth_start);
  1174. $day_start=intval($sday_start);
  1175. $year_end=intval($syear_end);
  1176. $month_end=intval($smonth_end);
  1177. $day_end=intval($sday_end);
  1178. $id=intval($id);
  1179. $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
  1180. $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
  1181. if (empty($name)) {
  1182. $msg=get_lang('SessionCategoryNameIsRequired');
  1183. return $msg;
  1184. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
  1185. $msg=get_lang('InvalidStartDate');
  1186. return $msg;
  1187. } elseif (!$month_end && !$day_end && !$year_end) {
  1188. $date_end = null;
  1189. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
  1190. $msg=get_lang('InvalidEndDate');
  1191. return $msg;
  1192. } elseif($date_start >= $date_end) {
  1193. $msg=get_lang('StartDateShouldBeBeforeEndDate');
  1194. return $msg;
  1195. }
  1196. if ( $date_end <> null ) {
  1197. $sql = "UPDATE $tbl_session_category SET name = '".Database::escape_string($name)."', date_start = '$date_start' ".
  1198. ", date_end = '$date_end' WHERE id= '".$id."' ";
  1199. } else {
  1200. $sql = "UPDATE $tbl_session_category SET name = '".Database::escape_string($name)."', date_start = '$date_start' ".
  1201. ", date_end = NULL WHERE id= '".$id."' ";
  1202. }
  1203. $result = Database::query($sql);
  1204. return ($result? true:false);
  1205. }
  1206. /**
  1207. * Delete sessions categories
  1208. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  1209. * @param array id_checked
  1210. * @param bool include delete session
  1211. * @param bool optional, true if the function is called by a webservice, false otherwise.
  1212. * @return void Nothing, or false on error
  1213. * The parameters is a array to delete sessions
  1214. **/
  1215. public static function delete_session_category($id_checked, $delete_session = false,$from_ws = false){
  1216. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1217. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1218. if (is_array($id_checked)) {
  1219. $id_checked = Database::escape_string(implode(',',$id_checked));
  1220. } else {
  1221. $id_checked = intval($id_checked);
  1222. }
  1223. //Setting session_category_id to 0
  1224. $sql = "UPDATE $tbl_session SET session_category_id = 0 WHERE session_category_id IN (".$id_checked.")";
  1225. Database::query($sql);
  1226. $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (".$id_checked.")";
  1227. $result = @Database::query($sql);
  1228. while ($rows = Database::fetch_array($result)) {
  1229. $session_id = $rows['id'];
  1230. if ($delete_session) {
  1231. if ($from_ws) {
  1232. SessionManager::delete_session($session_id,true);
  1233. } else {
  1234. SessionManager::delete_session($session_id);
  1235. }
  1236. }
  1237. }
  1238. $sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
  1239. $rs = Database::query($sql);
  1240. $result = Database::affected_rows($rs);
  1241. // Add event to system log
  1242. $user_id = api_get_user_id();
  1243. Event::addEvent(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, api_get_utc_datetime(), $user_id);
  1244. // delete extra session fields where field variable is "PERIODO"
  1245. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1246. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1247. $sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'PERIODO' ";
  1248. $rs_field = Database::query($sql);
  1249. $field_id = 0;
  1250. if (Database::num_rows($rs_field) > 0) {
  1251. $row_field = Database::fetch_row($rs_field);
  1252. $field_id = $row_field[0];
  1253. $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
  1254. $rs_delete_sfv = Database::query($sql_delete_sfv);
  1255. }
  1256. $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
  1257. $rs_field_id = Database::query($sql);
  1258. if (Database::num_rows($rs_field_id) == 0) {
  1259. $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
  1260. $rs_delete_sf = Database::query($sql_delete_sf);
  1261. }
  1262. return true;
  1263. }
  1264. /**
  1265. * Get a list of sessions of which the given conditions match with an = 'cond'
  1266. * @param array $conditions a list of condition (exemple : array('status =' =>STUDENT) or array('s.name LIKE' => "%$needle%")
  1267. * @param array $order_by a list of fields on which sort
  1268. * @return array An array with all sessions of the platform.
  1269. * @todo optional course code parameter, optional sorting parameters...
  1270. */
  1271. public static function get_sessions_list($conditions = array(), $order_by = array()) {
  1272. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1273. $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1274. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1275. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1276. $access_url_id = api_get_current_access_url_id();
  1277. $return_array = array();
  1278. $sql_query = " SELECT s.id, s.name, s.nbr_courses, s.access_start_date, s.access_end_date, u.firstname, u.lastname, sc.name as category_name, s.promotion_id
  1279. FROM $session_table s
  1280. INNER JOIN $user_table u ON s.id_coach = u.user_id
  1281. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  1282. LEFT JOIN $session_category_table sc ON s.session_category_id = sc.id
  1283. WHERE ar.access_url_id = $access_url_id ";
  1284. if (count($conditions) > 0) {
  1285. $sql_query .= ' AND ';
  1286. foreach ($conditions as $field=>$value) {
  1287. $field = Database::escape_string($field);
  1288. $value = Database::escape_string($value);
  1289. $sql_query .= $field." '".$value."'";
  1290. }
  1291. }
  1292. if (count($order_by)>0) {
  1293. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',',$order_by));
  1294. }
  1295. //echo $sql_query;
  1296. $sql_result = Database::query($sql_query);
  1297. if (Database::num_rows($sql_result)>0) {
  1298. while ($result = Database::fetch_array($sql_result)) {
  1299. $return_array[$result['id']] = $result;
  1300. }
  1301. }
  1302. return $return_array;
  1303. }
  1304. /**
  1305. * Get the session category information by id
  1306. * @param string session category ID
  1307. * @return mixed false if the session category does not exist, array if the session category exists
  1308. */
  1309. public static function get_session_category ($id) {
  1310. $id = intval($id);
  1311. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1312. $sql = "SELECT id, name, date_start, date_end FROM $tbl_session_category WHERE id= $id";
  1313. $result = Database::query($sql);
  1314. $num = Database::num_rows($result);
  1315. if ($num>0){
  1316. return Database::fetch_array($result);
  1317. } else {
  1318. return false;
  1319. }
  1320. }
  1321. /**
  1322. * Get all session categories (filter by access_url_id)
  1323. * @return mixed false if the session category does not exist, array if the session category exists
  1324. */
  1325. public static function get_all_session_category() {
  1326. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1327. $id = api_get_current_access_url_id();
  1328. $sql = 'SELECT * FROM '.$tbl_session_category.' WHERE access_url_id ="'.$id.'" ORDER BY name ASC';
  1329. $result = Database::query($sql);
  1330. if (Database::num_rows($result) > 0 ){
  1331. $data = Database::store_result($result,'ASSOC');
  1332. return $data;
  1333. } else {
  1334. return false;
  1335. }
  1336. }
  1337. /**
  1338. * Assign a coach to course in session with status = 2
  1339. * @param int - user id
  1340. * @param int - session id
  1341. * @param int - course id
  1342. * @param bool - optional, if is true the user don't be a coach now, otherwise it'll assign a coach
  1343. * @return bool true if there are affected rows, otherwise false
  1344. */
  1345. public static function set_coach_to_course_session($user_id, $session_id = 0, $courseId = '',$nocoach = false) {
  1346. // Definition of variables
  1347. $user_id = intval($user_id);
  1348. if (!empty($session_id)) {
  1349. $session_id = intval($session_id);
  1350. } else {
  1351. $session_id = api_get_session_id();
  1352. }
  1353. if (!empty($courseId)) {
  1354. $courseId = Database::escape_string($courseId);
  1355. } else {
  1356. $courseId = api_get_course_int_id();
  1357. }
  1358. // definitios of tables
  1359. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1360. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1361. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1362. // check if user is a teacher
  1363. $sql= "SELECT * FROM $tbl_user WHERE status='1' AND user_id = '$user_id'";
  1364. $rs_check_user = Database::query($sql);
  1365. if (Database::num_rows($rs_check_user) > 0) {
  1366. if ($nocoach) {
  1367. // check if user_id exits int session_rel_user
  1368. $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session = '$session_id' AND id_user = '$user_id'";
  1369. $res = Database::query($sql);
  1370. if (Database::num_rows($res) > 0) {
  1371. // The user don't be a coach now
  1372. $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 0 WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' ";
  1373. $rs_update = Database::query($sql);
  1374. if (Database::affected_rows($rs_update) > 0) return true;
  1375. else return false;
  1376. } else {
  1377. // The user don't be a coach now
  1378. $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' ";
  1379. $rs_delete = Database::query($sql);
  1380. if (Database::affected_rows($rs_delete) > 0) return true;
  1381. else return false;
  1382. }
  1383. } else {
  1384. // Assign user like a coach to course
  1385. // First check if the user is registered in the course
  1386. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id'";
  1387. $rs_check = Database::query($sql);
  1388. //Then update or insert
  1389. if (Database::num_rows($rs_check) > 0) {
  1390. $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2 WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' ";
  1391. $rs_update = Database::query($sql);
  1392. if (Database::affected_rows($rs_update) > 0) return true;
  1393. else return false;
  1394. } else {
  1395. $sql = " INSERT INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, status) VALUES('$session_id', '$courseId', '$user_id', 2)";
  1396. $rs_insert = Database::query($sql);
  1397. if (Database::affected_rows($rs_insert) > 0) return true;
  1398. else return false;
  1399. }
  1400. }
  1401. } else {
  1402. return false;
  1403. }
  1404. }
  1405. /**
  1406. * Subscribes sessions to human resource manager (Dashboard feature)
  1407. * @param int Human Resource Manager id
  1408. * @param array Sessions id
  1409. * @param int Relation type
  1410. **/
  1411. public static function suscribe_sessions_to_hr_manager($hr_manager_id,$sessions_list) {
  1412. global $_configuration;
  1413. // Database Table Definitions
  1414. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1415. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1416. $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1417. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1418. $hr_manager_id = intval($hr_manager_id);
  1419. $affected_rows = 0;
  1420. //Deleting assigned sessions to hrm_id
  1421. if (api_is_multiple_url_enabled()) {
  1422. $sql = "SELECT id_session FROM $tbl_session_rel_user s INNER JOIN $tbl_session_rel_access_url a ON (a.session_id = s.id_session)
  1423. WHERE id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH." AND access_url_id = ".api_get_current_access_url_id()."";
  1424. } else {
  1425. $sql = "SELECT id_session FROM $tbl_session_rel_user s WHERE id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH."";
  1426. }
  1427. $result = Database::query($sql);
  1428. if (Database::num_rows($result) > 0) {
  1429. while ($row = Database::fetch_array($result)) {
  1430. $sql = "DELETE FROM $tbl_session_rel_user
  1431. WHERE id_session = {$row['id_session']} AND id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH." ";
  1432. Database::query($sql);
  1433. }
  1434. }
  1435. // inserting new sessions list
  1436. if (is_array($sessions_list)) {
  1437. foreach ($sessions_list as $session_id) {
  1438. $session_id = intval($session_id);
  1439. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user, relation_type) VALUES($session_id, $hr_manager_id, '".SESSION_RELATION_TYPE_RRHH."')";
  1440. $result = Database::query($insert_sql);
  1441. $affected_rows = Database::affected_rows($result);
  1442. }
  1443. }
  1444. return $affected_rows;
  1445. }
  1446. /**
  1447. * Get sessions followed by human resources manager
  1448. * @param int Human resources manager or Session admin id
  1449. * @return array sessions
  1450. */
  1451. public static function get_sessions_followed_by_drh($hr_manager_id)
  1452. {
  1453. // Database Table Definitions
  1454. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1455. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1456. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1457. $hr_manager_id = intval($hr_manager_id);
  1458. $assigned_sessions_to_hrm = array();
  1459. if (api_is_multiple_url_enabled()) {
  1460. $sql = "SELECT * FROM $tbl_session s INNER JOIN $tbl_session_rel_user sru ON (sru.id_session = s.id) LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
  1461. WHERE sru.id_user = '$hr_manager_id' AND sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND access_url_id = ".api_get_current_access_url_id()."";
  1462. } else {
  1463. $sql = "SELECT * FROM $tbl_session s
  1464. INNER JOIN $tbl_session_rel_user sru ON sru.id_session = s.id AND sru.id_user = '$hr_manager_id' AND sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' ";
  1465. }
  1466. $rs_assigned_sessions = Database::query($sql);
  1467. if (Database::num_rows($rs_assigned_sessions) > 0) {
  1468. while ($row_assigned_sessions = Database::fetch_array($rs_assigned_sessions)) {
  1469. $assigned_sessions_to_hrm[$row_assigned_sessions['id']] = $row_assigned_sessions;
  1470. }
  1471. }
  1472. return $assigned_sessions_to_hrm;
  1473. }
  1474. /**
  1475. * Gets the list of courses by session filtered by access_url
  1476. * @param int session id
  1477. * @return array list of courses
  1478. */
  1479. public static function get_course_list_by_session_id ($session_id) {
  1480. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1481. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1482. // select the courses
  1483. $sql = "SELECT c.*, c.id as real_id FROM $tbl_course c INNER JOIN $tbl_session_rel_course src ON c.id = src.c_id
  1484. WHERE src.id_session = '$session_id'
  1485. ORDER BY title;";
  1486. $result = Database::query($sql);
  1487. $num_rows = Database::num_rows($result);
  1488. $courses = array();
  1489. if ($num_rows > 0) {
  1490. while ($row = Database::fetch_array($result,'ASSOC')) {
  1491. $row['real_id'] = $row['id'];
  1492. $courses[$row['id']] = $row;
  1493. }
  1494. }
  1495. return $courses;
  1496. }
  1497. /**
  1498. * Get the session id based on the original id and field name in the extra fields. Returns 0 if session was not found
  1499. *
  1500. * @param string Original session id
  1501. * @param string Original field name
  1502. * @return int Session id
  1503. */
  1504. public static function get_session_id_from_original_id($original_session_id_value, $original_session_id_name) {
  1505. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1506. $table_field = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1507. $sql_session = "SELECT session_id FROM $table_field sf INNER JOIN $t_sfv sfv ON sfv.field_id=sf.id WHERE field_variable='$original_session_id_name' AND field_value='$original_session_id_value'";
  1508. $res_session = Database::query($sql_session);
  1509. $row = Database::fetch_object($res_session);
  1510. if ($row) {
  1511. return $row->session_id;
  1512. } else {
  1513. return 0;
  1514. }
  1515. }
  1516. /**
  1517. * Get users by session
  1518. * @param int session id
  1519. * @param int filter by status
  1520. * @return array a list with an user list
  1521. */
  1522. public static function get_users_by_session($id, $with_status = null) {
  1523. if (empty($id)) {
  1524. return array();
  1525. }
  1526. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1527. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1528. $id = intval($id);
  1529. /*
  1530. * sessions are not shared between urls
  1531. if (api_is_multiple_url_enabled()) {
  1532. $tbl_session_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1533. $url_id = api_get_current_access_url_id();
  1534. $sql = "SELECT u.user_id, lastname, firstname, username, access_url_id, moved_to, moved_status, moved_at
  1535. FROM $tbl_user u
  1536. INNER JOIN $tbl_session_rel_user su
  1537. ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH."
  1538. INNER JOIN $tbl_session_rel_url s ON (s.session_id = su.id_session)
  1539. LEFT OUTER JOIN $tbl_session_rel_user uu ON (uu.user_id = u.user_id AND s.session_id = uu.id_session)
  1540. WHERE su.id_session = $id AND (access_url_id = $url_id OR access_url_id is null )";
  1541. } else {
  1542. $sql = "SELECT u.user_id, lastname, firstname, username, moved_to, moved_status, moved_at
  1543. FROM $tbl_user u INNER JOIN $tbl_session_rel_user su
  1544. ON u.user_id = su.id_user AND
  1545. su.id_session = $id
  1546. WHERE 1 = 1
  1547. ";
  1548. }*/
  1549. $sql = "SELECT u.user_id,
  1550. lastname,
  1551. firstname,
  1552. username,
  1553. moved_to,
  1554. moved_status,
  1555. moved_at
  1556. FROM $tbl_user u INNER JOIN $tbl_session_rel_user su
  1557. ON u.user_id = su.id_user AND
  1558. su.id_session = $id
  1559. WHERE 1 = 1
  1560. ";
  1561. if (isset($with_status) && $with_status != '') {
  1562. $with_status = intval($with_status);
  1563. $sql .= " AND relation_type = $with_status ";
  1564. }
  1565. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
  1566. $sql .= $order_clause;
  1567. $return_array = array();
  1568. $result = Database::query($sql);
  1569. while ($row = Database::fetch_array($result,'ASSOC')) {
  1570. $return_array[] = $row;
  1571. }
  1572. return $return_array;
  1573. }
  1574. /**
  1575. * The general coach (field: session.id_coach)
  1576. * @param int user id
  1577. */
  1578. public static function get_sessions_by_general_coach($user_id) {
  1579. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1580. $user_id = intval($user_id);
  1581. // session where we are general coach
  1582. $sql = "SELECT DISTINCT *
  1583. FROM $session_table
  1584. WHERE id_coach = $user_id";
  1585. if (api_is_multiple_url_enabled()) {
  1586. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1587. $access_url_id = api_get_current_access_url_id();
  1588. if ($access_url_id != -1) {
  1589. $sql = 'SELECT DISTINCT session.*
  1590. FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  1591. ON (session.id = session_rel_url.session_id)
  1592. WHERE id_coach = '.$user_id.' AND access_url_id = '.$access_url_id;
  1593. }
  1594. }
  1595. $sql .= ' ORDER by name';
  1596. $result = Database::query($sql);
  1597. return Database::store_result($result, 'ASSOC');
  1598. }
  1599. /**
  1600. * Get all sessions if the user is a sesion course coach of any session
  1601. * @param int user id
  1602. */
  1603. static function get_sessions_by_coach($user_id) {
  1604. // table definition
  1605. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1606. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1607. $sql = 'SELECT DISTINCT session.*
  1608. FROM ' . $tbl_session . ' as session
  1609. INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
  1610. ON session.id = session_course_user.id_session
  1611. AND session_course_user.id_user=' . $user_id.' AND session_course_user.status=2';
  1612. if (api_is_multiple_url_enabled()) {
  1613. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1614. $access_url_id = api_get_current_access_url_id();
  1615. if ($access_url_id != -1){
  1616. $sql = 'SELECT DISTINCT session.*
  1617. FROM '.$tbl_session.' as session
  1618. INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
  1619. ON session.id = session_course_user.id_session AND session_course_user.id_user = '.$user_id.' AND session_course_user.status=2
  1620. INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  1621. ON (session.id = session_rel_url.session_id)
  1622. WHERE access_url_id = '.$access_url_id;
  1623. }
  1624. }
  1625. //$sql .= " ORDER BY session.name";
  1626. $result = Database::query($sql);
  1627. return Database::store_result($result, 'ASSOC');
  1628. }
  1629. public static function get_sessions_coached_by_user($coach_id, $check_session_rel_user_visibility = false) {
  1630. $sessions = self::get_sessions_by_general_coach($coach_id);
  1631. $sessions_by_coach = self::get_sessions_by_coach($coach_id);
  1632. if (!empty($sessions_by_coach)) {
  1633. $sessions = array_merge($sessions, $sessions_by_coach);
  1634. }
  1635. //Remove repeated sessions
  1636. if (!empty($sessions)) {
  1637. $clean_sessions = array();
  1638. foreach ($sessions as $session) {
  1639. $clean_sessions[$session['id']] = $session;
  1640. }
  1641. $sessions = $clean_sessions;
  1642. }
  1643. if ($check_session_rel_user_visibility) {
  1644. if (!empty($sessions)) {
  1645. $new_session = array();
  1646. foreach ($sessions as $session) {
  1647. $visibility = api_get_session_visibility($session['id']);
  1648. if ($visibility == SESSION_INVISIBLE) {
  1649. continue;
  1650. }
  1651. $new_session[] = $session;
  1652. }
  1653. $sessions = $new_session;
  1654. }
  1655. }
  1656. return $sessions;
  1657. }
  1658. /**
  1659. * Gets user status within a session
  1660. * @param $user_id
  1661. * @param $course_code
  1662. * @param $session_id
  1663. * @return unknown_type
  1664. */
  1665. public static function get_user_status_in_course_session($user_id, $courseId, $session_id) {
  1666. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1667. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1668. $sql = "SELECT session_rcru.status
  1669. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  1670. WHERE session_rcru.id_user = user.user_id AND
  1671. session_rcru.id_session = '".intval($session_id)."' AND
  1672. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  1673. user.user_id = ".intval($user_id);
  1674. $result = Database::query($sql);
  1675. $status = false;
  1676. if (Database::num_rows($result)) {
  1677. $status = Database::fetch_row($result);
  1678. $status = $status['0'];
  1679. }
  1680. return $status;
  1681. }
  1682. static function get_user_status_in_session($session_id, $user_id) {
  1683. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1684. $session_id = intval($session_id);
  1685. $user_id = intval($user_id);
  1686. $sql = "SELECT * FROM $tbl_session_rel_user WHERE id_user = $user_id AND id_session = $session_id";
  1687. $result = Database::query($sql);
  1688. if (Database::num_rows($result)) {
  1689. $result = Database::store_result($result, 'ASSOC');
  1690. return $result[0];
  1691. }
  1692. return array();
  1693. }
  1694. static function get_all_sessions_by_promotion($id) {
  1695. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1696. return Database::select('*', $t, array('where'=>array('promotion_id = ?'=>$id)));
  1697. }
  1698. static function suscribe_sessions_to_promotion($promotion_id, $list) {
  1699. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1700. $params = array();
  1701. $params['promotion_id'] = 0;
  1702. Database::update($t, $params, array('promotion_id = ?'=>$promotion_id));
  1703. $params['promotion_id'] = $promotion_id;
  1704. if (!empty($list)) {
  1705. foreach ($list as $session_id) {
  1706. $session_id= intval($session_id);
  1707. Database::update($t, $params, array('id = ?'=>$session_id));
  1708. }
  1709. }
  1710. }
  1711. /**
  1712. * Updates a session status
  1713. * @param int session id
  1714. * @param int status
  1715. */
  1716. public static function set_session_status($session_id, $status)
  1717. {
  1718. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1719. $params['visibility'] = $status;
  1720. Database::update($t, $params, array('id = ?'=>$session_id));
  1721. }
  1722. /**
  1723. * Copies a session with the same data to a new session.
  1724. * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
  1725. * @param int Session ID
  1726. * @param bool Whether to copy the relationship with courses
  1727. * @param bool Whether to copy the relationship with users
  1728. * @param bool New courses will be created
  1729. * @return int The new session ID on success, 0 otherwise
  1730. * @todo make sure the extra session fields are copied too
  1731. */
  1732. /**
  1733. * @param $id
  1734. * @param $copy_courses
  1735. * @param $copy_users
  1736. * @param $create_new_courses
  1737. * @param $set_exercises_lp_invisible
  1738. * @return int
  1739. */
  1740. public static function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false) {
  1741. $id = intval($id);
  1742. $params = self::fetch($id);
  1743. $params['name'] = $params['name'].' '.get_lang('CopyLabelSuffix');
  1744. $sid = self::add($params);
  1745. if (!is_numeric($sid) || empty($sid)) {
  1746. return false;
  1747. }
  1748. if ($copy_courses) {
  1749. // Register courses from the original session to the new session
  1750. $courses = self::get_course_list_by_session_id($id);
  1751. $short_courses = $new_short_courses = array();
  1752. if (is_array($courses) && count($courses)>0) {
  1753. foreach ($courses as $course) {
  1754. $short_courses[] = $course;
  1755. }
  1756. }
  1757. $courses = null;
  1758. //We will copy the current courses of the session to new courses
  1759. if (!empty($short_courses)) {
  1760. if ($create_new_courses) {
  1761. //Just in case
  1762. if (function_exists('ini_set')) {
  1763. api_set_memory_limit('256M');
  1764. ini_set('max_execution_time',0);
  1765. }
  1766. $params = array();
  1767. $params['skip_lp_dates'] = true;
  1768. foreach ($short_courses as $course_data) {
  1769. $course_info = CourseManager::copy_course_simple($course_data['title'].' '.get_lang('CopyLabelSuffix'), $course_data['course_code'], $id, $sid, $params);
  1770. if ($course_info) {
  1771. //By default new elements are invisible
  1772. if ($set_exercises_lp_invisible) {
  1773. $list = new LearnpathList('', $course_info['code'], $sid);
  1774. $flat_list = $list->get_flat_list();
  1775. if (!empty($flat_list)) {
  1776. foreach ($flat_list as $lp_id => $data) {
  1777. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0 ,0, 0, 0, $sid);
  1778. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0 ,0, 0, 0);
  1779. }
  1780. }
  1781. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  1782. $course_id = $course_info['real_id'];
  1783. //@todo check this query
  1784. //Disabling quiz items
  1785. $sql = "UPDATE $quiz_table SET active = 0 WHERE c_id = $course_id ";
  1786. Database::query($sql);
  1787. }
  1788. $new_short_courses[] = $course_info['code'];
  1789. }
  1790. }
  1791. } else {
  1792. foreach($short_courses as $course_data) {
  1793. $new_short_courses[] = $course_data['id'];
  1794. }
  1795. }
  1796. $short_courses = $new_short_courses;
  1797. $res = self::add_courses_to_session($sid, $short_courses, true);
  1798. $short_courses = null;
  1799. }
  1800. }
  1801. if ($copy_users) {
  1802. // Register users from the original session to the new session
  1803. $users = self::get_users_by_session($id);
  1804. $short_users = array();
  1805. if (is_array($users) && count($users)>0) {
  1806. foreach ($users as $user) {
  1807. $short_users[] = $user['user_id'];
  1808. }
  1809. }
  1810. $users = null;
  1811. //Subscribing in read only mode
  1812. $res = self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true, false);
  1813. $short_users = null;
  1814. }
  1815. return $sid;
  1816. }
  1817. static function user_is_general_coach($user_id, $session_id) {
  1818. $session_id = intval($session_id);
  1819. $user_id = intval($user_id);
  1820. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1821. $sql = "SELECT DISTINCT id
  1822. FROM $session_table
  1823. WHERE session.id_coach = '".$user_id."' AND id = '$session_id'";
  1824. $result = Database::query($sql);
  1825. if ($result && Database::num_rows($result)) {
  1826. return true;
  1827. }
  1828. return false;
  1829. }
  1830. /**
  1831. * Get the number of sessions
  1832. * @param int ID of the URL we want to filter on (optional)
  1833. * @return int Number of sessions
  1834. */
  1835. public static function count_sessions($access_url_id=null) {
  1836. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1837. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1838. $sql = "SELECT count(id) FROM $session_table s";
  1839. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  1840. $sql .= ", $access_url_rel_session_table u ".
  1841. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  1842. }
  1843. $res = Database::query($sql);
  1844. $row = Database::fetch_row($res);
  1845. return $row[0];
  1846. }
  1847. /**
  1848. * @param int $id
  1849. * @return bool
  1850. */
  1851. static function protect_session_edit($id = null)
  1852. {
  1853. if (api_is_platform_admin()) {
  1854. return false;
  1855. }
  1856. if (api_is_session_admin()) {
  1857. return false;
  1858. }
  1859. $blockTeachers = !api_is_teacher() || (api_is_teacher() && api_get_setting('allow_teachers_to_create_sessions') == 'false');
  1860. if ($blockTeachers) {
  1861. api_not_allowed(true);
  1862. }
  1863. if (!empty($id)) {
  1864. $session_info = self::fetch($id);
  1865. if (empty($session_info)) {
  1866. api_not_allowed(true);
  1867. }
  1868. if ($blockTeachers && !api_is_platform_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true') {
  1869. if ($session_info['session_admin_id'] != api_get_user_id()) {
  1870. api_not_allowed(true);
  1871. }
  1872. }
  1873. //Blocking teachers that want to edit another session
  1874. if ($blockTeachers == false && $session_info['id_coach'] != api_get_user_id()) {
  1875. api_not_allowed(true);
  1876. }
  1877. }
  1878. }
  1879. /**
  1880. * @param $courseId
  1881. * @return array
  1882. */
  1883. static function get_session_by_course($courseId)
  1884. {
  1885. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1886. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1887. $courseId = Database::escape_string($courseId);
  1888. $sql = "SELECT name, s.id FROM $table_session_course sc INNER JOIN $table_session s ON (sc.id_session = s.id)
  1889. WHERE sc.c_id = '$courseId' ";
  1890. $result = Database::query($sql);
  1891. return Database::store_result($result);
  1892. }
  1893. /**
  1894. * @param int $user_id
  1895. * @param bool $ignore_visibility_for_admins
  1896. * @return array
  1897. */
  1898. public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false)
  1899. {
  1900. $session_categories = UserManager::get_sessions_by_category($user_id, false, $ignore_visibility_for_admins);
  1901. $session_array = array();
  1902. if (!empty($session_categories)) {
  1903. foreach ($session_categories as $category) {
  1904. if (isset($category['sessions'])) {
  1905. foreach ($category['sessions'] as $session) {
  1906. $session_array[] = $session;
  1907. }
  1908. }
  1909. }
  1910. }
  1911. return $session_array;
  1912. }
  1913. /**
  1914. * @param string $file
  1915. * @param bool $updateSession options:
  1916. * true: if the session exists it will be updated.
  1917. * false: if session exists a new session will be created adding a counter session1, session2, etc
  1918. * @param int $defaultUserId
  1919. * @param mixed $logger
  1920. * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  1921. * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  1922. * @param string $extraFieldId
  1923. * @param int $daysCoachAccessBeforeBeginning
  1924. * @param int $daysCoachAccessAfterBeginning
  1925. * @param int $sessionVisibility
  1926. * @param array $fieldsToAvoidUpdate
  1927. * @param bool $deleteUsersNotInList
  1928. * @param bool $updateCourseCoaches
  1929. * @param bool $sessionWithCoursesModifier
  1930. * @return array
  1931. */
  1932. static function importCSV(
  1933. $file,
  1934. $updateSession,
  1935. $defaultUserId = null,
  1936. $logger = null,
  1937. $extraFields = array(),
  1938. $extraFieldId = null,
  1939. $daysCoachAccessBeforeBeginning = null,
  1940. $daysCoachAccessAfterBeginning = null,
  1941. $sessionVisibility = 1,
  1942. $fieldsToAvoidUpdate = array(),
  1943. $deleteUsersNotInList = false,
  1944. $updateCourseCoaches = false,
  1945. $sessionWithCoursesModifier = false
  1946. ) {
  1947. $content = file($file);
  1948. $error_message = null;
  1949. $session_counter = 0;
  1950. if (empty($defaultUserId)) {
  1951. $defaultUserId = api_get_user_id();
  1952. }
  1953. $eol = PHP_EOL;
  1954. if (PHP_SAPI != 'cli') {
  1955. $eol = '<br />';
  1956. }
  1957. $debug = false;
  1958. if (isset($logger)) {
  1959. $debug = true;
  1960. }
  1961. $extraParameters = null;
  1962. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  1963. $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
  1964. $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
  1965. }
  1966. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1967. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1968. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1969. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1970. $sessions = array();
  1971. if (!api_strstr($content[0], ';')) {
  1972. $error_message = get_lang('NotCSV');
  1973. } else {
  1974. $tag_names = array();
  1975. foreach ($content as $key => $enreg) {
  1976. $enreg = explode(';', trim($enreg));
  1977. if ($key) {
  1978. foreach ($tag_names as $tag_key => $tag_name) {
  1979. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  1980. }
  1981. } else {
  1982. foreach ($enreg as $tag_name) {
  1983. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  1984. }
  1985. if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
  1986. $error_message = get_lang('NoNeededData');
  1987. break;
  1988. }
  1989. }
  1990. }
  1991. $sessionList = array();
  1992. // Looping the sessions.
  1993. foreach ($sessions as $enreg) {
  1994. $user_counter = 0;
  1995. $course_counter = 0;
  1996. if (isset($extraFields) && !empty($extraFields)) {
  1997. foreach ($extraFields as $original => $to) {
  1998. $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
  1999. }
  2000. }
  2001. $session_name = Database::escape_string($enreg['SessionName']);
  2002. if (empty($session_name)) {
  2003. continue;
  2004. }
  2005. $date_start = $enreg['DateStart'];
  2006. $date_end = $enreg['DateEnd'];
  2007. $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
  2008. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  2009. $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
  2010. $extraSessionParameters = null;
  2011. if (!empty($sessionDescription)) {
  2012. $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
  2013. }
  2014. // Searching a general coach.
  2015. if (!empty($enreg['Coach'])) {
  2016. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  2017. if ($coach_id === false) {
  2018. // If the coach-user does not exist - I'm the coach.
  2019. $coach_id = $defaultUserId;
  2020. }
  2021. } else {
  2022. $coach_id = $defaultUserId;
  2023. }
  2024. if (!$updateSession) {
  2025. // Always create a session.
  2026. $unique_name = false;
  2027. $i = 0;
  2028. // Change session name, verify that session doesn't exist.
  2029. $suffix = null;
  2030. while (!$unique_name) {
  2031. if ($i > 1) {
  2032. $suffix = ' - ' . $i;
  2033. }
  2034. $sql = 'SELECT 1 FROM ' . $tbl_session . ' WHERE name="' . $session_name . $suffix . '"';
  2035. $rs = Database::query($sql);
  2036. if (Database::result($rs, 0, 0)) {
  2037. $i++;
  2038. } else {
  2039. $unique_name = true;
  2040. $session_name .= $suffix;
  2041. }
  2042. }
  2043. // Creating the session.
  2044. $sql = "INSERT IGNORE INTO $tbl_session SET
  2045. name = '" . $session_name . "',
  2046. id_coach = '$coach_id',
  2047. date_start = '$date_start',
  2048. date_end = '$date_end',
  2049. visibility = '$visibility',
  2050. session_category_id = '$session_category_id',
  2051. session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
  2052. Database::query($sql);
  2053. $session_id = Database::insert_id();
  2054. if ($debug) {
  2055. if ($session_id) {
  2056. foreach ($enreg as $key => $value) {
  2057. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2058. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2059. }
  2060. }
  2061. $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
  2062. } else {
  2063. $logger->addError("Sessions - Session NOT created: $session_name");
  2064. }
  2065. }
  2066. $session_counter++;
  2067. } else {
  2068. $sessionId = null;
  2069. if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
  2070. $sessionId = self::get_session_id_from_original_id($enreg['extra_'.$extraFieldId], $extraFieldId);
  2071. if (empty($sessionId)) {
  2072. $my_session_result = false;
  2073. } else {
  2074. $my_session_result = true;
  2075. }
  2076. } else {
  2077. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  2078. }
  2079. if ($my_session_result === false) {
  2080. // Creating a session.
  2081. $sql_session = "INSERT IGNORE INTO $tbl_session SET
  2082. name = '$session_name',
  2083. id_coach = '$coach_id',
  2084. date_start = '$date_start',
  2085. date_end = '$date_end',
  2086. visibility = '$visibility',
  2087. session_category_id = '$session_category_id' " . $extraParameters . $extraSessionParameters;
  2088. Database::query($sql_session);
  2089. // We get the last insert id.
  2090. $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
  2091. $session_id = $my_session_result['id'];
  2092. if ($session_id) {
  2093. if ($session_id) {
  2094. foreach ($enreg as $key => $value) {
  2095. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2096. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2097. }
  2098. }
  2099. if ($debug) {
  2100. $logger->addInfo("Sessions - #$session_id created: $session_name");
  2101. }
  2102. } else {
  2103. if ($debug) {
  2104. $logger->addError("Sessions - Session NOT created: $session_name");
  2105. }
  2106. }
  2107. // Delete session-user relation only for students
  2108. $sql = "DELETE FROM $tbl_session_user
  2109. WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  2110. Database::query($sql);
  2111. $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'";
  2112. Database::query($sql);
  2113. // Delete session-course-user relationships students and coaches.
  2114. if ($updateCourseCoaches) {
  2115. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status in ('0', '2')";
  2116. Database::query($sql);
  2117. } else {
  2118. // Delete session-course-user relation ships *only* for students.
  2119. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status <> 2";
  2120. Database::query($sql);
  2121. }
  2122. }
  2123. } else {
  2124. // Updating the session.
  2125. $params = array(
  2126. 'id_coach' => $coach_id,
  2127. 'date_start' => $date_start,
  2128. 'date_end' => $date_end,
  2129. 'visibility' => $visibility,
  2130. 'session_category_id' => $session_category_id
  2131. );
  2132. if (!empty($sessionDescription)) {
  2133. $params['description'] = $sessionDescription;
  2134. }
  2135. if (!empty($fieldsToAvoidUpdate)) {
  2136. foreach ($fieldsToAvoidUpdate as $field) {
  2137. unset($params[$field]);
  2138. }
  2139. }
  2140. if (isset($sessionId) && !empty($sessionId)) {
  2141. Database::update($tbl_session, $params, array('id = ?' => $sessionId));
  2142. $session_id = $sessionId;
  2143. } else {
  2144. Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName']));
  2145. $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
  2146. list($session_id) = Database::fetch_array($row);
  2147. }
  2148. if ($session_id) {
  2149. foreach ($enreg as $key => $value) {
  2150. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2151. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2152. }
  2153. }
  2154. // Delete session-user relation only for students
  2155. $sql = "DELETE FROM $tbl_session_user
  2156. WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
  2157. Database::query($sql);
  2158. $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'";
  2159. Database::query($sql);
  2160. // Delete session-course-user relationships students and coaches.
  2161. if ($updateCourseCoaches) {
  2162. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status in ('0', '2')";
  2163. Database::query($sql);
  2164. } else {
  2165. // Delete session-course-user relation ships *only* for students.
  2166. $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status <> 2";
  2167. Database::query($sql);
  2168. }
  2169. }
  2170. }
  2171. $session_counter++;
  2172. }
  2173. $sessionList[] = $session_id;
  2174. $users = explode('|', $enreg['Users']);
  2175. // Adding the relationship "Session - User".
  2176. $userList = array();
  2177. if (is_array($users)) {
  2178. foreach ($users as $user) {
  2179. $user_id = UserManager::get_user_id_from_username($user);
  2180. if ($user_id !== false) {
  2181. $userList[] = $user_id;
  2182. // Insert new users.
  2183. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  2184. id_user = '$user_id',
  2185. id_session = '$session_id'";
  2186. Database::query($sql);
  2187. if ($debug) {
  2188. $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
  2189. }
  2190. $user_counter++;
  2191. }
  2192. }
  2193. }
  2194. if ($deleteUsersNotInList) {
  2195. // Getting user in DB in order to compare to the new list.
  2196. $usersListInDatabase = self::get_users_by_session($session_id, 0);
  2197. if (!empty($usersListInDatabase)) {
  2198. if (empty($userList)) {
  2199. foreach ($usersListInDatabase as $userInfo) {
  2200. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  2201. }
  2202. } else {
  2203. foreach ($usersListInDatabase as $userInfo) {
  2204. if (!in_array($userInfo['user_id'], $userList)) {
  2205. self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
  2206. }
  2207. }
  2208. }
  2209. }
  2210. }
  2211. $courses = explode('|', $enreg['Courses']);
  2212. // See BT#6449
  2213. $onlyAddFirstCoachOrTeacher = false;
  2214. $removeAllTeachersFromCourse = false;
  2215. if ($sessionWithCoursesModifier) {
  2216. if (count($courses) >= 2) {
  2217. // Only first teacher in course session;
  2218. $onlyAddFirstCoachOrTeacher = true;
  2219. // Remove all teachers from course.
  2220. $removeAllTeachersFromCourse = true;
  2221. }
  2222. }
  2223. foreach ($courses as $course) {
  2224. $courseArray = bracketsToArray($course);
  2225. $course_code = $courseArray[0];
  2226. if (CourseManager::course_exists($course_code)) {
  2227. $courseInfo = api_get_course_info($course_code);
  2228. $courseId = $courseInfo['real_id'];
  2229. // Adding the course to a session.
  2230. $sql_course = "INSERT IGNORE INTO $tbl_session_course
  2231. SET c_id = '".$courseId."', id_session = '$session_id'";
  2232. Database::query($sql_course);
  2233. $course_info = api_get_course_info($course_code);
  2234. SessionManager::installCourse($session_id, $course_info['real_id']);
  2235. if ($debug) {
  2236. $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
  2237. }
  2238. $course_counter++;
  2239. $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
  2240. $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
  2241. $course_users = explode(',', $course_users);
  2242. $course_coaches = explode(',', $course_coaches);
  2243. // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
  2244. $addTeachersToSession = true;
  2245. if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
  2246. $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
  2247. }
  2248. // If any user provided for a course, use the users array.
  2249. if (empty($course_users)) {
  2250. if (!empty($userList)) {
  2251. SessionManager::subscribe_users_to_session_course($userList, $session_id, $course_code);
  2252. if ($debug) {
  2253. $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
  2254. $logger->addInfo($msg);
  2255. }
  2256. }
  2257. }
  2258. // Adding coaches to session course user
  2259. if (!empty($course_coaches)) {
  2260. $savedCoaches = array();
  2261. // only edit if add_teachers_to_sessions_courses is set.
  2262. if ($addTeachersToSession) {
  2263. // Adding course teachers as course session teachers.
  2264. $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
  2265. if (!empty($alreadyAddedTeachers)) {
  2266. $teachersToAdd = array();
  2267. foreach ($alreadyAddedTeachers as $user) {
  2268. $teachersToAdd[] = $user['username'];
  2269. }
  2270. $course_coaches = array_merge($course_coaches, $teachersToAdd);
  2271. }
  2272. foreach ($course_coaches as $course_coach) {
  2273. $coach_id = UserManager::get_user_id_from_username($course_coach);
  2274. if ($coach_id !== false) {
  2275. // Just insert new coaches
  2276. SessionManager::updateCoaches($session_id, $course_code, array($coach_id), false);
  2277. if ($debug) {
  2278. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  2279. }
  2280. $savedCoaches[] = $coach_id;
  2281. } else {
  2282. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  2283. }
  2284. }
  2285. }
  2286. // Custom courses/session coaches
  2287. $teacherToAdd = null;
  2288. if ($onlyAddFirstCoachOrTeacher == true) {
  2289. foreach ($course_coaches as $course_coach) {
  2290. $coach_id = UserManager::get_user_id_from_username($course_coach);
  2291. if ($coach_id !== false) {
  2292. $teacherToAdd = $coach_id;
  2293. break;
  2294. }
  2295. }
  2296. if (!empty($teacherToAdd)) {
  2297. SessionManager::updateCoaches($session_id, $course_code, array($teacherToAdd), true);
  2298. }
  2299. }
  2300. if ($removeAllTeachersFromCourse && !empty($teacherToAdd)) {
  2301. // Deleting all course teachers and adding the only coach as teacher.
  2302. $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
  2303. if (!empty($teacherList)) {
  2304. foreach ($teacherList as $teacher) {
  2305. CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
  2306. }
  2307. }
  2308. CourseManager::subscribe_user($teacherToAdd, $course_code, COURSEMANAGER);
  2309. }
  2310. // Continue default behaviour.
  2311. if ($onlyAddFirstCoachOrTeacher == false) {
  2312. // Checking one more time see BT#6449#note-149
  2313. $coaches = SessionManager::getCoachesByCourseSession($session_id, $course_code);
  2314. if (empty($coaches)) {
  2315. foreach ($course_coaches as $course_coach) {
  2316. $course_coach = trim($course_coach);
  2317. $coach_id = UserManager::get_user_id_from_username($course_coach);
  2318. if ($coach_id !== false) {
  2319. // Just insert new coaches
  2320. SessionManager::updateCoaches($session_id, $course_code, array($coach_id), false);
  2321. if ($debug) {
  2322. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  2323. }
  2324. $savedCoaches[] = $coach_id;
  2325. } else {
  2326. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  2327. }
  2328. }
  2329. }
  2330. }
  2331. }
  2332. // Adding Students, updating relationship "Session - Course - User".
  2333. if (!empty($course_users)) {
  2334. foreach ($course_users as $user) {
  2335. $user_id = UserManager::get_user_id_from_username($user);
  2336. if ($user_id !== false) {
  2337. SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $course_code);
  2338. if ($debug) {
  2339. $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  2340. }
  2341. } else {
  2342. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  2343. }
  2344. }
  2345. }
  2346. $course_info = CourseManager::get_course_information($course_code);
  2347. $inserted_in_course[$course_code] = $course_info['title'];
  2348. }
  2349. }
  2350. $access_url_id = api_get_current_access_url_id();
  2351. UrlManager::add_session_to_url($session_id, $access_url_id);
  2352. $sql_update_users = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
  2353. Database::query($sql_update_users);
  2354. }
  2355. }
  2356. return array(
  2357. 'error_message' => $error_message,
  2358. 'session_counter' => $session_counter,
  2359. 'session_list' => $sessionList
  2360. );
  2361. }
  2362. /**
  2363. * @param int $sessionId
  2364. * @param string $courseCode
  2365. * @return array
  2366. */
  2367. public static function getCoachesByCourseSession($sessionId, $courseCode)
  2368. {
  2369. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2370. $sessionId = intval($sessionId);
  2371. $courseCode = Database::escape_string($courseCode);
  2372. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$sessionId' AND course_code = '$courseCode' AND status = 2";
  2373. $result = Database::query($sql);
  2374. $coaches = array();
  2375. if (Database::num_rows($result) > 0) {
  2376. while ($row = Database::fetch_row($result)) {
  2377. $coaches[] = $row[0];
  2378. }
  2379. }
  2380. return $coaches;
  2381. }
  2382. /**
  2383. * Get all coaches added in the session - course relationship
  2384. * @param int $sessionId
  2385. * @return array
  2386. */
  2387. public static function getCoachesBySession($sessionId)
  2388. {
  2389. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2390. $sessionId = intval($sessionId);
  2391. $sql = "SELECT DISTINCT id_user FROM $table
  2392. WHERE id_session = '$sessionId' AND status = 2";
  2393. $result = Database::query($sql);
  2394. $coaches = array();
  2395. if (Database::num_rows($result) > 0) {
  2396. while ($row = Database::fetch_array($result)) {
  2397. $coaches[] = $row['id_user'];
  2398. }
  2399. }
  2400. return $coaches;
  2401. }
  2402. /**
  2403. * @param int $userId
  2404. * @return array
  2405. */
  2406. public static function getAllCoursesFromAllSessionFromDrh($userId)
  2407. {
  2408. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  2409. $coursesFromSession = array();
  2410. if (!empty($sessions)) {
  2411. foreach ($sessions as $session) {
  2412. $courseList = SessionManager::get_course_list_by_session_id($session['id']);
  2413. foreach ($courseList as $course) {
  2414. $coursesFromSession[] = $course['code'];
  2415. }
  2416. }
  2417. }
  2418. return $coursesFromSession;
  2419. }
  2420. /**
  2421. * @param string $status
  2422. * @param int $userId
  2423. * @param bool $getCount
  2424. * @param int $from
  2425. * @param int $numberItems
  2426. * @param int $column
  2427. * @param string $direction
  2428. * @param string $keyword
  2429. * @param string $active
  2430. * @param string $lastConnectionDate
  2431. * @param array $sessionIdList
  2432. * @param array $studentIdList
  2433. * @param int $filterByStatus
  2434. * @return array|int
  2435. */
  2436. public static function getAllUsersFromCoursesFromAllSessionFromStatus(
  2437. $status,
  2438. $userId,
  2439. $getCount = false,
  2440. $from = null,
  2441. $numberItems = null,
  2442. $column = 1,
  2443. $direction = 'asc',
  2444. $keyword = null,
  2445. $active = null,
  2446. $lastConnectionDate = null,
  2447. $sessionIdList = array(),
  2448. $studentIdList = array(),
  2449. $filterByStatus = null
  2450. ) {
  2451. $filterByStatus = intval($filterByStatus);
  2452. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2453. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2454. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2455. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2456. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2457. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2458. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2459. $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
  2460. $column = Database::escape_string($column);
  2461. $userId = intval($userId);
  2462. $limitCondition = null;
  2463. if (isset($from) && isset($numberItems)) {
  2464. $from = intval($from);
  2465. $numberItems = intval($numberItems);
  2466. $limitCondition = "LIMIT $from, $numberItems";
  2467. }
  2468. $urlId = api_get_current_access_url_id();
  2469. $sessionConditions = null;
  2470. $courseConditions = null;
  2471. $userConditions = null;
  2472. if (isset($active)) {
  2473. $active = intval($active);
  2474. $userConditions .= " AND active = $active";
  2475. }
  2476. switch ($status) {
  2477. case 'drh':
  2478. // Classic DRH
  2479. if (empty($studentIdList)) {
  2480. $studentListSql = UserManager::get_users_followed_by_drh(
  2481. $userId,
  2482. $filterByStatus,
  2483. true,
  2484. false
  2485. );
  2486. $studentIdList = array_keys($studentListSql);
  2487. $studentListSql = "'".implode("','", $studentIdList)."'";
  2488. } else {
  2489. $studentIdList = array_map('intval', $studentIdList);
  2490. $studentListSql = "'".implode("','", $studentIdList)."'";
  2491. }
  2492. if (!empty($studentListSql)) {
  2493. $userConditions = " AND u.user_id IN (".$studentListSql.") ";
  2494. }
  2495. break;
  2496. case 'drh_all':
  2497. // Show all by DRH
  2498. if (empty($sessionIdList)) {
  2499. $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
  2500. $userId,
  2501. null,
  2502. null,
  2503. false,
  2504. true,
  2505. true
  2506. );
  2507. } else {
  2508. $sessionIdList = array_map('intval', $sessionIdList);
  2509. $sessionsListSql = "'".implode("','", $sessionIdList)."'";
  2510. }
  2511. if (!empty($sessionsListSql)) {
  2512. $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
  2513. }
  2514. break;
  2515. case 'session_admin';
  2516. $sessionConditions = " AND s.id_coach = $userId ";
  2517. break;
  2518. case 'admin':
  2519. break;
  2520. case 'teacher':
  2521. $sessionConditions = " AND s.id_coach = $userId ";
  2522. // $statusConditions = " AND s.id_coach = $userId";
  2523. break;
  2524. }
  2525. $select = "SELECT DISTINCT u.* ";
  2526. $masterSelect = "SELECT DISTINCT * FROM ";
  2527. if ($getCount) {
  2528. $select = "SELECT DISTINCT u.user_id ";
  2529. $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
  2530. }
  2531. if (!empty($filterByStatus)) {
  2532. $userConditions .= " AND u.status = ".$filterByStatus;
  2533. }
  2534. if (!empty($lastConnectionDate)) {
  2535. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  2536. $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
  2537. }
  2538. if (!empty($keyword)) {
  2539. $keyword = Database::escape_string($keyword);
  2540. $userConditions .= " AND (
  2541. u.username LIKE '%$keyword%' OR
  2542. u.firstname LIKE '%$keyword%' OR
  2543. u.lastname LIKE '%$keyword%' OR
  2544. u.official_code LIKE '%$keyword%' OR
  2545. u.email LIKE '%$keyword%'
  2546. )";
  2547. }
  2548. $where = " WHERE
  2549. access_url_id = $urlId
  2550. $userConditions
  2551. ";
  2552. $sql = "$masterSelect (
  2553. ($select
  2554. FROM $tbl_session s
  2555. INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.id_session)
  2556. INNER JOIN $tbl_user u ON (u.user_id = su.id_user AND s.id = id_session)
  2557. INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
  2558. $where
  2559. $sessionConditions
  2560. )
  2561. UNION (
  2562. $select
  2563. FROM $tbl_course c
  2564. INNER JOIN $tbl_course_user cu ON (cu.course_code = c.code)
  2565. INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
  2566. INNER JOIN $tbl_course_rel_access_url url ON (url.course_code = c.code)
  2567. $where
  2568. $courseConditions
  2569. )
  2570. ) as t1
  2571. ";
  2572. if ($getCount) {
  2573. ///var_dump($sql);
  2574. $result = Database::query($sql);
  2575. $count = 0;
  2576. if (Database::num_rows($result)) {
  2577. $rows = Database::fetch_array($result);
  2578. $count = $rows['count'];
  2579. }
  2580. return $count;
  2581. }
  2582. if (!empty($column) && !empty($direction)) {
  2583. $column = str_replace('u.', '', $column);
  2584. $sql .= " ORDER BY $column $direction ";
  2585. }
  2586. $sql .= $limitCondition;
  2587. $result = Database::query($sql);
  2588. $result = Database::store_result($result);
  2589. return $result ;
  2590. }
  2591. /**
  2592. * @param int $sessionId
  2593. * @param string $courseCode
  2594. * @param array $coachList
  2595. * @param bool $deleteCoachesNotInList
  2596. */
  2597. public static function updateCoaches($sessionId, $courseCode, $coachList, $deleteCoachesNotInList = false)
  2598. {
  2599. $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseCode);
  2600. if (!empty($coachList)) {
  2601. foreach ($coachList as $userId) {
  2602. self::set_coach_to_course_session($userId, $sessionId, $courseCode);
  2603. }
  2604. }
  2605. if ($deleteCoachesNotInList) {
  2606. if (!empty($coachList)) {
  2607. $coachesToDelete = array_diff($currentCoaches, $coachList);
  2608. } else {
  2609. $coachesToDelete = $currentCoaches;
  2610. }
  2611. if (!empty($coachesToDelete)) {
  2612. foreach ($coachesToDelete as $userId) {
  2613. self::set_coach_to_course_session($userId, $sessionId, $courseCode, true);
  2614. }
  2615. }
  2616. }
  2617. }
  2618. /**
  2619. * @param array $sessions
  2620. * @param array $sessionsDestination
  2621. * @return string
  2622. */
  2623. public static function copyStudentsFromSession($sessions, $sessionsDestination)
  2624. {
  2625. $messages = array();
  2626. if (!empty($sessions)) {
  2627. foreach ($sessions as $sessionId) {
  2628. $sessionInfo = self::fetch($sessionId);
  2629. $userList = self::get_users_by_session($sessionId, 0);
  2630. if (!empty($userList)) {
  2631. $newUserList = array();
  2632. $userToString = null;
  2633. foreach ($userList as $userInfo) {
  2634. $newUserList[] = $userInfo['user_id'];
  2635. $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
  2636. }
  2637. if (!empty($sessionsDestination)) {
  2638. foreach ($sessionsDestination as $sessionDestinationId) {
  2639. $sessionDestinationInfo = self::fetch($sessionDestinationId);
  2640. $messages[] = Display::return_message(
  2641. sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
  2642. );
  2643. if ($sessionId == $sessionDestinationId) {
  2644. $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
  2645. continue;
  2646. }
  2647. $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
  2648. SessionManager::suscribe_users_to_session($sessionDestinationId, $newUserList, SESSION_VISIBLE_READ_ONLY, false);
  2649. }
  2650. } else {
  2651. $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
  2652. }
  2653. } else {
  2654. $messages[] = Display::return_message(get_lang('NoStudentsFoundForSession') . ' #' . $sessionInfo['name'], 'warning');
  2655. }
  2656. }
  2657. } else {
  2658. $messages[] = Display::return_message(get_lang('NoData'), 'warning');
  2659. }
  2660. return $messages;
  2661. }
  2662. /**
  2663. * Assign coaches of a session(s) as teachers to a given course (or courses)
  2664. * @param array A list of session IDs
  2665. * @param array A list of course IDs
  2666. * @return string
  2667. */
  2668. public static function copyCoachesFromSessionToCourse($sessions, $courses)
  2669. {
  2670. $coachesPerSession = array();
  2671. foreach ($sessions as $sessionId) {
  2672. $coaches = self::getCoachesBySession($sessionId);
  2673. $coachesPerSession[$sessionId] = $coaches;
  2674. }
  2675. $result = array();
  2676. if (!empty($courses)) {
  2677. foreach ($courses as $courseId) {
  2678. $courseInfo = api_get_course_info_by_id($courseId);
  2679. foreach ($coachesPerSession as $sessionId => $coachList) {
  2680. CourseManager::updateTeachers(
  2681. $courseInfo['code'], $coachList, false, false, false
  2682. );
  2683. $result[$courseInfo['code']][$sessionId] = $coachList;
  2684. }
  2685. }
  2686. }
  2687. $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
  2688. $htmlResult = null;
  2689. if (!empty($result)) {
  2690. foreach ($result as $courseCode => $data) {
  2691. $url = api_get_course_url($courseCode);
  2692. $htmlResult .= sprintf(get_lang('CoachesSubscribedAsATeacherInCourseX'), Display::url($courseCode, $url, array('target' => '_blank')));
  2693. foreach ($data as $sessionId => $coachList) {
  2694. $sessionInfo = self::fetch($sessionId);
  2695. $htmlResult .= '<br />';
  2696. $htmlResult .= Display::url(
  2697. get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
  2698. );
  2699. $teacherList = array();
  2700. foreach ($coachList as $coachId) {
  2701. $userInfo = api_get_user_info($coachId);
  2702. $teacherList[] = $userInfo['complete_name'];
  2703. }
  2704. if (!empty($teacherList)) {
  2705. $htmlResult .= implode(', ', $teacherList);
  2706. } else {
  2707. $htmlResult .= get_lang('NothingToAdd');
  2708. }
  2709. }
  2710. $htmlResult .= '<br />';
  2711. }
  2712. $htmlResult = Display::return_message($htmlResult, 'normal', false);
  2713. }
  2714. return $htmlResult;
  2715. }
  2716. /**
  2717. * @param string $keyword
  2718. * @param string $active
  2719. * @param string $lastConnectionDate
  2720. * @param array $sessionIdList
  2721. * @param array $studentIdList
  2722. * @param int $userStatus STUDENT|COURSEMANAGER constants
  2723. *
  2724. * @return array|int
  2725. */
  2726. public static function getCountUserTracking(
  2727. $keyword = null,
  2728. $active = null,
  2729. $lastConnectionDate = null,
  2730. $sessionIdList = array(),
  2731. $studentIdList = array(),
  2732. $filterUserStatus = null
  2733. ) {
  2734. $userId = api_get_user_id();
  2735. $drhLoaded = false;
  2736. if (api_is_drh()) {
  2737. if (api_drh_can_access_all_session_content()) {
  2738. $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
  2739. 'drh_all',
  2740. $userId,
  2741. true,
  2742. null,
  2743. null,
  2744. null,
  2745. null,
  2746. $keyword,
  2747. $active,
  2748. $lastConnectionDate,
  2749. $sessionIdList,
  2750. $studentIdList,
  2751. $filterUserStatus
  2752. );
  2753. $drhLoaded = true;
  2754. }
  2755. }
  2756. if ($drhLoaded == false) {
  2757. $count = UserManager::getUsersFollowedByUser(
  2758. $userId,
  2759. $filterUserStatus,
  2760. false,
  2761. false,
  2762. true,
  2763. null,
  2764. null,
  2765. null,
  2766. null,
  2767. $active,
  2768. $lastConnectionDate,
  2769. COURSEMANAGER,
  2770. $keyword
  2771. );
  2772. }
  2773. return $count;
  2774. }
  2775. /**
  2776. * Get teachers followed by a user
  2777. * @param int $userId
  2778. * @param int $active
  2779. * @param string $lastConnectionDate
  2780. * @param bool $getCount
  2781. * @param array $sessionIdList
  2782. * @return array|int
  2783. */
  2784. public static function getTeacherTracking(
  2785. $userId,
  2786. $active = 1,
  2787. $lastConnectionDate = null,
  2788. $getCount = false,
  2789. $sessionIdList = array()
  2790. ) {
  2791. $teacherResult = array();
  2792. if (api_is_drh() || api_is_platform_admin()) {
  2793. // Followed teachers by drh
  2794. if (api_drh_can_access_all_session_content()) {
  2795. if (empty($sessionIdList)) {
  2796. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  2797. $sessionIdList = array();
  2798. foreach ($sessions as $session) {
  2799. $sessionIdList[] = $session['id'];
  2800. }
  2801. }
  2802. $sessionIdList = array_map('intval', $sessionIdList);
  2803. $sessionToString = implode("', '", $sessionIdList);
  2804. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  2805. $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2806. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2807. // Select the teachers.
  2808. $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
  2809. INNER JOIN $sessionCourse src ON c.code = src.course_code
  2810. INNER JOIN $courseUser cu ON (cu.course_code = c.code)
  2811. WHERE src.id_session IN ('$sessionToString') AND cu.status = 1";
  2812. $result = Database::query($sql);
  2813. $teacherListId = array();
  2814. while($row = Database::fetch_array($result, 'ASSOC')) {
  2815. $teacherListId[$row['user_id']] = $row['user_id'];
  2816. }
  2817. } else {
  2818. $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
  2819. $teacherListId = array();
  2820. foreach ($teacherResult as $userInfo) {
  2821. $teacherListId[] = $userInfo['user_id'];
  2822. }
  2823. }
  2824. }
  2825. if (!empty($teacherListId)) {
  2826. $tableUser = Database::get_main_table(TABLE_MAIN_USER);
  2827. $select = "SELECT DISTINCT u.* ";
  2828. if ($getCount) {
  2829. $select = "SELECT count(DISTINCT(u.user_id)) as count";
  2830. }
  2831. $sql = "$select FROM $tableUser u";
  2832. if (!empty($lastConnectionDate)) {
  2833. $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  2834. //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
  2835. }
  2836. $active = intval($active);
  2837. $teacherListId = implode("','", $teacherListId);
  2838. $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
  2839. if (!empty($lastConnectionDate)) {
  2840. $lastConnectionDate = Database::escape_string($lastConnectionDate);
  2841. //$where .= " AND l.login_date <= '$lastConnectionDate' ";
  2842. }
  2843. $sql .= $where;
  2844. $result = Database::query($sql);
  2845. if (Database::num_rows($result)) {
  2846. if ($getCount) {
  2847. $row = Database::fetch_array($result);
  2848. return $row['count'];
  2849. } else {
  2850. return Database::store_result($result, 'ASSOC');
  2851. }
  2852. }
  2853. }
  2854. return 0;
  2855. }
  2856. /**
  2857. * Get the list of course tools that have to be dealt with in case of
  2858. * registering any course to a session
  2859. * @return array The list of tools to be dealt with (literal names)
  2860. */
  2861. public static function getCourseToolToBeManaged()
  2862. {
  2863. return array(
  2864. 'courseDescription',
  2865. 'courseIntroduction'
  2866. );
  2867. }
  2868. /**
  2869. * Calls the methods bound to each tool when a course is registered into a session
  2870. * @param int $sessionId
  2871. * @param int $courseId
  2872. * @return void
  2873. */
  2874. public static function installCourse($sessionId, $courseId)
  2875. {
  2876. return true;
  2877. $toolList = self::getCourseToolToBeManaged();
  2878. foreach ($toolList as $tool) {
  2879. $method = 'add' . $tool;
  2880. if (method_exists(get_class(), $method)) {
  2881. self::$method($sessionId, $courseId);
  2882. }
  2883. }
  2884. }
  2885. /**
  2886. * Calls the methods bound to each tool when a course is unregistered from
  2887. * a session
  2888. * @param int $sessionId
  2889. * @param int $courseId
  2890. */
  2891. public static function unInstallCourse($sessionId, $courseId)
  2892. {
  2893. return true;
  2894. $toolList = self::getCourseToolToBeManaged();
  2895. foreach ($toolList as $tool) {
  2896. $method = 'remove' . $tool;
  2897. if (method_exists(get_class(), $method)) {
  2898. self::$method($sessionId, $courseId);
  2899. }
  2900. }
  2901. }
  2902. /**
  2903. * @param int $sessionId
  2904. * @param int $courseId
  2905. */
  2906. public static function addCourseIntroduction($sessionId, $courseId)
  2907. {
  2908. // @todo create a tool intro lib
  2909. $sessionId = intval($sessionId);
  2910. $courseId = intval($courseId);
  2911. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  2912. $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
  2913. $result = Database::query($sql);
  2914. $result = Database::store_result($result, 'ASSOC');
  2915. if (!empty($result)) {
  2916. foreach ($result as $result) {
  2917. // @todo check if relation exits.
  2918. $result['session_id'] = $sessionId;
  2919. Database::insert($TBL_INTRODUCTION, $result);
  2920. }
  2921. }
  2922. }
  2923. /**
  2924. * @param int $sessionId
  2925. * @param int $courseId
  2926. */
  2927. public static function removeCourseIntroduction($sessionId, $courseId)
  2928. {
  2929. $sessionId = intval($sessionId);
  2930. $courseId = intval($courseId);
  2931. $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
  2932. $sql = "DELETE FROM $TBL_INTRODUCTION WHERE c_id = $courseId AND session_id = $sessionId";
  2933. Database::query($sql);
  2934. }
  2935. /**
  2936. * @param int $sessionId
  2937. * @param int $courseId
  2938. */
  2939. public static function addCourseDescription($sessionId, $courseId)
  2940. {
  2941. /* $description = new CourseDescription();
  2942. $descriptions = $description->get_descriptions($courseId);
  2943. foreach ($descriptions as $description) {
  2944. } */
  2945. }
  2946. /**
  2947. * @param int $sessionId
  2948. * @param int $courseId
  2949. */
  2950. public static function removeCourseDescription($sessionId, $courseId)
  2951. {
  2952. }
  2953. /**
  2954. * @param array $list format see self::importSessionDrhCSV()
  2955. * @param bool $sendEmail
  2956. * @param bool $removeOldRelationShips
  2957. * @return string
  2958. */
  2959. public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
  2960. {
  2961. if (!empty($userSessionList)) {
  2962. foreach ($userSessionList as $userId => $data) {
  2963. $sessionList = array();
  2964. foreach ($data['session_list'] as $sessionInfo) {
  2965. $sessionList[] = $sessionInfo['session_id'];
  2966. }
  2967. $userInfo = $data['user_info'];
  2968. self::suscribe_sessions_to_hr_manager($userInfo, $sessionList, $sendEmail, $removeOldRelationShips);
  2969. }
  2970. }
  2971. }
  2972. /**
  2973. * @param array $userSessionList format see self::importSessionDrhCSV()
  2974. */
  2975. public static function checkSubscribeDrhToSessionList($userSessionList)
  2976. {
  2977. $message = null;
  2978. if (!empty($userSessionList)) {
  2979. if (!empty($userSessionList)) {
  2980. foreach ($userSessionList as $userId => $data) {
  2981. $userInfo = $data['user_info'];
  2982. $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
  2983. if (!empty($sessionListSubscribed)) {
  2984. $sessionListSubscribed = array_keys($sessionListSubscribed);
  2985. }
  2986. $sessionList = array();
  2987. if (!empty($data['session_list'])) {
  2988. foreach ($data['session_list'] as $sessionInfo) {
  2989. if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
  2990. $sessionList[] = $sessionInfo['session_info']['name'];
  2991. }
  2992. }
  2993. }
  2994. $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
  2995. if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
  2996. $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
  2997. continue;
  2998. }
  2999. if (!empty($sessionList)) {
  3000. $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
  3001. $message .= implode(', ', $sessionList) . '<br /><br />';
  3002. } else {
  3003. $message .= get_lang('NoSessionProvided') . ' <br /><br />';
  3004. }
  3005. }
  3006. }
  3007. }
  3008. return $message;
  3009. }
  3010. /**
  3011. * @param string $file
  3012. * @param bool $sendEmail
  3013. * @param bool $removeOldRelationShips
  3014. */
  3015. public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
  3016. {
  3017. $list = Import::csv_reader($file);
  3018. if (!empty($list)) {
  3019. $userSessionList = array();
  3020. foreach ($list as $data) {
  3021. $userInfo = api_get_user_info_from_username($data['Username']);
  3022. $sessionInfo = self::get_session_by_name($data['SessionName']);
  3023. if (!empty($userInfo) && !empty($sessionInfo)) {
  3024. $userSessionList[$userInfo['user_id']]['session_list'][] = array(
  3025. 'session_id' => $sessionInfo['id'],
  3026. 'session_info' => $sessionInfo
  3027. );
  3028. $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
  3029. }
  3030. }
  3031. self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
  3032. return self::checkSubscribeDrhToSessionList($userSessionList);
  3033. }
  3034. }
  3035. /**
  3036. * Courses re-ordering in resume_session.php flag see BT#8316
  3037. */
  3038. public static function orderCourseIsEnabled()
  3039. {
  3040. global $_configuration;
  3041. if (isset($_configuration['session_course_ordering']) &&
  3042. $_configuration['session_course_ordering']
  3043. ) {
  3044. return true;
  3045. }
  3046. return false;
  3047. }
  3048. /**
  3049. * @param string $direction (up/down)
  3050. * @param int $sessionId
  3051. * @param string $courseCode
  3052. * @return bool
  3053. */
  3054. public static function move($direction, $sessionId, $courseCode)
  3055. {
  3056. if (!self::orderCourseIsEnabled()) {
  3057. return false;
  3058. }
  3059. $sessionId = intval($sessionId);
  3060. $courseCode = Database::escape_string($courseCode);
  3061. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3062. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  3063. $position = array();
  3064. $count = 0;
  3065. foreach ($courseList as $course) {
  3066. if ($course['position'] == '') {
  3067. $course['position'] = $count;
  3068. }
  3069. $position[$course['code']] = $course['position'];
  3070. // Saving current order.
  3071. $sql = "UPDATE $table SET position = $count
  3072. WHERE id_session = $sessionId AND course_code = '".$course['code']."'";
  3073. Database::query($sql);
  3074. $count++;
  3075. }
  3076. // Loading new positions.
  3077. $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
  3078. $found = false;
  3079. switch ($direction) {
  3080. case 'up':
  3081. $courseList = array_reverse($courseList);
  3082. break;
  3083. case 'down':
  3084. break;
  3085. }
  3086. foreach ($courseList as $course) {
  3087. if ($found) {
  3088. $nextId = $course['code'];
  3089. $nextOrder = $course['position'];
  3090. break;
  3091. }
  3092. if ($courseCode == $course['code']) {
  3093. $thisCourseCode = $course['code'];
  3094. $thisOrder = $course['position'];
  3095. $found = true;
  3096. }
  3097. }
  3098. $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
  3099. WHERE id_session = $sessionId AND course_code = '".$thisCourseCode."'";
  3100. $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
  3101. WHERE id_session = $sessionId AND course_code = '".$nextId."'";
  3102. Database::query($sql1);
  3103. Database::query($sql2);
  3104. return true;
  3105. }
  3106. /**
  3107. * @param int $sessionId
  3108. * @param string $courseCode
  3109. * @return bool
  3110. */
  3111. public static function moveUp($sessionId, $courseCode)
  3112. {
  3113. return self::move('up', $sessionId, $courseCode);
  3114. }
  3115. /**
  3116. * @param int $sessionId
  3117. * @param string $courseCode
  3118. * @return bool
  3119. */
  3120. public static function moveDown($sessionId, $courseCode)
  3121. {
  3122. return self::move('down', $sessionId, $courseCode);
  3123. }
  3124. /**
  3125. * Use the session duration to allow/block user access see BT#8317
  3126. * Needs these DB changes
  3127. * ALTER TABLE session ADD COLUMN duration int;
  3128. * ALTER TABLE session_rel_user ADD COLUMN duration int;
  3129. */
  3130. public static function durationPerUserIsEnabled()
  3131. {
  3132. global $_configuration;
  3133. if (isset($_configuration['session_duration_feature']) &&
  3134. $_configuration['session_duration_feature']
  3135. ) {
  3136. return true;
  3137. }
  3138. return false;
  3139. }
  3140. /**
  3141. * @param int $userId
  3142. * @param int $sessionId
  3143. * @param int $duration in days
  3144. * @return int
  3145. */
  3146. public static function getDayLeftInSession($sessionId, $userId, $duration)
  3147. {
  3148. $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
  3149. $sessionId,
  3150. $userId
  3151. );
  3152. $currentTime = time();
  3153. $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
  3154. $endDateInSeconds = $firstAccess + $duration*24*60*60;
  3155. $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
  3156. return $leftDays;
  3157. }
  3158. /**
  3159. * @param int $duration
  3160. * @param int $userId
  3161. * @param int $sessionId
  3162. */
  3163. public static function editUserSessionDuration($duration, $userId, $sessionId)
  3164. {
  3165. $duration = intval($duration);
  3166. $userId = intval($userId);
  3167. $sessionId = intval($sessionId);
  3168. if (empty($userId) || empty($sessionId)) {
  3169. return false;
  3170. }
  3171. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3172. $parameters = array('duration' => $duration);
  3173. $where = array('id_session = ? AND id_user = ? ' => array($sessionId, $userId));
  3174. Database::update($table, $parameters, $where);
  3175. }
  3176. /**
  3177. * @param int $userId
  3178. * @param int $sessionId
  3179. *
  3180. * @param return array
  3181. */
  3182. public static function getUserSession($userId, $sessionId)
  3183. {
  3184. $userId = intval($userId);
  3185. $sessionId = intval($sessionId);
  3186. if (empty($userId) || empty($sessionId)) {
  3187. return false;
  3188. }
  3189. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3190. $sql = "SELECT * FROM $table WHERE id_session =$sessionId AND id_user = $userId";
  3191. $result = Database::query($sql);
  3192. $values = array();
  3193. if (Database::num_rows($result)) {
  3194. $values = Database::fetch_array($result, 'ASSOC');
  3195. }
  3196. return $values;
  3197. }
  3198. /**
  3199. * @todo Add constatns in a DB table
  3200. */
  3201. static function get_session_change_user_reasons() {
  3202. return array (
  3203. self::SESSION_CHANGE_USER_REASON_SCHEDULE => get_lang('ScheduleChanged'),
  3204. self::SESSION_CHANGE_USER_REASON_CLASSROOM => get_lang('ClassRoomChanged'),
  3205. self::SESSION_CHANGE_USER_REASON_LOCATION => get_lang('LocationChanged'),
  3206. //self::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION => get_lang('EnrollmentAnnulation'),
  3207. );
  3208. }
  3209. static function get_session_change_user_reasons_variations() {
  3210. return array (
  3211. self::SESSION_CHANGE_USER_REASON_SCHEDULE => array(
  3212. 'default' => get_lang('ScheduleChanged'),
  3213. 'from' => get_lang('ScheduleChangedFrom'),
  3214. 'to' => get_lang('ScheduleChangedTo'),
  3215. ),
  3216. self::SESSION_CHANGE_USER_REASON_CLASSROOM => array(
  3217. 'default' => get_lang('ClassRoomChanged'),
  3218. 'from' => get_lang('ClassRoomChangedFrom'),
  3219. 'to' => get_lang('ClassRoomChangedTo'),
  3220. ),
  3221. self::SESSION_CHANGE_USER_REASON_LOCATION => array(
  3222. 'default' => get_lang('LocationChanged'),
  3223. 'from' => get_lang('LocationChangedFrom'),
  3224. 'to' => get_lang('LocationChangedTo'),
  3225. )
  3226. );
  3227. }
  3228. static function get_session_change_user_reasons_variations_by_id($id, $type) {
  3229. $reasons = self::get_session_change_user_reasons_variations();
  3230. $my_reason = isset($reasons[$id]) ? $reasons[$id] : null;
  3231. return isset($my_reason[$type]) ? $my_reason[$type] : null;
  3232. }
  3233. static function get_session_changed_reason_label($id, $type) {
  3234. switch ($type) {
  3235. case 'origin':
  3236. break;
  3237. case 'destination':
  3238. break;
  3239. }
  3240. }
  3241. /**
  3242. * Gets the reason name
  3243. * @param int reason id
  3244. */
  3245. static function get_session_change_user_reason($id) {
  3246. $reasons = self::get_session_change_user_reasons();
  3247. return isset($reasons[$id]) ? $reasons[$id] : null;
  3248. }
  3249. /**
  3250. * Changes the user from one session to another due a reason
  3251. * @params int user_id
  3252. * @params int old session id
  3253. * @params int new session id
  3254. * @params int see SessionManager::get_session_change_user_reasons()
  3255. */
  3256. static function change_user_session($user_id, $old_session_id, $new_session_id, $reason_id) {
  3257. if (!empty($user_id) && !empty($old_session_id) && !empty($new_session_id)) {
  3258. $user_id = intval($user_id);
  3259. $old_session_id = intval($old_session_id);
  3260. $new_session_id = intval($new_session_id);
  3261. $reason_id = intval($reason_id);
  3262. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3263. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3264. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3265. // Update number of users
  3266. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users - 1 WHERE id = '$old_session_id' ";
  3267. Database::query($update_sql);
  3268. // Get the list of courses related to this session
  3269. $course_list = SessionManager::get_course_list_by_session_id($old_session_id);
  3270. if (!empty($course_list)) {
  3271. foreach ($course_list as $course) {
  3272. $courseId = $course['id'];
  3273. // Delete user from course
  3274. //Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$session_id' AND course_code='$course_code' AND id_user='$user_id'");
  3275. //if (Database::affected_rows()) {
  3276. // Update number of users in this relation
  3277. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1 WHERE id_session = '$old_session_id' AND c_id='$courseId'";
  3278. Database::query($sql);
  3279. //}
  3280. }
  3281. }
  3282. //Deal with reasons
  3283. switch ($reason_id) {
  3284. case self::SESSION_CHANGE_USER_REASON_SCHEDULE:
  3285. case self::SESSION_CHANGE_USER_REASON_CLASSROOM:
  3286. case self::SESSION_CHANGE_USER_REASON_LOCATION:
  3287. //Adding to the new session
  3288. self::suscribe_users_to_session($new_session_id, array($user_id), null, false);
  3289. //Setting move_to if session was provided
  3290. $sql = "UPDATE $tbl_session_rel_user SET moved_to = '$new_session_id'
  3291. WHERE id_session = '$old_session_id' AND id_user ='$user_id'";
  3292. Database::query($sql);
  3293. break;
  3294. case self::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION:
  3295. UserManager::deactivate_users(array($user_id));
  3296. break;
  3297. }
  3298. $now = api_get_utc_datetime();
  3299. //Setting the moved_status
  3300. $sql = "UPDATE $tbl_session_rel_user SET moved_status = $reason_id, moved_at = '$now'
  3301. WHERE id_session = '$old_session_id' AND id_user ='$user_id'";
  3302. Database::query($sql);
  3303. return true;
  3304. }
  3305. return;
  3306. }
  3307. /**
  3308. * Get users inside a course session
  3309. */
  3310. static function get_users_in_course_session($courseId, $id_session, $sort, $direction, $from = null, $limit = null) {
  3311. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3312. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3313. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3314. $courseId = Database::escape_string($courseId);
  3315. $id_session = Database::escape_string($id_session);
  3316. $from = intval($from);
  3317. $limit = intval($limit);
  3318. $is_western_name_order = api_is_western_name_order();
  3319. //Select the number of users
  3320. $sql = " SELECT DISTINCT u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
  3321. FROM $tbl_session_rel_user sru INNER JOIN $tbl_user u ON (u.user_id=sru.id_user)
  3322. LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id = scru.id_user AND scru.c_id = '".$courseId."' )
  3323. WHERE sru.id_session = '$id_session' AND
  3324. sru.moved_to = 0 AND sru.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION." AND
  3325. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH;
  3326. $sql .= " ORDER BY $sort $direction ";
  3327. if (!empty($from) && !empty($limit)) {
  3328. $sql .= " LIMIT $from, $limit";
  3329. }
  3330. $result = Database::query($sql);
  3331. if (Database::num_rows($result)) {
  3332. return Database::store_result($result);
  3333. }
  3334. return false;
  3335. }
  3336. /**
  3337. * @param $courseId
  3338. * @param $id_session
  3339. * @return int|mixed
  3340. */
  3341. static function get_count_users_in_course_session($courseId, $id_session) {
  3342. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3343. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3344. //Select the number of users
  3345. $sql = " SELECT count(*) FROM $tbl_session_rel_user sru, $tbl_session_rel_course_rel_user srcru
  3346. WHERE srcru.id_user = sru.id_user AND
  3347. srcru.id_session = sru.id_session AND
  3348. srcru.c_id = '".Database::escape_string($courseId)."' AND
  3349. srcru.id_session = '".intval($id_session)."' AND
  3350. (sru.moved_to = 0 AND sru.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION.") AND
  3351. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH;
  3352. $result = Database::query($sql);
  3353. if (Database::num_rows($result)) {
  3354. return Database::result($result,0,0);
  3355. }
  3356. return 0;
  3357. }
  3358. /**
  3359. * Get the list of coaches (only user ids)
  3360. * @param string course_code
  3361. * @param in session_id
  3362. * @return array
  3363. */
  3364. static function get_session_course_coaches($courseId, $session_id)
  3365. {
  3366. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3367. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3368. // Get coachs of the courses in session
  3369. $sql = "SELECT user.user_id FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3370. WHERE session_rcru.id_user = user.user_id AND
  3371. session_rcru.id_session = '".intval($session_id)."' AND
  3372. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  3373. session_rcru.status=2";
  3374. $result = Database::query($sql);
  3375. return Database::store_result($result);
  3376. }
  3377. static function get_session_course_coaches_by_user($courseId, $session_id, $user_id)
  3378. {
  3379. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3380. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3381. // Get coachs of the courses in session
  3382. $sql = "SELECT user.user_id FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  3383. WHERE session_rcru.id_user = user.user_id AND
  3384. session_rcru.id_session = '".intval($session_id)."' AND
  3385. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  3386. session_rcru.status=2";
  3387. $result = Database::query($sql);
  3388. return Database::store_result($result);
  3389. }
  3390. static function get_session_course_coaches_to_string($courseId, $session_id)
  3391. {
  3392. $coaches = self::get_session_course_coaches($courseId, $session_id);
  3393. if (!empty($coaches)) {
  3394. $coach_list = array();
  3395. foreach ($coaches as $coach_info) {
  3396. $user_info = api_get_user_info($coach_info['user_id']);
  3397. $coach_list[] = $user_info['complete_name'];
  3398. }
  3399. if (!empty($coach_list)) {
  3400. return implode(', ', $coach_list);
  3401. }
  3402. }
  3403. return get_lang('None');
  3404. }
  3405. /**
  3406. * @param $id_session
  3407. * @param $courseId
  3408. */
  3409. static function delete_course_in_session($id_session, $courseId)
  3410. {
  3411. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3412. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3413. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3414. $id_session = intval($id_session);
  3415. $courseId = Database::escape_string($courseId);
  3416. if (!empty($id_session) && !empty($courseId)) {
  3417. $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND c_id = '$courseId'");
  3418. $nbr_affected_rows = Database::affected_rows($result);
  3419. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id = '$courseId'");
  3420. Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'");
  3421. }
  3422. }
  3423. static function get_session_rel_user_by_moved_to($session_id, $user_id) {
  3424. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  3425. $sql = "SELECT id_session, moved_status, moved_at FROM $tbl_session_rel_user WHERE id_user = $user_id AND moved_to = $session_id LIMIT 1";
  3426. $result = Database::query($sql);
  3427. if (Database::num_rows($result)) {
  3428. $result = Database::store_result($result,'ASSOC');
  3429. return $result[0];
  3430. }
  3431. return false;
  3432. }
  3433. static function get_coaches_by_keyword($tag) {
  3434. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3435. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
  3436. $select ="SELECT user.user_id, lastname, firstname, username ";
  3437. $sql = " $select FROM $tbl_user user WHERE status='1'";
  3438. $tag = Database::escape_string($tag);
  3439. $where_condition = array();
  3440. if (!empty($tag)) {
  3441. $condition = ' LIKE "%'.$tag.'%"';
  3442. $where_condition = array( "firstname $condition",
  3443. "lastname $condition",
  3444. "username $condition"
  3445. );
  3446. $where_condition = ' AND ('.implode(' OR ', $where_condition).') ';
  3447. }
  3448. if (api_is_multiple_url_enabled()) {
  3449. $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  3450. $access_url_id = api_get_current_access_url_id();
  3451. if ($access_url_id != -1){
  3452. $sql = $select.' FROM '.$tbl_user.' user
  3453. INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
  3454. WHERE access_url_id = '.$access_url_id.' AND status = 1';
  3455. }
  3456. }
  3457. $sql .= $where_condition.$order_clause;
  3458. $result = Database::query($sql);
  3459. return Database::store_result($result, 'ASSOC');
  3460. }
  3461. /**
  3462. * Returns a human readable string
  3463. * @params array An array with all the session dates
  3464. * @return string
  3465. */
  3466. static function parse_session_dates($session_info)
  3467. {
  3468. //This will clean the variables if 0000-00-00 00:00:00 the variable will be empty
  3469. $start_date = null;
  3470. $end_date = null;
  3471. if (isset($session_info['display_start_date'])) {
  3472. $start_date = api_get_local_time($session_info['display_start_date'], null, null, true);
  3473. }
  3474. if (isset($session_info['display_end_date'])) {
  3475. $end_date = api_get_local_time($session_info['display_end_date'], null, null, true);
  3476. }
  3477. $msg_date = null;
  3478. if (!empty($start_date) && !empty($end_date)) {
  3479. //$msg_date = get_lang('From').' '.$start_date.' '.get_lang('To').' '.$end_date;
  3480. $msg_date = sprintf(get_lang('FromDateXToDateY'), $start_date, $end_date);
  3481. } else {
  3482. if (!empty($start_date)) {
  3483. $msg_date = get_lang('From').' '.$start_date;
  3484. }
  3485. if (!empty($end_date)) {
  3486. $msg_date = get_lang('Until').' '.$end_date;
  3487. }
  3488. }
  3489. return $msg_date;
  3490. }
  3491. public static function get_session_columns($list_type = 'simple') {
  3492. //Column config
  3493. $operators = array('cn', 'nc');
  3494. $date_operators = array('gt', 'ge', 'lt', 'le');
  3495. switch ($list_type) {
  3496. case 'simple':
  3497. $columns = array(
  3498. get_lang('Name'),
  3499. get_lang('SessionDisplayStartDate'),
  3500. get_lang('SessionDisplayEndDate'),
  3501. //get_lang('SessionCategoryName'),
  3502. //get_lang('Coach'),
  3503. //get_lang('Status'),
  3504. get_lang('Visibility'),
  3505. //get_lang('CourseTitle'),
  3506. );
  3507. $column_model = array (
  3508. array('name'=>'name', 'index'=>'name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  3509. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  3510. array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
  3511. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  3512. );
  3513. break;
  3514. case 'complete':
  3515. $columns = array(
  3516. get_lang('Name'),
  3517. get_lang('SessionDisplayStartDate'),
  3518. get_lang('SessionDisplayEndDate'),
  3519. get_lang('Coach'),
  3520. get_lang('Status'),
  3521. get_lang('Visibility'),
  3522. get_lang('CourseTitle'),
  3523. );
  3524. $column_model = array (
  3525. array('name'=>'name', 'index'=>'name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  3526. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  3527. array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
  3528. array('name'=>'coach_name', 'index'=>'coach_name', 'width'=>'70', 'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
  3529. array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25', 'align'=>'left', 'search' => 'true', 'stype'=>'select',
  3530. //for the bottom bar
  3531. 'searchoptions' => array(
  3532. 'defaultValue' => '1',
  3533. 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  3534. //for the top bar
  3535. 'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))
  3536. ),
  3537. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  3538. array('name'=>'course_title', 'index'=>'course_title', 'width'=>'50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  3539. );
  3540. break;
  3541. }
  3542. // Inject extra session fields
  3543. $session_field = new SessionField();
  3544. $rules = $session_field->getRules($columns, $column_model);
  3545. $column_model[] = array('name'=>'actions', 'index'=>'actions', 'width'=>'80', 'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false');
  3546. $columns[] = get_lang('Actions');
  3547. foreach ($column_model as $col_model) {
  3548. $simple_column_name[] = $col_model['name'];
  3549. }
  3550. $return_array = array(
  3551. 'columns' => $columns,
  3552. 'column_model' => $column_model,
  3553. 'rules' => $rules,
  3554. 'simple_column_name' => $simple_column_name
  3555. );
  3556. return $return_array;
  3557. }
  3558. /**
  3559. * @param int $categoryId
  3560. * @return array
  3561. */
  3562. static function getSessionsByCategory($categoryId)
  3563. {
  3564. $categoryId = intval($categoryId);
  3565. $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
  3566. $sql = "select * FROM $tableSession WHERE session_category_id = $categoryId";
  3567. $result = Database::query($sql);
  3568. return Database::store_result($result);
  3569. }
  3570. }