sessionmanager.lib.php 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the session library for Chamilo.
  5. * All main sessions functions should be placed here.
  6. * This class provides methods for sessions management.
  7. * Include/require it in your code to use its features.
  8. * @package chamilo.library
  9. */
  10. /**
  11. * The SessionManager class manages all the Chamilo sessions (as in course
  12. * groups).
  13. * @package chamilo.library.session
  14. */
  15. class SessionManager
  16. {
  17. //See BT#4871
  18. CONST SESSION_CHANGE_USER_REASON_SCHEDULE = 1;
  19. CONST SESSION_CHANGE_USER_REASON_CLASSROOM = 2;
  20. CONST SESSION_CHANGE_USER_REASON_LOCATION = 3;
  21. CONST SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION = 4;
  22. CONST DEFAULT_VISIBILITY = 4; //SESSION_AVAILABLE
  23. /**
  24. * Fetches a session from the database
  25. * @param int Session ID
  26. * @return array Session details
  27. * @assert (-1) === array()
  28. */
  29. public static function fetch($id) {
  30. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  31. if ($id != strval(intval($id))) { return array(); }
  32. $s = "SELECT * FROM $t WHERE id = $id";
  33. $r = Database::query($s);
  34. if (Database::num_rows($r) != 1) { return array(); }
  35. return Database::fetch_array($r,'ASSOC');
  36. }
  37. /**
  38. * Creates a session
  39. * @param array Fields to use in the creation of the session
  40. * @param boolean Whether to allow for same-name sessions or not.
  41. * @assert (array()) === false
  42. */
  43. public static function add($params, $allow_homonyms=false) {
  44. global $_configuration;
  45. //just in case
  46. if (isset($params['id'])) {
  47. unset($params['id']);
  48. }
  49. //Check portal limits
  50. $access_url_id = 1;
  51. if (api_is_multiple_url_enabled()) {
  52. $access_url_id = api_get_current_access_url_id();
  53. }
  54. if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_sessions']) && $_configuration[$access_url_id]['hosting_limit_sessions'] > 0) {
  55. $num = self::count_sessions();
  56. if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
  57. return get_lang('PortalSessionsLimitReached');
  58. }
  59. }
  60. if (!$allow_homonyms) {
  61. $my_session_result = SessionManager::get_session_by_name($params['name']);
  62. $session_id = null;
  63. if ($my_session_result == false) {
  64. $session_model = new SessionModel();
  65. $session_id = $session_model->save($params);
  66. } else {
  67. error_log('Session already exists with name: '.$params['name']." session_id: ".$my_session_result['id']);
  68. }
  69. } else {
  70. //with the allow_homonyms option, two sessions can share names
  71. $session_model = new SessionModel();
  72. $session_id = $session_model->save($params);
  73. }
  74. if (!empty($session_id)) {
  75. /*
  76. Sends a message to the user_id = 1
  77. $user_info = api_get_user_info(1);
  78. $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
  79. $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
  80. $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
  81. api_mail_html($complete_name, $user_info['email'], $subject, $message);
  82. *
  83. */
  84. //Saving extra fields
  85. $session_field_value = new SessionFieldValue();
  86. $params['session_id'] = $session_id;
  87. $session_field_value->save_field_values($params);
  88. //Adding to the correct URL
  89. $access_url_id = api_get_current_access_url_id();
  90. UrlManager::add_session_to_url($session_id, $access_url_id);
  91. // Add event to system log
  92. event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), api_get_user_id());
  93. if (isset($params['course_code'])) {
  94. $courseInfo = api_get_course_info($params['course_code']);
  95. self::add_courses_to_session($session_id, array($courseInfo['real_id']));
  96. //Update default course gradebook to the session if exists
  97. $create_gradebook_evaluation = isset($params['create_gradebook_evaluation']) ? $params['create_gradebook_evaluation'] : false;
  98. if ($create_gradebook_evaluation) {
  99. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
  100. $category_id = create_default_course_gradebook($params['course_code'], false, $session_id);
  101. /*
  102. if ($category_id && isset($params['gradebook_params'])) {
  103. $eval = new Evaluation();
  104. $eval->set_name($params['gradebook_params']['name']);
  105. $eval->set_user_id($params['gradebook_params']['user_id']);
  106. $eval->set_course_code($params['course_code']);
  107. $eval->set_category_id($category_id);
  108. $eval->set_weight($params['gradebook_params']['weight']);
  109. $eval->set_max($params['gradebook_params']['max']);
  110. $eval->set_visible(0);
  111. $eval->add();
  112. }*/
  113. /*$tbl_gradebook_category = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
  114. $sql = "SELECT id FROM $tbl_gradebook_category WHERE course_code = {$params['course_code']} AND session_id = 0 LIMIT 1";
  115. $result = Database::query($sql);
  116. if (Database::num_rows($result)) {
  117. $gradebook_data = Database::fetch_array($result, 'ASSOC');
  118. if (!empty($gradebook_data)) {
  119. $sql = "UPDATE SET session_id = $session_id WHERE id = {$gradebook_data['id']}";
  120. Database::query($sql);
  121. }
  122. }*/
  123. }
  124. }
  125. } else {
  126. if (isset($params['return_item_if_already_exists']) && $params['return_item_if_already_exists']) {
  127. $my_session_result = SessionManager::get_session_by_name($params['name']);
  128. $session_id = $my_session_result['id'];
  129. }
  130. }
  131. return $session_id;
  132. }
  133. /**
  134. * Updates a session with the given array of field values
  135. * @param array An array of fields values
  136. * @return void
  137. * @assert (null) === false
  138. */
  139. public static function update($params) {
  140. if (empty($params) || count($params)<1) {
  141. return false;
  142. }
  143. $session_model = new SessionModel();
  144. $session_model->update($params);
  145. if (!empty($params['id'])) {
  146. $session_field_value = new SessionFieldValue();
  147. $params['session_id'] = $params['id'];
  148. unset($params['id']);
  149. $session_field_value->save_field_values($params);
  150. }
  151. }
  152. /**
  153. * Checks whether a session already exists with the given name (used in
  154. * add() to avoid homonym sessions)
  155. * @param string A session name
  156. * @assert ('') === false
  157. */
  158. function session_name_exists($session_name) {
  159. $session_name = Database::escape_string($session_name);
  160. $result = Database::fetch_array(Database::query("SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." WHERE name = '$session_name' "));
  161. return $result['count'] > 0;
  162. }
  163. /**
  164. * Gets the admin session list callback of the session/session_list.php page
  165. * @param array order and limit keys
  166. * @param boolean Whether to get all the results or only the count
  167. * @return mixed Integer for number of rows, or array of results
  168. * @assert (array(),true) !== false
  169. */
  170. public static function get_sessions_admin($options = array(), $get_count = false)
  171. {
  172. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  173. $where = 'WHERE 1 = 1 ';
  174. $user_id = api_get_user_id();
  175. if (!api_is_platform_admin()) {
  176. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
  177. $where .=" AND s.session_admin_id = $user_id ";
  178. }
  179. }
  180. if (!api_is_platform_admin() && api_is_teacher() && api_get_setting('allow_teachers_to_create_sessions') == 'true') {
  181. $where .=" AND s.id_coach = $user_id ";
  182. }
  183. $extra_field = new ExtraField('session');
  184. $conditions = $extra_field->parseConditions($options);
  185. $inject_joins = $conditions['inject_joins'];
  186. $where .= $conditions['where'];
  187. $inject_where = $conditions['inject_where'];
  188. $inject_extra_fields = $conditions['inject_extra_fields'];
  189. $order = $conditions['order'];
  190. $limit = $conditions['limit'];
  191. if ($get_count == true) {
  192. $select = " SELECT count(*) as total_rows";
  193. } else {
  194. $select =
  195. "SELECT DISTINCT ".
  196. " s.name, ".
  197. " s.display_start_date, ".
  198. " s.display_end_date, ".
  199. " access_start_date, ".
  200. " access_end_date, ".
  201. " s.visibility, ".
  202. " $inject_extra_fields ".
  203. " s.id ";
  204. }
  205. $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
  206. if (api_is_multiple_url_enabled()) {
  207. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  208. $access_url_id = api_get_current_access_url_id();
  209. if ($access_url_id != -1) {
  210. $where.= " AND ar.access_url_id = $access_url_id ";
  211. $query = "$select FROM $tbl_session s $inject_joins INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id) $where";
  212. }
  213. }
  214. $query .= $order;
  215. $query .= $limit;
  216. $result = Database::query($query);
  217. $formatted_sessions = array();
  218. if (Database::num_rows($result)) {
  219. $sessions = Database::store_result($result, 'ASSOC');
  220. if ($get_count) {
  221. return $sessions[0]['total_rows'];
  222. }
  223. foreach ($sessions as $session) {
  224. $session_id = $session['id'];
  225. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  226. if (isset($session['session_active']) && $session['session_active'] == 1) {
  227. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  228. } else {
  229. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  230. }
  231. $session = self::convert_dates_to_local($session);
  232. switch ($session['visibility']) {
  233. case SESSION_VISIBLE_READ_ONLY: //1
  234. $session['visibility'] = get_lang('ReadOnly');
  235. break;
  236. case SESSION_VISIBLE: //2
  237. case SESSION_AVAILABLE: //4
  238. $session['visibility'] = get_lang('Visible');
  239. break;
  240. case SESSION_INVISIBLE: //3
  241. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  242. break;
  243. }
  244. // Cleaning double selects.
  245. foreach ($session as $key => &$value) {
  246. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  247. $options = explode('::', $value);
  248. }
  249. $original_key = $key;
  250. if (strpos($key, '_second') === false) {
  251. } else {
  252. $key = str_replace('_second', '', $key);
  253. }
  254. if (isset($options_by_double[$key])) {
  255. if (isset($options[0])) {
  256. if (isset($options_by_double[$key][$options[0]])) {
  257. if (strpos($original_key, '_second') === false) {
  258. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  259. } else {
  260. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  261. }
  262. }
  263. }
  264. }
  265. }
  266. $formatted_sessions[$session_id] = $session;
  267. }
  268. }
  269. return $formatted_sessions;
  270. }
  271. /**
  272. * Gets the number of rows in the session table filtered through the given
  273. * array of parameters
  274. * @param array Array of options/filters/keys
  275. * @return integer The number of rows, or false on wrong param
  276. * @assert ('a') === false
  277. */
  278. static function get_count_admin_complete($options = array()) {
  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. $where = 'WHERE 1 = 1 ';
  286. $user_id = api_get_user_id();
  287. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_see_all_sessions') == 'false') {
  288. $where.=" WHERE s.session_admin_id = $user_id ";
  289. }
  290. if (!empty($options['where'])) {
  291. if (!empty($options['extra'])) {
  292. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  293. $options['where'] = str_replace('AND', 'OR', $options['where']);
  294. foreach ($options['extra'] as $extra) {
  295. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  296. }
  297. }
  298. $where .= ' AND '.$options['where'];
  299. }
  300. $query_rows = "SELECT count(*) as total_rows
  301. FROM $tbl_session s
  302. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  303. INNER JOIN $tbl_user u ON s.id_coach = u.user_id $where ";
  304. if (api_is_multiple_url_enabled()) {
  305. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  306. $access_url_id = api_get_current_access_url_id();
  307. if ($access_url_id != -1) {
  308. $where.= " AND ar.access_url_id = $access_url_id ";
  309. $query_rows = "SELECT count(*) as total_rows
  310. FROM $tbl_session s
  311. LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
  312. INNER JOIN $tbl_user u ON s.id_coach = u.user_id
  313. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id $where ";
  314. }
  315. }
  316. $result_rows = Database::query($query_rows);
  317. $recorset = Database::fetch_array($result_rows);
  318. $num = $recorset['total_rows'];
  319. return $num;
  320. }
  321. /**
  322. * Gets the admin session list callback of the session/session_list.php
  323. * page with all user/details in the right fomat
  324. * @param array order and limit keys
  325. * @result array Array of rows results
  326. * @asset ('a') === false
  327. */
  328. public static function get_sessions_admin_complete($options = array()) {
  329. if (!is_array($options)) {
  330. return false;
  331. }
  332. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  333. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  334. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  335. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  336. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  337. $tbl_session_field_values = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  338. $tbl_session_field_options = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_OPTIONS);
  339. $where = 'WHERE 1 = 1 ';
  340. $user_id = api_get_user_id();
  341. if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
  342. $where.=" AND s.session_admin_id = $user_id ";
  343. }
  344. $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
  345. if (api_is_western_name_order()) {
  346. $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
  347. }
  348. $today = api_get_utc_datetime();
  349. $inject_extra_fields = null;
  350. $extra_fields = array();
  351. $extra_fields_info = array();
  352. //for now only sessions
  353. $extra_field = new ExtraField('session');
  354. $double_fields = array();
  355. $extra_field_option = new ExtraFieldOption('session');
  356. if (isset($options['extra'])) {
  357. $extra_fields = $options['extra'];
  358. if (!empty($extra_fields)) {
  359. foreach ($extra_fields as $extra) {
  360. $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
  361. if (isset($extra_fields_info[$extra['id']])) {
  362. $info = $extra_fields_info[$extra['id']];
  363. } else {
  364. $info = $extra_field->get($extra['id']);
  365. $extra_fields_info[$extra['id']] = $info;
  366. }
  367. if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
  368. $double_fields[$info['id']] = $info;
  369. }
  370. }
  371. }
  372. }
  373. $options_by_double = array();
  374. foreach ($double_fields as $double) {
  375. $my_options = $extra_field_option->get_field_options_by_field($double['id'], true);
  376. $options_by_double['extra_'.$double['field_variable']] = $my_options;
  377. }
  378. //sc.name as category_name,
  379. $select = "
  380. SELECT * FROM (
  381. SELECT DISTINCT
  382. IF (
  383. (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
  384. (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
  385. (s.access_start_date <= '$today' AND '0000-00-00 00:00:00' = s.access_end_date) OR
  386. ('$today' < s.access_end_date AND '0000-00-00 00:00:00' = s.access_start_date)
  387. , 1, 0) as session_active,
  388. s.name,
  389. s.nbr_courses,
  390. s.nbr_users,
  391. s.display_start_date,
  392. s.display_end_date,
  393. $coach_name,
  394. access_start_date,
  395. access_end_date,
  396. s.visibility,
  397. u.user_id,
  398. $inject_extra_fields
  399. c.title as course_title,
  400. s.id ";
  401. if (!empty($options['where'])) {
  402. if (!empty($options['extra'])) {
  403. $options['where'] = str_replace(' 1 = 1 AND', '', $options['where']);
  404. $options['where'] = str_replace('AND', 'OR', $options['where']);
  405. foreach ($options['extra'] as $extra) {
  406. $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
  407. }
  408. }
  409. $options['where'] = str_replace('course_title', 'c.title', $options['where']);
  410. $where .= ' AND '.$options['where'];
  411. }
  412. if (!empty($options['limit'])) {
  413. $where .= " LIMIT ".$options['limit'];
  414. }
  415. $query = "$select FROM $tbl_session s
  416. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  417. INNER JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
  418. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  419. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  420. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  421. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id) ".
  422. $where;
  423. if (api_is_multiple_url_enabled()) {
  424. $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  425. $access_url_id = api_get_current_access_url_id();
  426. if ($access_url_id != -1) {
  427. $where.= " AND ar.access_url_id = $access_url_id ";
  428. $query = "$select
  429. FROM $tbl_session s
  430. LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
  431. LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
  432. LEFT JOIN $tbl_course c ON (src.c_id = c.id)
  433. LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
  434. INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
  435. INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
  436. $where";
  437. }
  438. }
  439. $query .= ") AS session_table";
  440. if (!empty($options['order'])) {
  441. $query .= " ORDER BY ".$options['order'];
  442. }
  443. //error_log($query);
  444. // echo $query;
  445. $result = Database::query($query);
  446. $formatted_sessions = array();
  447. if (Database::num_rows($result)) {
  448. $sessions = Database::store_result($result, 'ASSOC');
  449. foreach ($sessions as $session) {
  450. $session_id = $session['id'];
  451. $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
  452. $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
  453. if ($session['session_active'] == 1) {
  454. $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
  455. } else {
  456. $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
  457. }
  458. $session = self::convert_dates_to_local($session);
  459. switch ($session['visibility']) {
  460. case SESSION_VISIBLE_READ_ONLY: //1
  461. $session['visibility'] = get_lang('ReadOnly');
  462. break;
  463. case SESSION_VISIBLE: //2
  464. case SESSION_AVAILABLE: //4
  465. $session['visibility'] = get_lang('Visible');
  466. break;
  467. case SESSION_INVISIBLE: //3
  468. $session['visibility'] = api_ucfirst(get_lang('Invisible'));
  469. break;
  470. }
  471. //Cleaning double selects
  472. foreach ($session as $key => &$value) {
  473. if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
  474. $options = explode('::', $value);
  475. }
  476. $original_key = $key;
  477. if (strpos($key, '_second') === false) {
  478. } else {
  479. $key = str_replace('_second', '', $key);
  480. }
  481. if (isset($options_by_double[$key])) {
  482. if (isset($options[0])) {
  483. if (isset($options_by_double[$key][$options[0]])) {
  484. if (strpos($original_key, '_second') === false) {
  485. $value = $options_by_double[$key][$options[0]]['option_display_text'];
  486. } else {
  487. $value = $options_by_double[$key][$options[1]]['option_display_text'];
  488. }
  489. }
  490. }
  491. }
  492. }
  493. //Magic filter
  494. if (isset($formatted_sessions[$session_id])) {
  495. $formatted_sessions[$session_id] = self::compare_arrays_to_merge($formatted_sessions[$session_id], $session);
  496. } else {
  497. $formatted_sessions[$session_id] = $session;
  498. }
  499. }
  500. }
  501. return $formatted_sessions;
  502. }
  503. /**
  504. *
  505. */
  506. static function compare_arrays_to_merge($array1, $array2)
  507. {
  508. if (empty($array2)) {
  509. return $array1;
  510. }
  511. foreach ($array1 as $key => $item) {
  512. if (!isset($array1[$key])) {
  513. //My string is empty try the other one
  514. if (isset($array2[$key]) && !empty($array2[$key])) {
  515. $array1[$key] = $array2[$key];
  516. }
  517. }
  518. }
  519. return $array1;
  520. }
  521. /**
  522. * Converts all dates sent through the param array (given form) to correct
  523. * dates with timezones
  524. * @param array The dates
  525. * @return array The same array, with times converted
  526. * @assert ('a') === false
  527. */
  528. static function convert_dates_to_local($params) {
  529. if (!is_array($params)) {
  530. return false;
  531. }
  532. $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
  533. $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
  534. $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
  535. $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
  536. $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
  537. $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
  538. return $params;
  539. }
  540. /**
  541. * Creates a new course code based in given code
  542. *
  543. * @param string wanted code
  544. * <code>
  545. * $wanted_code = 'sess' if there are names like sess, sess1, sess2 in the
  546. * database already, the function will return: sess3
  547. * if the session name doesn't exist in the DB the same name is returned
  548. * </code>
  549. * @return string wanted unused code
  550. */
  551. function generate_nice_next_session_name($session_name) {
  552. $session_name_ok = !self::session_name_exists($session_name);
  553. if (!$session_name_ok) {
  554. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  555. $session_name = Database::escape_string($session_name);
  556. $sql = "SELECT count(*) as count FROM $table WHERE name LIKE '$session_name%'";
  557. $result = Database::query($sql);
  558. if (Database::num_rows($result) > 0 ) {
  559. $row = Database::fetch_array($result);
  560. $count = $row['count'] + 1;
  561. $session_name = $session_name.'_'.$count;
  562. $result = self::session_name_exists($session_name);
  563. if (!$result) {
  564. return $session_name;
  565. }
  566. }
  567. return false;
  568. }
  569. return $session_name;
  570. }
  571. /**
  572. * Delete session
  573. * @author Carlos Vargas from existing code
  574. * @param array id_checked
  575. * @param boolean optional, true if the function is called by a webservice, false otherwise.
  576. * @return void Nothing, or false on error
  577. * The parameters is a array to delete sessions
  578. **/
  579. public static function delete_session ($id_checked, $from_ws = false) {
  580. $tbl_session= Database::get_main_table(TABLE_MAIN_SESSION);
  581. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  582. $tbl_session_rel_course_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  583. $tbl_session_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_USER);
  584. $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  585. global $_user;
  586. if(is_array($id_checked)) {
  587. $id_checked = Database::escape_string(implode(',',$id_checked));
  588. } else {
  589. $id_checked = intval($id_checked);
  590. }
  591. if (!api_is_platform_admin() && !$from_ws) {
  592. $sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
  593. $rs = Database::query($sql);
  594. if (Database::result($rs,0,0)!=$_user['user_id']) {
  595. api_not_allowed(true);
  596. }
  597. }
  598. Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
  599. Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
  600. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
  601. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
  602. Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
  603. // delete extra session fields
  604. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  605. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  606. // Delete extra fields from session where field variable is "SECCION"
  607. $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' ";
  608. $rs_field = Database::query($sql);
  609. $field_id = 0;
  610. if (Database::num_rows($rs_field) == 1) {
  611. $row_field = Database::fetch_row($rs_field);
  612. $field_id = $row_field[0];
  613. $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
  614. $rs_delete_sfv = Database::query($sql_delete_sfv);
  615. }
  616. $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
  617. $rs_field_id = Database::query($sql);
  618. if (Database::num_rows($rs_field_id) == 0) {
  619. $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
  620. $rs_delete_sf = Database::query($sql_delete_sf);
  621. }
  622. /*
  623. $sql = "SELECT distinct field_id FROM $t_sfv WHERE session_id = '$id_checked'";
  624. $res_field_ids = @Database::query($sql);
  625. if (Database::num_rows($res_field_ids) > 0) {
  626. while($row_field_id = Database::fetch_row($res_field_ids)){
  627. $field_ids[] = $row_field_id[0];
  628. }
  629. }
  630. //delete from table_session_field_value from a given session id
  631. $sql_session_field_value = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
  632. @Database::query($sql_session_field_value);
  633. $sql = "SELECT distinct field_id FROM $t_sfv";
  634. $res_field_all_ids = @Database::query($sql);
  635. if (Database::num_rows($res_field_all_ids) > 0) {
  636. while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
  637. $field_all_ids[] = $row_field_all_id[0];
  638. }
  639. }
  640. if (count($field_ids) > 0 && count($field_all_ids) > 0) {
  641. foreach($field_ids as $field_id) {
  642. // check if field id is used into table field value
  643. if (in_array($field_id,$field_all_ids)) {
  644. continue;
  645. } else {
  646. $sql_session_field = "DELETE FROM $t_sf WHERE id = '$field_id'";
  647. Database::query($sql_session_field);
  648. }
  649. }
  650. }
  651. */
  652. // Add event to system log
  653. $user_id = api_get_user_id();
  654. event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $user_id);
  655. }
  656. /**
  657. * Subscribes users (students) to the given session and optionally (default) unsubscribes previous users
  658. * @author Carlos Vargas from existing code
  659. * @param integer Session ID
  660. * @param array List of user IDs
  661. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  662. * @return void Nothing, or false on error
  663. **/
  664. public static function suscribe_users_to_session($id_session, $user_list, $session_visibility = SESSION_VISIBLE_READ_ONLY, $empty_users = true, $send_email = false) {
  665. if ($id_session!= strval(intval($id_session))) return false;
  666. foreach ($user_list as $intUser){
  667. if ($intUser!= strval(intval($intUser))) return false;
  668. }
  669. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  670. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  671. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  672. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  673. $session_info = api_get_session_info($id_session);
  674. if ($session_info) {
  675. $session_name = $session_info['name'];
  676. } else {
  677. return false;
  678. }
  679. //from function parameter
  680. if (empty($session_visibility)) {
  681. $session_visibility = $session_info['visibility']; //loaded from DB
  682. //default status loaded if empty
  683. if (empty($session_visibility))
  684. $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
  685. } else {
  686. if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
  687. $session_visibility = SESSION_VISIBLE_READ_ONLY;
  688. }
  689. }
  690. $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$id_session' AND status = 0";
  691. $result = Database::query($sql);
  692. $existingUsers = array();
  693. while ($row = Database::fetch_array($result)) {
  694. $existingUsers[] = $row['id_user'];
  695. }
  696. $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE id_session = '$id_session'";
  697. $result = Database::query($sql);
  698. $course_list = array();
  699. while ($row = Database::fetch_array($result)) {
  700. $course_list[] = $row['c_id'];
  701. }
  702. if ($send_email) {
  703. //sending emails only
  704. if (is_array($user_list) && count($user_list)>0) {
  705. foreach ($user_list as $user_id) {
  706. if (!in_array($user_id, $existingUsers)) {
  707. $subject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
  708. $user_info = api_get_user_info($user_id);
  709. $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('siteName') ." ". 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');
  710. MessageManager::send_message($user_id, $subject, $content, array(), array(), null, null, null, null, null);
  711. }
  712. }
  713. }
  714. }
  715. foreach ($course_list as $courseId) {
  716. // for each course in the session
  717. $nbr_users = 0;
  718. $courseId = Database::escape_string($courseId);
  719. // delete existing users
  720. if ($empty_users) {
  721. foreach ($existingUsers as $existing_user) {
  722. if (!in_array($existing_user, $user_list)) {
  723. $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";
  724. $result = Database::query($sql);
  725. if (Database::affected_rows($result)) {
  726. $nbr_users--;
  727. }
  728. }
  729. }
  730. }
  731. //Replace with this new function
  732. //
  733. // insert new users into session_rel_course_rel_user and ignore if they already exist
  734. foreach ($user_list as $enreg_user) {
  735. if(!in_array($enreg_user, $existingUsers)) {
  736. $enreg_user = Database::escape_string($enreg_user);
  737. $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')";
  738. $result = Database::query($insert_sql);
  739. if (Database::affected_rows($result)) {
  740. $nbr_users++;
  741. }
  742. }
  743. }
  744. // count users in this session-course relation
  745. $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";
  746. $rs = Database::query($sql);
  747. list($nbr_users) = Database::fetch_array($rs);
  748. // update the session-course relation to add the users total
  749. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users WHERE id_session='$id_session' AND c_id ='$courseId'";
  750. Database::query($update_sql);
  751. }
  752. // Delete users from the session
  753. if ($empty_users === true) {
  754. Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session = $id_session AND relation_type<>".SESSION_RELATION_TYPE_RRHH."");
  755. }
  756. // Insert missing users into session
  757. $nbr_users = 0;
  758. foreach ($user_list as $enreg_user) {
  759. $enreg_user = Database::escape_string($enreg_user);
  760. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user) VALUES ('$id_session', '$enreg_user')";
  761. Database::query($insert_sql);
  762. //Reset moved_to just in case
  763. $update_sql = "UPDATE $tbl_session_rel_user SET moved_to = 0, moved_status = 0, moved_at ='0000-00-00 00:00:00'
  764. WHERE id_session = $id_session AND id_user = $enreg_user";
  765. Database::query($update_sql);
  766. $nbr_users++;
  767. }
  768. // update number of users in the session
  769. $nbr_users = count($user_list);
  770. if ($empty_users) {
  771. // update number of users in the session
  772. $update_sql = "UPDATE $tbl_session SET nbr_users = $nbr_users WHERE id='$id_session' ";
  773. Database::query($update_sql);
  774. } else {
  775. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users WHERE id='$id_session' ";
  776. Database::query($update_sql);
  777. }
  778. }
  779. /**
  780. * @param $user_list
  781. * @param $session_id
  782. * @param $courseId
  783. * @param int $session_visibility
  784. * @return bool
  785. */
  786. static function subscribe_users_to_session_course($user_list, $session_id, $courseId, $session_visibility = SESSION_VISIBLE_READ_ONLY ) {
  787. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  788. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  789. if (empty($user_list) || empty($session_id) || empty($course_code)) {
  790. return false;
  791. }
  792. $session_id = intval($session_id);
  793. $courseId = Database::escape_string($courseId);
  794. $session_visibility = intval($session_visibility);
  795. $nbr_users = 0;
  796. foreach ($user_list as $enreg_user) {
  797. //if (!in_array($enreg_user, $existingUsers)) {
  798. $enreg_user = intval($enreg_user);
  799. $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, visibility)
  800. VALUES ('$session_id','$courseId','$enreg_user','$session_visibility')";
  801. $result = Database::query($insert_sql);
  802. if (Database::affected_rows($result)) {
  803. $nbr_users++;
  804. }
  805. //}
  806. }
  807. // count users in this session-course relation
  808. $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";
  809. $rs = Database::query($sql);
  810. list($nbr_users) = Database::fetch_array($rs);
  811. // update the session-course relation to add the users total
  812. $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users WHERE id_session='$session_id' AND c_id = '$courseId'";
  813. Database::query($update_sql);
  814. }
  815. /**
  816. * Unsubscribe user from session
  817. *
  818. * @param int session id
  819. * @param int user id
  820. * @param int reason of unsubscription see function get_session_change_user_reasons()
  821. * @return bool true in case of success, false in case of error
  822. */
  823. public static function unsubscribe_user_from_session($session_id, $user_id) {
  824. $session_id = intval($session_id);
  825. $user_id = intval($user_id);
  826. $reason_id = intval($reason_id);
  827. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  828. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  829. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  830. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  831. $user_status = SessionManager::get_user_status_in_session($session_id, $user_id);
  832. if ($user_status['moved_to'] != 0) {
  833. //You can't subscribe a user that was moved
  834. return false;
  835. }
  836. $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."";
  837. $result = Database::query($delete_sql);
  838. $return = Database::affected_rows($result);
  839. // Update number of users
  840. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users - $return WHERE id='$session_id' ";
  841. Database::query($update_sql);
  842. // Get the list of courses related to this session
  843. $course_list = SessionManager::get_course_list_by_session_id($session_id);
  844. if (!empty($course_list)) {
  845. foreach($course_list as $course) {
  846. $courseId = $course['id'];
  847. // Delete user from course
  848. $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'");
  849. if (Database::affected_rows($result)) {
  850. // Update number of users in this relation
  851. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users - 1 WHERE id_session='$session_id' AND c_id ='$courseId'");
  852. }
  853. }
  854. }
  855. return true;
  856. }
  857. /**
  858. *
  859. * @param int $session_id
  860. * @param array user id list
  861. * @param int $courseId
  862. */
  863. static function unsubscribe_user_from_course_session($session_id, $user_list, $courseId) {
  864. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  865. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  866. if (is_array($user_list) && count($user_list)>0 ) {
  867. array_map('intval', $user_list);
  868. $user_list = implode(',', $user_list);
  869. }
  870. $session_id = intval($session_id);
  871. $courseId = Database::escape_string($courseId);
  872. if (!empty($user_list)) {
  873. $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)");
  874. $nbr_affected_rows = Database::affected_rows($result);
  875. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$session_id' AND c_id='".$courseId."'");
  876. }
  877. }
  878. /** Subscribes courses to the given session and optionally (default) unsubscribes previous users
  879. * @author Carlos Vargas from existing code
  880. * @param int Session ID
  881. * @param array List of courses IDs
  882. * @param bool Whether to unsubscribe existing users (true, default) or not (false)
  883. * @return void Nothing, or false on error
  884. **/
  885. public static function add_courses_to_session($id_session, $course_list, $empty_courses = true) {
  886. // security checks
  887. if ($id_session!= strval(intval($id_session))) { return false; }
  888. // initialisation
  889. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  890. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  891. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  892. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  893. // get general coach ID
  894. $id_coach = Database::query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
  895. $id_coach = Database::fetch_array($id_coach);
  896. $id_coach = $id_coach[0];
  897. // get list of courses subscribed to this session
  898. $rs = Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE id_session=$id_session");
  899. $existingCourses = Database::store_result($rs, 'ASSOC');
  900. $nbr_courses=count($existingCourses);
  901. // get list of users subscribed to this session
  902. $sql="SELECT id_user
  903. FROM $tbl_session_rel_user
  904. WHERE id_session = $id_session AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
  905. $result=Database::query($sql);
  906. $user_list=Database::store_result($result, 'ASSOC');
  907. // Remove existing courses from the session
  908. if ($empty_courses === true) {
  909. foreach ($existingCourses as $existingCourse) {
  910. if (!in_array($existingCourse['c_id'], $course_list)){
  911. Database::query("DELETE FROM $tbl_session_rel_course WHERE c_id='".$existingCourse['c_id']."' AND id_session=$id_session");
  912. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id='".$existingCourse['c_id']."' AND id_session=$id_session");
  913. }
  914. }
  915. $nbr_courses=0;
  916. }
  917. // Pass through the courses list we want to add to the session
  918. foreach ($course_list as $courseId) {
  919. $courseId = Database::escape_string($courseId);
  920. $exists = false;
  921. // check if the course we want to add is already subscribed
  922. foreach ($existingCourses as $existingCourse) {
  923. if ($courseId == $existingCourse['c_id']) {
  924. $exists=true;
  925. }
  926. }
  927. if ($exists == false) {
  928. CourseManager::update_course_ranking($courseId, $id_session);
  929. //if the course isn't subscribed yet
  930. $sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course (id_session, c_id) VALUES ('$id_session','$courseId')";
  931. Database::query($sql_insert_rel_course);
  932. //We add the current course in the existing courses array, to avoid adding another time the current course
  933. $existingCourses[]=array('c_id' => $courseId);
  934. $nbr_courses++;
  935. // subscribe all the users from the session to this course inside the session
  936. $nbr_users=0;
  937. foreach ($user_list as $enreg_user) {
  938. $enreg_user_id = Database::escape_string($enreg_user['id_user']);
  939. $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, c_id, id_user) VALUES ('$id_session','$courseId','$enreg_user_id')";
  940. $result = Database::query($sql_insert);
  941. if (Database::affected_rows($result)) {
  942. $nbr_users++;
  943. }
  944. }
  945. SessionManager::subscribe_users_to_session_course($user_list, $id_session, $courseId);
  946. Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND c_id = '$courseId'");
  947. }
  948. }
  949. Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'");
  950. }
  951. /**
  952. * Unsubscribe course from a session
  953. *
  954. * @param int Session id
  955. * @param int Course id
  956. * @return bool True in case of success, false otherwise
  957. */
  958. public static function unsubscribe_course_from_session($session_id, $course_id) {
  959. $session_id = (int)$session_id;
  960. $course_id = (int)$course_id;
  961. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  962. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  963. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  964. // Unsubscribe course
  965. $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE c_id ='$course_id' AND id_session='$session_id'");
  966. $nb_affected = Database::affected_rows($result);
  967. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id ='$course_id' AND id_session='$session_id'");
  968. if ($nb_affected > 0) {
  969. // Update number of courses in the session
  970. Database::query("UPDATE $tbl_session SET nbr_courses= nbr_courses + $nb_affected WHERE id='$session_id' ");
  971. return true;
  972. } else {
  973. return false;
  974. }
  975. }
  976. /**
  977. * Creates a new extra field for a given session
  978. * @param string Field's internal variable name
  979. * @param int Field's type
  980. * @param string Field's language var name
  981. * @return int new extra field id
  982. */
  983. public static function create_session_extra_field ($fieldvarname, $fieldtype, $fieldtitle) {
  984. // database table definition
  985. $params = array('field_variable' => $fieldvarname,
  986. 'field_type' => $fieldtype,
  987. 'field_display_text' => $fieldtitle
  988. );
  989. $session_field = new SessionField();
  990. $field_id = $session_field->save($params);
  991. return $field_id;
  992. }
  993. /**
  994. * Update an extra field value for a given session
  995. * @param integer Course ID
  996. * @param string Field variable name
  997. * @param string Field value
  998. * @return boolean true if field updated, false otherwise
  999. */
  1000. public static function update_session_extra_field_value ($session_id, $fname, $fvalue = null) {
  1001. $session_field_value = new SessionFieldValue();
  1002. $session_field_value->update($params);
  1003. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1004. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1005. $fname = Database::escape_string($fname);
  1006. $session_id = (int)$session_id;
  1007. $tms = api_get_utc_datetime();
  1008. $fvalues = '';
  1009. if (is_array($fvalue)) {
  1010. foreach($fvalue as $val) {
  1011. $fvalues .= Database::escape_string($val).';';
  1012. }
  1013. if(!empty($fvalues)) {
  1014. $fvalues = substr($fvalues,0,-1);
  1015. }
  1016. } else {
  1017. $fvalues = Database::escape_string($fvalue);
  1018. }
  1019. $sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
  1020. $ressf = Database::query($sqlsf);
  1021. if (Database::num_rows($ressf)==1) {
  1022. // ok, the field exists
  1023. // Check if enumerated field, if the option is available
  1024. $rowsf = Database::fetch_array($ressf);
  1025. $sqlsfv = "SELECT * FROM $t_sfv WHERE session_id = '$session_id' AND field_id = '".$rowsf['id']."' ORDER BY id";
  1026. $ressfv = Database::query($sqlsfv);
  1027. $n = Database::num_rows($ressfv);
  1028. if ($n>1) {
  1029. //problem, we already have to values for this field and user combination - keep last one
  1030. while($rowsfv = Database::fetch_array($ressfv)) {
  1031. if($n > 1) {
  1032. $sqld = "DELETE FROM $t_sfv WHERE id = ".$rowsfv['id'];
  1033. $resd = Database::query($sqld);
  1034. $n--;
  1035. }
  1036. $rowsfv = Database::fetch_array($ressfv);
  1037. if ($rowsfv['field_value'] != $fvalues) {
  1038. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = '$tms' WHERE id = ".$rowsfv['id'];
  1039. $resu = Database::query($sqlu);
  1040. return($resu?true:false);
  1041. }
  1042. return true;
  1043. }
  1044. } else if ($n==1) {
  1045. //we need to update the current record
  1046. $rowsfv = Database::fetch_array($ressfv);
  1047. if($rowsfv['field_value'] != $fvalues) {
  1048. $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = '$tms' WHERE id = ".$rowsfv['id'];
  1049. //error_log('UM::update_extra_field_value: '.$sqlu);
  1050. $resu = Database::query($sqlu);
  1051. return($resu?true:false);
  1052. }
  1053. return true;
  1054. } else {
  1055. $sqli = "INSERT INTO $t_sfv (session_id,field_id,field_value,tms) " .
  1056. "VALUES ('$session_id',".$rowsf['id'].",'$fvalues', '$tms')";
  1057. //error_log('UM::update_extra_field_value: '.$sqli);
  1058. $resi = Database::query($sqli);
  1059. return($resi?true:false);
  1060. }
  1061. } else {
  1062. return false; //field not found
  1063. }
  1064. }
  1065. /**
  1066. * Checks the relationship between a session and a course.
  1067. * @param int $session_id
  1068. * @param int $course_id
  1069. * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
  1070. * */
  1071. public static function relation_session_course_exist ($session_id, $courseId) {
  1072. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1073. $return_value = false;
  1074. $sql= "SELECT c_id FROM $tbl_session_course
  1075. WHERE id_session = ".Database::escape_string($session_id)." AND c_id = '".Database::escape_string($courseId)."'";
  1076. $result = Database::query($sql);
  1077. $num = Database::num_rows($result);
  1078. if ($num>0) {
  1079. $return_value = true;
  1080. }
  1081. return $return_value;
  1082. }
  1083. /**
  1084. * Get the session information by name
  1085. * @param string session name
  1086. * @return mixed false if the session does not exist, array if the session exist
  1087. * */
  1088. public static function get_session_by_name ($session_name) {
  1089. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1090. $sql = 'SELECT * FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name).'"';
  1091. $result = Database::query($sql);
  1092. $num = Database::num_rows($result);
  1093. if ($num) {
  1094. return Database::fetch_array($result, 'ASSOC');
  1095. } else {
  1096. return false;
  1097. }
  1098. }
  1099. /**
  1100. * Create a session category
  1101. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  1102. * @param string name
  1103. * @param integer year_start
  1104. * @param integer month_start
  1105. * @param integer day_start
  1106. * @param integer year_end
  1107. * @param integer month_end
  1108. * @param integer day_end
  1109. * @return $id_session;
  1110. **/
  1111. public static function create_category_session($sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end){
  1112. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1113. $name= trim($sname);
  1114. $year_start= intval($syear_start);
  1115. $month_start=intval($smonth_start);
  1116. $day_start=intval($sday_start);
  1117. $year_end=intval($syear_end);
  1118. $month_end=intval($smonth_end);
  1119. $day_end=intval($sday_end);
  1120. $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
  1121. $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
  1122. if (empty($name)) {
  1123. $msg=get_lang('SessionCategoryNameIsRequired');
  1124. return $msg;
  1125. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
  1126. $msg=get_lang('InvalidStartDate');
  1127. return $msg;
  1128. } elseif (!$month_end && !$day_end && !$year_end) {
  1129. $date_end = "null";
  1130. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
  1131. $msg=get_lang('InvalidEndDate');
  1132. return $msg;
  1133. } elseif($date_start >= $date_end) {
  1134. $msg=get_lang('StartDateShouldBeBeforeEndDate');
  1135. return $msg;
  1136. }
  1137. $access_url_id = api_get_current_access_url_id();
  1138. $sql = "INSERT INTO $tbl_session_category (name, date_start, date_end, access_url_id)
  1139. VALUES('".Database::escape_string($name)."','$date_start','$date_end', '$access_url_id')";
  1140. Database::query($sql);
  1141. $id_session = Database::insert_id();
  1142. // Add event to system log
  1143. $user_id = api_get_user_id();
  1144. event_system(LOG_SESSION_CATEGORY_CREATE, LOG_SESSION_CATEGORY_ID, $id_session, api_get_utc_datetime(), $user_id);
  1145. return $id_session;
  1146. }
  1147. /**
  1148. * Edit a sessions categories
  1149. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
  1150. * @param integer id
  1151. * @param string name
  1152. * @param integer year_start
  1153. * @param integer month_start
  1154. * @param integer day_start
  1155. * @param integer year_end
  1156. * @param integer month_end
  1157. * @param integer day_end
  1158. * @return $id;
  1159. * The parameter id is a primary key
  1160. **/
  1161. public static function edit_category_session($id, $sname,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end){
  1162. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1163. $name= trim($sname);
  1164. $year_start= intval($syear_start);
  1165. $month_start=intval($smonth_start);
  1166. $day_start=intval($sday_start);
  1167. $year_end=intval($syear_end);
  1168. $month_end=intval($smonth_end);
  1169. $day_end=intval($sday_end);
  1170. $id=intval($id);
  1171. $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
  1172. $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
  1173. if (empty($name)) {
  1174. $msg=get_lang('SessionCategoryNameIsRequired');
  1175. return $msg;
  1176. } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
  1177. $msg=get_lang('InvalidStartDate');
  1178. return $msg;
  1179. } elseif (!$month_end && !$day_end && !$year_end) {
  1180. $date_end = null;
  1181. } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
  1182. $msg=get_lang('InvalidEndDate');
  1183. return $msg;
  1184. } elseif($date_start >= $date_end) {
  1185. $msg=get_lang('StartDateShouldBeBeforeEndDate');
  1186. return $msg;
  1187. }
  1188. if ( $date_end <> null ) {
  1189. $sql = "UPDATE $tbl_session_category SET name = '".Database::escape_string($name)."', date_start = '$date_start' ".
  1190. ", date_end = '$date_end' WHERE id= '".$id."' ";
  1191. } else {
  1192. $sql = "UPDATE $tbl_session_category SET name = '".Database::escape_string($name)."', date_start = '$date_start' ".
  1193. ", date_end = NULL WHERE id= '".$id."' ";
  1194. }
  1195. $result = Database::query($sql);
  1196. return ($result? true:false);
  1197. }
  1198. /**
  1199. * Delete sessions categories
  1200. * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
  1201. * @param array id_checked
  1202. * @param bool include delete session
  1203. * @param bool optional, true if the function is called by a webservice, false otherwise.
  1204. * @return void Nothing, or false on error
  1205. * The parameters is a array to delete sessions
  1206. **/
  1207. public static function delete_session_category($id_checked, $delete_session = false,$from_ws = false){
  1208. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1209. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1210. if (is_array($id_checked)) {
  1211. $id_checked = Database::escape_string(implode(',',$id_checked));
  1212. } else {
  1213. $id_checked = intval($id_checked);
  1214. }
  1215. //Setting session_category_id to 0
  1216. $sql = "UPDATE $tbl_session SET session_category_id = 0 WHERE session_category_id IN (".$id_checked.")";
  1217. Database::query($sql);
  1218. $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (".$id_checked.")";
  1219. $result = @Database::query($sql);
  1220. while ($rows = Database::fetch_array($result)) {
  1221. $session_id = $rows['id'];
  1222. if ($delete_session) {
  1223. if ($from_ws) {
  1224. SessionManager::delete_session($session_id,true);
  1225. } else {
  1226. SessionManager::delete_session($session_id);
  1227. }
  1228. }
  1229. }
  1230. $sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
  1231. $rs = Database::query($sql);
  1232. $result = Database::affected_rows($rs);
  1233. // Add event to system log
  1234. $user_id = api_get_user_id();
  1235. event_system(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, api_get_utc_datetime(), $user_id);
  1236. // delete extra session fields where field variable is "PERIODO"
  1237. $t_sf = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1238. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1239. $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' ";
  1240. $rs_field = Database::query($sql);
  1241. $field_id = 0;
  1242. if (Database::num_rows($rs_field) > 0) {
  1243. $row_field = Database::fetch_row($rs_field);
  1244. $field_id = $row_field[0];
  1245. $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
  1246. $rs_delete_sfv = Database::query($sql_delete_sfv);
  1247. }
  1248. $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
  1249. $rs_field_id = Database::query($sql);
  1250. if (Database::num_rows($rs_field_id) == 0) {
  1251. $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
  1252. $rs_delete_sf = Database::query($sql_delete_sf);
  1253. }
  1254. return true;
  1255. }
  1256. /**
  1257. * Get a list of sessions of which the given conditions match with an = 'cond'
  1258. * @param array $conditions a list of condition (exemple : array('status =' =>STUDENT) or array('s.name LIKE' => "%$needle%")
  1259. * @param array $order_by a list of fields on which sort
  1260. * @return array An array with all sessions of the platform.
  1261. * @todo optional course code parameter, optional sorting parameters...
  1262. */
  1263. public static function get_sessions_list($conditions = array(), $order_by = array()) {
  1264. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1265. $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1266. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  1267. $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1268. $access_url_id = api_get_current_access_url_id();
  1269. $return_array = array();
  1270. $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
  1271. FROM $session_table s
  1272. INNER JOIN $user_table u ON s.id_coach = u.user_id
  1273. INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
  1274. LEFT JOIN $session_category_table sc ON s.session_category_id = sc.id
  1275. WHERE ar.access_url_id = $access_url_id ";
  1276. if (count($conditions) > 0) {
  1277. $sql_query .= ' AND ';
  1278. foreach ($conditions as $field=>$value) {
  1279. $field = Database::escape_string($field);
  1280. $value = Database::escape_string($value);
  1281. $sql_query .= $field." '".$value."'";
  1282. }
  1283. }
  1284. if (count($order_by)>0) {
  1285. $sql_query .= ' ORDER BY '.Database::escape_string(implode(',',$order_by));
  1286. }
  1287. //echo $sql_query;
  1288. $sql_result = Database::query($sql_query);
  1289. if (Database::num_rows($sql_result)>0) {
  1290. while ($result = Database::fetch_array($sql_result)) {
  1291. $return_array[$result['id']] = $result;
  1292. }
  1293. }
  1294. return $return_array;
  1295. }
  1296. /**
  1297. * Get the session category information by id
  1298. * @param string session category ID
  1299. * @return mixed false if the session category does not exist, array if the session category exists
  1300. */
  1301. public static function get_session_category ($id) {
  1302. $id = intval($id);
  1303. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1304. $sql = "SELECT id, name, date_start, date_end FROM $tbl_session_category WHERE id= $id";
  1305. $result = Database::query($sql);
  1306. $num = Database::num_rows($result);
  1307. if ($num>0){
  1308. return Database::fetch_array($result);
  1309. } else {
  1310. return false;
  1311. }
  1312. }
  1313. /**
  1314. * Get all session categories (filter by access_url_id)
  1315. * @return mixed false if the session category does not exist, array if the session category exists
  1316. */
  1317. public static function get_all_session_category() {
  1318. $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1319. $id = api_get_current_access_url_id();
  1320. $sql = 'SELECT * FROM '.$tbl_session_category.' WHERE access_url_id ="'.$id.'" ORDER BY name ASC';
  1321. $result = Database::query($sql);
  1322. if (Database::num_rows($result) > 0 ){
  1323. $data = Database::store_result($result,'ASSOC');
  1324. return $data;
  1325. } else {
  1326. return false;
  1327. }
  1328. }
  1329. /**
  1330. * Assign a coach to course in session with status = 2
  1331. * @param int - user id
  1332. * @param int - session id
  1333. * @param int - course id
  1334. * @param bool - optional, if is true the user don't be a coach now, otherwise it'll assign a coach
  1335. * @return bool true if there are affected rows, otherwise false
  1336. */
  1337. public static function set_coach_to_course_session($user_id, $session_id = 0, $courseId = '',$nocoach = false) {
  1338. // Definition of variables
  1339. $user_id = intval($user_id);
  1340. if (!empty($session_id)) {
  1341. $session_id = intval($session_id);
  1342. } else {
  1343. $session_id = api_get_session_id();
  1344. }
  1345. if (!empty($courseId)) {
  1346. $courseId = Database::escape_string($courseId);
  1347. } else {
  1348. $courseId = api_get_course_int_id();
  1349. }
  1350. // definitios of tables
  1351. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1352. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1353. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1354. // check if user is a teacher
  1355. $sql= "SELECT * FROM $tbl_user WHERE status='1' AND user_id = '$user_id'";
  1356. $rs_check_user = Database::query($sql);
  1357. if (Database::num_rows($rs_check_user) > 0) {
  1358. if ($nocoach) {
  1359. // check if user_id exits int session_rel_user
  1360. $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session = '$session_id' AND id_user = '$user_id'";
  1361. $res = Database::query($sql);
  1362. if (Database::num_rows($res) > 0) {
  1363. // The user don't be a coach now
  1364. $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' ";
  1365. $rs_update = Database::query($sql);
  1366. if (Database::affected_rows($rs_update) > 0) return true;
  1367. else return false;
  1368. } else {
  1369. // The user don't be a coach now
  1370. $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' ";
  1371. $rs_delete = Database::query($sql);
  1372. if (Database::affected_rows($rs_delete) > 0) return true;
  1373. else return false;
  1374. }
  1375. } else {
  1376. // Assign user like a coach to course
  1377. // First check if the user is registered in the course
  1378. $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'";
  1379. $rs_check = Database::query($sql);
  1380. //Then update or insert
  1381. if (Database::num_rows($rs_check) > 0) {
  1382. $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' ";
  1383. $rs_update = Database::query($sql);
  1384. if (Database::affected_rows($rs_update) > 0) return true;
  1385. else return false;
  1386. } else {
  1387. $sql = " INSERT INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, status) VALUES('$session_id', '$courseId', '$user_id', 2)";
  1388. $rs_insert = Database::query($sql);
  1389. if (Database::affected_rows($rs_insert) > 0) return true;
  1390. else return false;
  1391. }
  1392. }
  1393. } else {
  1394. return false;
  1395. }
  1396. }
  1397. /**
  1398. * Subscribes sessions to human resource manager (Dashboard feature)
  1399. * @param int Human Resource Manager id
  1400. * @param array Sessions id
  1401. * @param int Relation type
  1402. **/
  1403. public static function suscribe_sessions_to_hr_manager($hr_manager_id,$sessions_list) {
  1404. global $_configuration;
  1405. // Database Table Definitions
  1406. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1407. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1408. $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1409. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1410. $hr_manager_id = intval($hr_manager_id);
  1411. $affected_rows = 0;
  1412. //Deleting assigned sessions to hrm_id
  1413. if (api_is_multiple_url_enabled()) {
  1414. $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)
  1415. WHERE id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH." AND access_url_id = ".api_get_current_access_url_id()."";
  1416. } else {
  1417. $sql = "SELECT id_session FROM $tbl_session_rel_user s WHERE id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH."";
  1418. }
  1419. $result = Database::query($sql);
  1420. if (Database::num_rows($result) > 0) {
  1421. while ($row = Database::fetch_array($result)) {
  1422. $sql = "DELETE FROM $tbl_session_rel_user
  1423. WHERE id_session = {$row['id_session']} AND id_user = $hr_manager_id AND relation_type=".SESSION_RELATION_TYPE_RRHH." ";
  1424. Database::query($sql);
  1425. }
  1426. }
  1427. // inserting new sessions list
  1428. if (is_array($sessions_list)) {
  1429. foreach ($sessions_list as $session_id) {
  1430. $session_id = intval($session_id);
  1431. $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."')";
  1432. $result = Database::query($insert_sql);
  1433. $affected_rows = Database::affected_rows($result);
  1434. }
  1435. }
  1436. return $affected_rows;
  1437. }
  1438. /**
  1439. * Get sessions followed by human resources manager
  1440. * @param int Human resources manager or Session admin id
  1441. * @return array sessions
  1442. */
  1443. public static function get_sessions_followed_by_drh($hr_manager_id) {
  1444. global $_configuration;
  1445. // Database Table Definitions
  1446. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1447. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1448. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1449. $hr_manager_id = intval($hr_manager_id);
  1450. $assigned_sessions_to_hrm = array();
  1451. if ($_configuration['multiple_access_urls']) {
  1452. $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)
  1453. 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()."";
  1454. } else {
  1455. $sql = "SELECT * FROM $tbl_session s
  1456. 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."' ";
  1457. }
  1458. $rs_assigned_sessions = Database::query($sql);
  1459. if (Database::num_rows($rs_assigned_sessions) > 0) {
  1460. while ($row_assigned_sessions = Database::fetch_array($rs_assigned_sessions)) {
  1461. $assigned_sessions_to_hrm[$row_assigned_sessions['id']] = $row_assigned_sessions;
  1462. }
  1463. }
  1464. return $assigned_sessions_to_hrm;
  1465. }
  1466. /**
  1467. * Gets the list of courses by session filtered by access_url
  1468. * @param int session id
  1469. * @return array list of courses
  1470. */
  1471. public static function get_course_list_by_session_id ($session_id) {
  1472. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1473. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1474. // select the courses
  1475. $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
  1476. WHERE src.id_session = '$session_id'
  1477. ORDER BY title;";
  1478. $result = Database::query($sql);
  1479. $num_rows = Database::num_rows($result);
  1480. $courses = array();
  1481. if ($num_rows > 0) {
  1482. while ($row = Database::fetch_array($result,'ASSOC')) {
  1483. $row['real_id'] = $row['id'];
  1484. $courses[$row['id']] = $row;
  1485. }
  1486. }
  1487. return $courses;
  1488. }
  1489. /**
  1490. * Get the session id based on the original id and field name in the extra fields. Returns 0 if session was not found
  1491. *
  1492. * @param string Original session id
  1493. * @param string Original field name
  1494. * @return int Session id
  1495. */
  1496. public static function get_session_id_from_original_id($original_session_id_value, $original_session_id_name) {
  1497. $t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  1498. $table_field = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
  1499. $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'";
  1500. $res_session = Database::query($sql_session);
  1501. $row = Database::fetch_object($res_session);
  1502. if ($row) {
  1503. return $row->session_id;
  1504. } else {
  1505. return 0;
  1506. }
  1507. }
  1508. /**
  1509. * Get users by session
  1510. * @param int session id
  1511. * @param int filter by status
  1512. * @return array a list with an user list
  1513. */
  1514. public static function get_users_by_session($id, $with_status = null) {
  1515. if (empty($id)) {
  1516. return array();
  1517. }
  1518. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1519. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1520. $id = intval($id);
  1521. /*
  1522. * sessions are not shared between urls
  1523. if (api_is_multiple_url_enabled()) {
  1524. $tbl_session_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1525. $url_id = api_get_current_access_url_id();
  1526. $sql = "SELECT u.user_id, lastname, firstname, username, access_url_id, moved_to, moved_status, moved_at
  1527. FROM $tbl_user u
  1528. INNER JOIN $tbl_session_rel_user su
  1529. ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH."
  1530. INNER JOIN $tbl_session_rel_url s ON (s.session_id = su.id_session)
  1531. LEFT OUTER JOIN $tbl_session_rel_user uu ON (uu.user_id = u.user_id AND s.session_id = uu.id_session)
  1532. WHERE su.id_session = $id AND (access_url_id = $url_id OR access_url_id is null )";
  1533. } else {
  1534. $sql = "SELECT u.user_id, lastname, firstname, username, moved_to, moved_status, moved_at
  1535. FROM $tbl_user u INNER JOIN $tbl_session_rel_user su
  1536. ON u.user_id = su.id_user AND
  1537. su.id_session = $id
  1538. WHERE 1 = 1
  1539. ";
  1540. }*/
  1541. $sql = "SELECT u.user_id,
  1542. lastname,
  1543. firstname,
  1544. username,
  1545. moved_to,
  1546. moved_status,
  1547. moved_at
  1548. FROM $tbl_user u INNER JOIN $tbl_session_rel_user su
  1549. ON u.user_id = su.id_user AND
  1550. su.id_session = $id
  1551. WHERE 1 = 1
  1552. ";
  1553. if (isset($with_status) && $with_status != '') {
  1554. $with_status = intval($with_status);
  1555. $sql .= " AND relation_type = $with_status ";
  1556. }
  1557. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
  1558. $sql .= $order_clause;
  1559. $return_array = array();
  1560. $result = Database::query($sql);
  1561. while ($row = Database::fetch_array($result,'ASSOC')) {
  1562. $return_array[] = $row;
  1563. }
  1564. return $return_array;
  1565. }
  1566. /**
  1567. * The general coach (field: session.id_coach)
  1568. * @param int user id
  1569. */
  1570. public static function get_sessions_by_general_coach($user_id) {
  1571. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1572. $user_id = intval($user_id);
  1573. // session where we are general coach
  1574. $sql = "SELECT DISTINCT *
  1575. FROM $session_table
  1576. WHERE id_coach = $user_id";
  1577. if (api_is_multiple_url_enabled()) {
  1578. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1579. $access_url_id = api_get_current_access_url_id();
  1580. if ($access_url_id != -1) {
  1581. $sql = 'SELECT DISTINCT session.*
  1582. FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  1583. ON (session.id = session_rel_url.session_id)
  1584. WHERE id_coach = '.$user_id.' AND access_url_id = '.$access_url_id;
  1585. }
  1586. }
  1587. $sql .= ' ORDER by name';
  1588. $result = Database::query($sql);
  1589. return Database::store_result($result, 'ASSOC');
  1590. }
  1591. /**
  1592. * Get all sessions if the user is a sesion course coach of any session
  1593. * @param int user id
  1594. */
  1595. static function get_sessions_by_coach($user_id) {
  1596. // table definition
  1597. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  1598. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1599. $sql = 'SELECT DISTINCT session.*
  1600. FROM ' . $tbl_session . ' as session
  1601. INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
  1602. ON session.id = session_course_user.id_session
  1603. AND session_course_user.id_user=' . $user_id.' AND session_course_user.status=2';
  1604. if (api_is_multiple_url_enabled()) {
  1605. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1606. $access_url_id = api_get_current_access_url_id();
  1607. if ($access_url_id != -1){
  1608. $sql = 'SELECT DISTINCT session.*
  1609. FROM '.$tbl_session.' as session
  1610. INNER JOIN ' . $tbl_session_course_user . ' as session_course_user
  1611. ON session.id = session_course_user.id_session AND session_course_user.id_user = '.$user_id.' AND session_course_user.status=2
  1612. INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  1613. ON (session.id = session_rel_url.session_id)
  1614. WHERE access_url_id = '.$access_url_id;
  1615. }
  1616. }
  1617. //$sql .= " ORDER BY session.name";
  1618. $result = Database::query($sql);
  1619. return Database::store_result($result, 'ASSOC');
  1620. }
  1621. public static function get_sessions_coached_by_user($coach_id, $check_session_rel_user_visibility = false) {
  1622. $sessions = self::get_sessions_by_general_coach($coach_id);
  1623. $sessions_by_coach = self::get_sessions_by_coach($coach_id);
  1624. if (!empty($sessions_by_coach)) {
  1625. $sessions = array_merge($sessions, $sessions_by_coach);
  1626. }
  1627. //Remove repeated sessions
  1628. if (!empty($sessions)) {
  1629. $clean_sessions = array();
  1630. foreach ($sessions as $session) {
  1631. $clean_sessions[$session['id']] = $session;
  1632. }
  1633. $sessions = $clean_sessions;
  1634. }
  1635. if ($check_session_rel_user_visibility) {
  1636. if (!empty($sessions)) {
  1637. $new_session = array();
  1638. foreach ($sessions as $session) {
  1639. $visibility = api_get_session_visibility($session['id']);
  1640. if ($visibility == SESSION_INVISIBLE) {
  1641. continue;
  1642. }
  1643. $new_session[] = $session;
  1644. }
  1645. $sessions = $new_session;
  1646. }
  1647. }
  1648. return $sessions;
  1649. }
  1650. /**
  1651. * Gets user status within a session
  1652. * @param $user_id
  1653. * @param $course_code
  1654. * @param $session_id
  1655. * @return unknown_type
  1656. */
  1657. public static function get_user_status_in_course_session($user_id, $courseId, $session_id) {
  1658. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1659. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1660. $sql = "SELECT session_rcru.status
  1661. FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  1662. WHERE session_rcru.id_user = user.user_id AND
  1663. session_rcru.id_session = '".intval($session_id)."' AND
  1664. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  1665. user.user_id = ".intval($user_id);
  1666. $result = Database::query($sql);
  1667. $status = false;
  1668. if (Database::num_rows($result)) {
  1669. $status = Database::fetch_row($result);
  1670. $status = $status['0'];
  1671. }
  1672. return $status;
  1673. }
  1674. static function get_user_status_in_session($session_id, $user_id) {
  1675. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1676. $session_id = intval($session_id);
  1677. $user_id = intval($user_id);
  1678. $sql = "SELECT * FROM $tbl_session_rel_user WHERE id_user = $user_id AND id_session = $session_id";
  1679. $result = Database::query($sql);
  1680. if (Database::num_rows($result)) {
  1681. $result = Database::store_result($result, 'ASSOC');
  1682. return $result[0];
  1683. }
  1684. return array();
  1685. }
  1686. function get_all_sessions_by_promotion($id) {
  1687. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1688. return Database::select('*', $t, array('where'=>array('promotion_id = ?'=>$id)));
  1689. }
  1690. function suscribe_sessions_to_promotion($promotion_id, $list) {
  1691. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1692. $params = array();
  1693. $params['promotion_id'] = 0;
  1694. Database::update($t, $params, array('promotion_id = ?'=>$promotion_id));
  1695. $params['promotion_id'] = $promotion_id;
  1696. if (!empty($list)) {
  1697. foreach ($list as $session_id) {
  1698. $session_id= intval($session_id);
  1699. Database::update($t, $params, array('id = ?'=>$session_id));
  1700. }
  1701. }
  1702. }
  1703. /**
  1704. * Updates a session status
  1705. * @param int session id
  1706. * @param int status
  1707. */
  1708. public function set_session_status($session_id, $status) {
  1709. $t = Database::get_main_table(TABLE_MAIN_SESSION);
  1710. $params['visibility'] = $status;
  1711. Database::update($t, $params, array('id = ?'=>$session_id));
  1712. }
  1713. /**
  1714. * Copies a session with the same data to a new session.
  1715. * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
  1716. * @param int Session ID
  1717. * @param bool Whether to copy the relationship with courses
  1718. * @param bool Whether to copy the relationship with users
  1719. * @param bool New courses will be created
  1720. * @return int The new session ID on success, 0 otherwise
  1721. * @todo make sure the extra session fields are copied too
  1722. */
  1723. /**
  1724. * @param $id
  1725. * @param $copy_courses
  1726. * @param $copy_users
  1727. * @param $create_new_courses
  1728. * @param $set_exercises_lp_invisible
  1729. * @return int
  1730. */
  1731. public function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false) {
  1732. $id = intval($id);
  1733. $params = self::fetch($id);
  1734. $params['name'] = $params['name'].' '.get_lang('CopyLabelSuffix');
  1735. $sid = self::add($params);
  1736. if (!is_numeric($sid) || empty($sid)) {
  1737. return false;
  1738. }
  1739. if ($copy_courses) {
  1740. // Register courses from the original session to the new session
  1741. $courses = self::get_course_list_by_session_id($id);
  1742. $short_courses = $new_short_courses = array();
  1743. if (is_array($courses) && count($courses)>0) {
  1744. foreach ($courses as $course) {
  1745. $short_courses[] = $course;
  1746. }
  1747. }
  1748. $courses = null;
  1749. //We will copy the current courses of the session to new courses
  1750. if (!empty($short_courses)) {
  1751. if ($create_new_courses) {
  1752. //Just in case
  1753. if (function_exists('ini_set')) {
  1754. api_set_memory_limit('256M');
  1755. ini_set('max_execution_time',0);
  1756. }
  1757. $params = array();
  1758. $params['skip_lp_dates'] = true;
  1759. foreach ($short_courses as $course_data) {
  1760. $course_info = CourseManager::copy_course_simple($course_data['title'].' '.get_lang('CopyLabelSuffix'), $course_data['course_code'], $id, $sid, $params);
  1761. if ($course_info) {
  1762. //By default new elements are invisible
  1763. if ($set_exercises_lp_invisible) {
  1764. $list = new LearnpathList('', $course_info['code'], $sid);
  1765. $flat_list = $list->get_flat_list();
  1766. if (!empty($flat_list)) {
  1767. foreach ($flat_list as $lp_id => $data) {
  1768. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0 ,0, 0, 0, $sid);
  1769. api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0 ,0, 0, 0);
  1770. }
  1771. }
  1772. $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
  1773. $course_id = $course_info['real_id'];
  1774. //@todo check this query
  1775. //Disabling quiz items
  1776. $sql = "UPDATE $quiz_table SET active = 0 WHERE c_id = $course_id ";
  1777. Database::query($sql);
  1778. }
  1779. $new_short_courses[] = $course_info['code'];
  1780. }
  1781. }
  1782. } else {
  1783. foreach($short_courses as $course_data) {
  1784. $new_short_courses[] = $course_data['id'];
  1785. }
  1786. }
  1787. $short_courses = $new_short_courses;
  1788. $res = self::add_courses_to_session($sid, $short_courses, true);
  1789. $short_courses = null;
  1790. }
  1791. }
  1792. if ($copy_users) {
  1793. // Register users from the original session to the new session
  1794. $users = self::get_users_by_session($id);
  1795. $short_users = array();
  1796. if (is_array($users) && count($users)>0) {
  1797. foreach ($users as $user) {
  1798. $short_users[] = $user['user_id'];
  1799. }
  1800. }
  1801. $users = null;
  1802. //Subscribing in read only mode
  1803. $res = self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true, false);
  1804. $short_users = null;
  1805. }
  1806. return $sid;
  1807. }
  1808. static function user_is_general_coach($user_id, $session_id) {
  1809. $session_id = intval($session_id);
  1810. $user_id = intval($user_id);
  1811. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1812. $sql = "SELECT DISTINCT id
  1813. FROM $session_table
  1814. WHERE session.id_coach = '".$user_id."' AND id = '$session_id'";
  1815. $result = Database::query($sql);
  1816. if ($result && Database::num_rows($result)) {
  1817. return true;
  1818. }
  1819. return false;
  1820. }
  1821. /**
  1822. * Get the number of sessions
  1823. * @param int ID of the URL we want to filter on (optional)
  1824. * @return int Number of sessions
  1825. */
  1826. public static function count_sessions($access_url_id=null) {
  1827. $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
  1828. $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1829. $sql = "SELECT count(id) FROM $session_table s";
  1830. if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
  1831. $sql .= ", $access_url_rel_session_table u ".
  1832. " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
  1833. }
  1834. $res = Database::query($sql);
  1835. $row = Database::fetch_row($res);
  1836. return $row[0];
  1837. }
  1838. /**
  1839. * @param int $id
  1840. * @return bool
  1841. */
  1842. static function protect_session_edit($id = null)
  1843. {
  1844. if (api_is_platform_admin()) {
  1845. return false;
  1846. }
  1847. if (api_is_session_admin()) {
  1848. return false;
  1849. }
  1850. $blockTeachers = !api_is_teacher() || (api_is_teacher() && api_get_setting('allow_teachers_to_create_sessions') == 'false');
  1851. if ($blockTeachers) {
  1852. api_not_allowed(true);
  1853. }
  1854. if (!empty($id)) {
  1855. $session_info = self::fetch($id);
  1856. if (empty($session_info)) {
  1857. api_not_allowed(true);
  1858. }
  1859. if ($blockTeachers && !api_is_platform_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true') {
  1860. if ($session_info['session_admin_id'] != api_get_user_id()) {
  1861. api_not_allowed(true);
  1862. }
  1863. }
  1864. //Blocking teachers that want to edit another session
  1865. if ($blockTeachers == false && $session_info['id_coach'] != api_get_user_id()) {
  1866. api_not_allowed(true);
  1867. }
  1868. }
  1869. }
  1870. /**
  1871. * @param $courseId
  1872. * @return array
  1873. */
  1874. static function get_session_by_course($courseId)
  1875. {
  1876. $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1877. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1878. $courseId = Database::escape_string($courseId);
  1879. $sql = "SELECT name, s.id FROM $table_session_course sc INNER JOIN $table_session s ON (sc.id_session = s.id)
  1880. WHERE sc.c_id = '$courseId' ";
  1881. $result = Database::query($sql);
  1882. return Database::store_result($result);
  1883. }
  1884. public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false)
  1885. {
  1886. $session_categories = UserManager::get_sessions_by_category($user_id, false, false, false, 0, null, null, $ignore_visibility_for_admins);
  1887. $session_array = array();
  1888. if (!empty($session_categories)) {
  1889. foreach ($session_categories as $category) {
  1890. if (isset($category['sessions'])) {
  1891. foreach ($category['sessions'] as $session) {
  1892. $session_array[] = $session;
  1893. }
  1894. }
  1895. }
  1896. }
  1897. return $session_array;
  1898. }
  1899. /**
  1900. * @param string $file
  1901. * @param bool $updatesession options:
  1902. * true: if the session exists it will be updated
  1903. * false: if session exists a new session will be created adding a counter session1, session2, etc
  1904. * @param int $user_id
  1905. * @param $logger
  1906. * @param array convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  1907. * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  1908. * @param array extra fields
  1909. * @param string extra field id
  1910. * @param int $daysCoachAccessBeforeBeginning
  1911. * @param int $daysCoachAccessAfterBeginning
  1912. * @param int $sessionVisibility
  1913. * @return array
  1914. */
  1915. static function importCSV(
  1916. $file,
  1917. $updatesession,
  1918. $defaultUserId = null,
  1919. $logger = null,
  1920. $extraFields = array(),
  1921. $extraFieldId = null,
  1922. $daysCoachAccessBeforeBeginning = null,
  1923. $daysCoachAccessAfterBeginning = null,
  1924. $sessionVisibility = 1,
  1925. $fieldsToAvoidUpdate = array()
  1926. )
  1927. {
  1928. $content = file($file);
  1929. $error_message = null;
  1930. $session_counter = 0;
  1931. if (empty($defaultUserId)) {
  1932. $defaultUserId = api_get_user_id();
  1933. }
  1934. $eol = PHP_EOL;
  1935. if (PHP_SAPI !='cli') {
  1936. $eol = '<br />';
  1937. }
  1938. $debug = false;
  1939. if (isset($logger)) {
  1940. $debug = true;
  1941. }
  1942. $extraParameters = null;
  1943. if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
  1944. $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
  1945. $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
  1946. }
  1947. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1948. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1949. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1950. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1951. $sessions = array();
  1952. if (!api_strstr($content[0], ';')) {
  1953. $error_message = get_lang('NotCSV');
  1954. } else {
  1955. $tag_names = array();
  1956. foreach ($content as $key => $enreg) {
  1957. $enreg = explode(';', trim($enreg));
  1958. if ($key) {
  1959. foreach ($tag_names as $tag_key => $tag_name) {
  1960. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  1961. }
  1962. } else {
  1963. foreach ($enreg as $tag_name) {
  1964. $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
  1965. }
  1966. if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
  1967. $error_message = get_lang('NoNeededData');
  1968. break;
  1969. }
  1970. }
  1971. }
  1972. // Looping the sessions.
  1973. foreach ($sessions as $enreg) {
  1974. $user_counter = 0;
  1975. $course_counter = 0;
  1976. if (isset($extraFields) && !empty($extraFields)) {
  1977. foreach ($extraFields as $original => $to) {
  1978. $enreg[$to] = $enreg[$original];
  1979. }
  1980. }
  1981. $session_name = Database::escape_string($enreg['SessionName']);
  1982. $date_start = $enreg['DateStart'];
  1983. $date_end = $enreg['DateEnd'];
  1984. $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
  1985. $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
  1986. // Searching a general coach.
  1987. if (!empty($enreg['Coach'])) {
  1988. $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
  1989. if ($coach_id === false) {
  1990. // If the coach-user does not exist - I'm the coach.
  1991. $coach_id = $defaultUserId;
  1992. }
  1993. } else {
  1994. $coach_id = $defaultUserId;
  1995. }
  1996. if (!$updatesession) {
  1997. // Always create a session.
  1998. $unique_name = false; // This MUST be initializead.
  1999. $i = 0;
  2000. // Change session name, verify that session doesn't exist.
  2001. $suffix = null;
  2002. while (!$unique_name) {
  2003. if ($i > 1) {
  2004. $suffix = ' - '.$i;
  2005. }
  2006. $sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.$session_name.$suffix.'"';
  2007. $rs = Database::query($sql);
  2008. if (Database::result($rs, 0, 0)) {
  2009. $i++;
  2010. } else {
  2011. $unique_name = true;
  2012. $session_name .= $suffix;
  2013. }
  2014. }
  2015. // Creating the session.
  2016. /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
  2017. name = '".$session_name."',
  2018. id_coach = '$coach_id',
  2019. date_start = '$date_start',
  2020. date_end = '$date_end',
  2021. visibility = '$visibility',
  2022. session_category_id = '$session_category_id',
  2023. session_admin_id=".intval($defaultUserId).$extraParameters;
  2024. Database::query($sql_session);*/
  2025. $params = array (
  2026. 'id_coach' => $coach_id,
  2027. 'visibility' => $visibility,
  2028. 'name' => $session_name,
  2029. 'access_start_date' => $date_start,
  2030. 'access_end_date' => $date_end,
  2031. 'session_category_id' => $session_category_id,
  2032. 'session_admin_id' => $defaultUserId,
  2033. );
  2034. $session_id = SessionManager::add($params);
  2035. if ($debug) {
  2036. if ($session_id) {
  2037. foreach ($enreg as $key => $value) {
  2038. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2039. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2040. }
  2041. }
  2042. $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
  2043. } else {
  2044. $logger->addError("Sessions - Session NOT created: $session_name");
  2045. }
  2046. }
  2047. $session_counter++;
  2048. } else {
  2049. $sessionId = null;
  2050. if (isset($extraFields) && !empty($extraFields)) {
  2051. $sessionId = self::get_session_id_from_original_id($enreg['extra_'.$extraFieldId], $extraFieldId);
  2052. if (empty($sessionId)) {
  2053. $my_session_result = false;
  2054. } else {
  2055. $my_session_result = true;
  2056. }
  2057. } else {
  2058. $my_session_result = self::get_session_by_name($enreg['SessionName']);
  2059. }
  2060. if ($my_session_result === false) {
  2061. // Creating a session.
  2062. /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
  2063. name = '$session_name',
  2064. id_coach = '$coach_id',
  2065. date_start = '$date_start',
  2066. date_end = '$date_end',
  2067. visibility = '$visibility',
  2068. session_category_id = '$session_category_id' ".$extraParameters;*/
  2069. $params = array (
  2070. 'id_coach' => $coach_id,
  2071. 'visibility' => $visibility,
  2072. 'name' => $session_name,
  2073. 'access_start_date' => $date_start,
  2074. 'access_end_date' => $date_end,
  2075. 'session_category_id' => $session_category_id,
  2076. 'session_admin_id' => $defaultUserId,
  2077. );
  2078. $session_id = SessionManager::add($params);
  2079. // We get the last insert id.
  2080. /*$my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
  2081. $session_id = $my_session_result['id'];*/
  2082. if ($debug) {
  2083. if ($session_id) {
  2084. foreach ($enreg as $key => $value) {
  2085. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2086. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2087. }
  2088. }
  2089. $logger->addInfo("Sessions - #$session_id created: $session_name");
  2090. } else {
  2091. $logger->addError("Sessions - Session NOT created: $session_name");
  2092. }
  2093. }
  2094. } else {
  2095. $params = array(
  2096. 'id_coach' => $coach_id,
  2097. 'date_start' => $date_start,
  2098. 'date_end' => $date_end,
  2099. 'visibility' => $visibility,
  2100. 'session_category_id' => $session_category_id
  2101. );
  2102. if (!empty($fieldsToAvoidUpdate)) {
  2103. foreach ($fieldsToAvoidUpdate as $field) {
  2104. unset($params[$field]);
  2105. }
  2106. }
  2107. if (isset($sessionId) && !empty($sessionId)) {
  2108. // The session already exists, update it then.
  2109. Database::update($tbl_session, $params, array('id = ?' => $sessionId));
  2110. $session_id = $sessionId;
  2111. } else {
  2112. Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName']));
  2113. $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
  2114. list($session_id) = Database::fetch_array($row);
  2115. }
  2116. foreach ($enreg as $key => $value) {
  2117. if (substr($key, 0, 6) == 'extra_') { //an extra field
  2118. self::update_session_extra_field_value($session_id, substr($key, 6), $value);
  2119. }
  2120. }
  2121. Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
  2122. Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'");
  2123. Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'");
  2124. }
  2125. $session_counter++;
  2126. }
  2127. $users = explode('|', $enreg['Users']);
  2128. // Adding the relationship "Session - User".
  2129. if (is_array($users)) {
  2130. foreach ($users as $user) {
  2131. $user_id = UserManager::get_user_id_from_username($user);
  2132. if ($user_id !== false) {
  2133. // Insert new users.
  2134. $sql = "INSERT IGNORE INTO $tbl_session_user SET
  2135. id_user = '$user_id',
  2136. id_session = '$session_id'";
  2137. Database::query($sql);
  2138. if ($debug) {
  2139. $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
  2140. }
  2141. $user_counter++;
  2142. }
  2143. }
  2144. }
  2145. $courses = explode('|', $enreg['Courses']);
  2146. foreach ($courses as $course) {
  2147. $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
  2148. if (CourseManager::course_exists($course_code)) {
  2149. $courseInfo = api_get_course_info($course_code);
  2150. $courseId = $courseInfo['real_id'];
  2151. // Adding the course to a session.
  2152. $sql_course = "INSERT IGNORE INTO $tbl_session_course
  2153. SET c_id = '".$courseId."', id_session = '$session_id'";
  2154. Database::query($sql_course);
  2155. if ($debug) {
  2156. $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
  2157. }
  2158. $course_counter++;
  2159. $pattern = "/\[(.*?)\]/";
  2160. preg_match_all($pattern, $course, $matches);
  2161. if (isset($matches[1])) {
  2162. $course_coaches = $matches[1][0];
  2163. $course_users = $matches[1][1];
  2164. }
  2165. $course_users = explode(',', $course_users);
  2166. $course_coaches = explode(',', $course_coaches);
  2167. // Adding coaches to session course user
  2168. if (!empty($course_coaches)) {
  2169. foreach ($course_coaches as $course_coach) {
  2170. $coach_id = UserManager::get_user_id_from_username($course_coach);
  2171. if ($coach_id !== false) {
  2172. $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
  2173. id_user='$coach_id',
  2174. c_id ='$courseId',
  2175. id_session = '$session_id',
  2176. status = 2 ";
  2177. Database::query($sql);
  2178. if ($debug) {
  2179. $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
  2180. }
  2181. } else {
  2182. $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
  2183. }
  2184. }
  2185. }
  2186. $users_in_course_counter = 0;
  2187. // Adding the relationship "Session - Course - User".
  2188. foreach ($course_users as $user) {
  2189. $user_id = UserManager::get_user_id_from_username($user);
  2190. if ($user_id !== false) {
  2191. $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
  2192. id_user='$user_id',
  2193. c_id = '$courseId',
  2194. id_session = '$session_id'";
  2195. Database::query($sql);
  2196. if ($debug) {
  2197. $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
  2198. }
  2199. $users_in_course_counter++;
  2200. } else {
  2201. $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
  2202. }
  2203. }
  2204. $sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE c_id ='$courseId'";
  2205. Database::query($sql);
  2206. $course_info = CourseManager::get_course_information($course_code);
  2207. $inserted_in_course[$course_code] = $course_info['title'];
  2208. }
  2209. }
  2210. $access_url_id = api_get_current_access_url_id();
  2211. UrlManager::add_session_to_url($session_id, $access_url_id);
  2212. $sql_update_users = "UPDATE $tbl_session SET nbr_users ='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
  2213. Database::query($sql_update_users);
  2214. }
  2215. }
  2216. return array(
  2217. 'error_message' => $error_message,
  2218. 'session_counter' => $session_counter
  2219. );
  2220. }
  2221. /**
  2222. * @todo Add constatns in a DB table
  2223. */
  2224. static function get_session_change_user_reasons() {
  2225. return array (
  2226. self::SESSION_CHANGE_USER_REASON_SCHEDULE => get_lang('ScheduleChanged'),
  2227. self::SESSION_CHANGE_USER_REASON_CLASSROOM => get_lang('ClassRoomChanged'),
  2228. self::SESSION_CHANGE_USER_REASON_LOCATION => get_lang('LocationChanged'),
  2229. //self::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION => get_lang('EnrollmentAnnulation'),
  2230. );
  2231. }
  2232. static function get_session_change_user_reasons_variations() {
  2233. return array (
  2234. self::SESSION_CHANGE_USER_REASON_SCHEDULE => array(
  2235. 'default' => get_lang('ScheduleChanged'),
  2236. 'from' => get_lang('ScheduleChangedFrom'),
  2237. 'to' => get_lang('ScheduleChangedTo'),
  2238. ),
  2239. self::SESSION_CHANGE_USER_REASON_CLASSROOM => array(
  2240. 'default' => get_lang('ClassRoomChanged'),
  2241. 'from' => get_lang('ClassRoomChangedFrom'),
  2242. 'to' => get_lang('ClassRoomChangedTo'),
  2243. ),
  2244. self::SESSION_CHANGE_USER_REASON_LOCATION => array(
  2245. 'default' => get_lang('LocationChanged'),
  2246. 'from' => get_lang('LocationChangedFrom'),
  2247. 'to' => get_lang('LocationChangedTo'),
  2248. )
  2249. );
  2250. }
  2251. static function get_session_change_user_reasons_variations_by_id($id, $type) {
  2252. $reasons = self::get_session_change_user_reasons_variations();
  2253. $my_reason = isset($reasons[$id]) ? $reasons[$id] : null;
  2254. return isset($my_reason[$type]) ? $my_reason[$type] : null;
  2255. }
  2256. static function get_session_changed_reason_label($id, $type) {
  2257. switch ($type) {
  2258. case 'origin':
  2259. break;
  2260. case 'destination':
  2261. break;
  2262. }
  2263. }
  2264. /**
  2265. * Gets the reason name
  2266. * @param int reason id
  2267. */
  2268. static function get_session_change_user_reason($id) {
  2269. $reasons = self::get_session_change_user_reasons();
  2270. return isset($reasons[$id]) ? $reasons[$id] : null;
  2271. }
  2272. /**
  2273. * Changes the user from one session to another due a reason
  2274. * @params int user_id
  2275. * @params int old session id
  2276. * @params int new session id
  2277. * @params int see SessionManager::get_session_change_user_reasons()
  2278. */
  2279. static function change_user_session($user_id, $old_session_id, $new_session_id, $reason_id) {
  2280. if (!empty($user_id) && !empty($old_session_id) && !empty($new_session_id)) {
  2281. $user_id = intval($user_id);
  2282. $old_session_id = intval($old_session_id);
  2283. $new_session_id = intval($new_session_id);
  2284. $reason_id = intval($reason_id);
  2285. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2286. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2287. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2288. // Update number of users
  2289. $update_sql = "UPDATE $tbl_session SET nbr_users = nbr_users - 1 WHERE id = '$old_session_id' ";
  2290. Database::query($update_sql);
  2291. // Get the list of courses related to this session
  2292. $course_list = SessionManager::get_course_list_by_session_id($old_session_id);
  2293. if (!empty($course_list)) {
  2294. foreach ($course_list as $course) {
  2295. $courseId = $course['id'];
  2296. // Delete user from course
  2297. //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'");
  2298. //if (Database::affected_rows()) {
  2299. // Update number of users in this relation
  2300. $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1 WHERE id_session = '$old_session_id' AND c_id='$courseId'";
  2301. Database::query($sql);
  2302. //}
  2303. }
  2304. }
  2305. //Deal with reasons
  2306. switch ($reason_id) {
  2307. case self::SESSION_CHANGE_USER_REASON_SCHEDULE:
  2308. case self::SESSION_CHANGE_USER_REASON_CLASSROOM:
  2309. case self::SESSION_CHANGE_USER_REASON_LOCATION:
  2310. //Adding to the new session
  2311. self::suscribe_users_to_session($new_session_id, array($user_id), null, false);
  2312. //Setting move_to if session was provided
  2313. $sql = "UPDATE $tbl_session_rel_user SET moved_to = '$new_session_id'
  2314. WHERE id_session = '$old_session_id' AND id_user ='$user_id'";
  2315. Database::query($sql);
  2316. break;
  2317. case self::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION:
  2318. UserManager::deactivate_users(array($user_id));
  2319. break;
  2320. }
  2321. $now = api_get_utc_datetime();
  2322. //Setting the moved_status
  2323. $sql = "UPDATE $tbl_session_rel_user SET moved_status = $reason_id, moved_at = '$now'
  2324. WHERE id_session = '$old_session_id' AND id_user ='$user_id'";
  2325. Database::query($sql);
  2326. return true;
  2327. }
  2328. return;
  2329. }
  2330. /**
  2331. * Get users inside a course session
  2332. */
  2333. static function get_users_in_course_session($courseId, $id_session, $sort, $direction, $from = null, $limit = null) {
  2334. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2335. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2336. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2337. $courseId = Database::escape_string($courseId);
  2338. $id_session = Database::escape_string($id_session);
  2339. $from = intval($from);
  2340. $limit = intval($limit);
  2341. $is_western_name_order = api_is_western_name_order();
  2342. //Select the number of users
  2343. $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
  2344. FROM $tbl_session_rel_user sru INNER JOIN $tbl_user u ON (u.user_id=sru.id_user)
  2345. LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id = scru.id_user AND scru.c_id = '".$courseId."' )
  2346. WHERE sru.id_session = '$id_session' AND
  2347. sru.moved_to = 0 AND sru.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION." AND
  2348. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH;
  2349. $sql .= " ORDER BY $sort $direction ";
  2350. if (!empty($from) && !empty($limit)) {
  2351. $sql .= " LIMIT $from, $limit";
  2352. }
  2353. $result = Database::query($sql);
  2354. if (Database::num_rows($result)) {
  2355. return Database::store_result($result);
  2356. }
  2357. return false;
  2358. }
  2359. /**
  2360. * @param $courseId
  2361. * @param $id_session
  2362. * @return int|mixed
  2363. */
  2364. static function get_count_users_in_course_session($courseId, $id_session) {
  2365. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2366. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2367. //Select the number of users
  2368. $sql = " SELECT count(*) FROM $tbl_session_rel_user sru, $tbl_session_rel_course_rel_user srcru
  2369. WHERE srcru.id_user = sru.id_user AND
  2370. srcru.id_session = sru.id_session AND
  2371. srcru.c_id = '".Database::escape_string($courseId)."' AND
  2372. srcru.id_session = '".intval($id_session)."' AND
  2373. (sru.moved_to = 0 AND sru.moved_status <> ".SessionManager::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION.") AND
  2374. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH;
  2375. $result = Database::query($sql);
  2376. if (Database::num_rows($result)) {
  2377. return Database::result($result,0,0);
  2378. }
  2379. return 0;
  2380. }
  2381. /**
  2382. * Get the list of coaches (only user ids)
  2383. * @param string course_code
  2384. * @param in session_id
  2385. * @return array
  2386. */
  2387. static function get_session_course_coaches($courseId, $session_id)
  2388. {
  2389. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2390. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2391. // Get coachs of the courses in session
  2392. $sql = "SELECT user.user_id FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  2393. WHERE session_rcru.id_user = user.user_id AND
  2394. session_rcru.id_session = '".intval($session_id)."' AND
  2395. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  2396. session_rcru.status=2";
  2397. $result = Database::query($sql);
  2398. return Database::store_result($result);
  2399. }
  2400. static function get_session_course_coaches_by_user($courseId, $session_id, $user_id)
  2401. {
  2402. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2403. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2404. // Get coachs of the courses in session
  2405. $sql = "SELECT user.user_id FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
  2406. WHERE session_rcru.id_user = user.user_id AND
  2407. session_rcru.id_session = '".intval($session_id)."' AND
  2408. session_rcru.c_id ='".Database::escape_string($courseId)."' AND
  2409. session_rcru.status=2";
  2410. $result = Database::query($sql);
  2411. return Database::store_result($result);
  2412. }
  2413. static function get_session_course_coaches_to_string($courseId, $session_id)
  2414. {
  2415. $coaches = self::get_session_course_coaches($courseId, $session_id);
  2416. if (!empty($coaches)) {
  2417. $coach_list = array();
  2418. foreach ($coaches as $coach_info) {
  2419. $user_info = api_get_user_info($coach_info['user_id']);
  2420. $coach_list[] = $user_info['complete_name'];
  2421. }
  2422. if (!empty($coach_list)) {
  2423. return implode(', ', $coach_list);
  2424. }
  2425. }
  2426. return get_lang('None');
  2427. }
  2428. /**
  2429. * @param $id_session
  2430. * @param $courseId
  2431. */
  2432. static function delete_course_in_session($id_session, $courseId)
  2433. {
  2434. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2435. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2436. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2437. $id_session = intval($id_session);
  2438. $courseId = Database::escape_string($courseId);
  2439. if (!empty($id_session) && !empty($courseId)) {
  2440. $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND c_id = '$courseId'");
  2441. $nbr_affected_rows = Database::affected_rows($result);
  2442. Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id = '$courseId'");
  2443. Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'");
  2444. }
  2445. }
  2446. static function get_session_rel_user_by_moved_to($session_id, $user_id) {
  2447. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2448. $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";
  2449. $result = Database::query($sql);
  2450. if (Database::num_rows($result)) {
  2451. $result = Database::store_result($result,'ASSOC');
  2452. return $result[0];
  2453. }
  2454. return false;
  2455. }
  2456. static function get_coaches_by_keyword($tag) {
  2457. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  2458. $roleRelUser = Database::get_main_table(TABLE_ROLE_USER);
  2459. $role = Database::get_main_table(TABLE_ROLE);
  2460. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
  2461. $select = "SELECT user.user_id, lastname, firstname, username ";
  2462. $sql = " $select FROM $tbl_user user INNER JOIN $roleRelUser ru on (user.user_id = ru.user_id) INNER JOIN $role r on (r.id = ru.role_id)
  2463. WHERE r.role in ('ROLE_ADMIN', 'ROLE_TEACHER') ";
  2464. $tag = Database::escape_string($tag);
  2465. $where_condition = array();
  2466. if (!empty($tag)) {
  2467. $condition = ' LIKE "%'.$tag.'%"';
  2468. $where_condition = array(
  2469. "firstname $condition",
  2470. "lastname $condition",
  2471. "username $condition"
  2472. );
  2473. $where_condition = ' AND ('.implode(' OR ', $where_condition).') ';
  2474. }
  2475. if (api_is_multiple_url_enabled()) {
  2476. $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  2477. $access_url_id = api_get_current_access_url_id();
  2478. if ($access_url_id != -1){
  2479. $sql = $select.' FROM '.$tbl_user.' user
  2480. INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
  2481. WHERE access_url_id = '.$access_url_id.' AND status = 1';
  2482. }
  2483. }
  2484. $sql .= $where_condition.$order_clause;
  2485. $result = Database::query($sql);
  2486. return Database::store_result($result, 'ASSOC');
  2487. }
  2488. /**
  2489. * Returns a human readable string
  2490. * @params array An array with all the session dates
  2491. * @return string
  2492. */
  2493. static function parse_session_dates($session_info)
  2494. {
  2495. //This will clean the variables if 0000-00-00 00:00:00 the variable will be empty
  2496. $start_date = null;
  2497. $end_date = null;
  2498. if (isset($session_info['display_start_date'])) {
  2499. $start_date = api_get_local_time($session_info['display_start_date'], null, null, true);
  2500. }
  2501. if (isset($session_info['display_end_date'])) {
  2502. $end_date = api_get_local_time($session_info['display_end_date'], null, null, true);
  2503. }
  2504. $msg_date = null;
  2505. if (!empty($start_date) && !empty($end_date)) {
  2506. //$msg_date = get_lang('From').' '.$start_date.' '.get_lang('To').' '.$end_date;
  2507. $msg_date = sprintf(get_lang('FromDateXToDateY'), $start_date, $end_date);
  2508. } else {
  2509. if (!empty($start_date)) {
  2510. $msg_date = get_lang('From').' '.$start_date;
  2511. }
  2512. if (!empty($end_date)) {
  2513. $msg_date = get_lang('Until').' '.$end_date;
  2514. }
  2515. }
  2516. return $msg_date;
  2517. }
  2518. public static function get_session_columns($list_type = 'simple') {
  2519. //Column config
  2520. $operators = array('cn', 'nc');
  2521. $date_operators = array('gt', 'ge', 'lt', 'le');
  2522. switch ($list_type) {
  2523. case 'simple':
  2524. $columns = array(
  2525. get_lang('Name'),
  2526. get_lang('SessionDisplayStartDate'),
  2527. get_lang('SessionDisplayEndDate'),
  2528. //get_lang('SessionCategoryName'),
  2529. //get_lang('Coach'),
  2530. //get_lang('Status'),
  2531. get_lang('Visibility'),
  2532. //get_lang('CourseTitle'),
  2533. );
  2534. $column_model = array (
  2535. array('name'=>'name', 'index'=>'name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  2536. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  2537. 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)),
  2538. // array('name'=>'category_name', 'index'=>'category_name', 'hidden' => 'true', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true', 'sopt' => $operators)),
  2539. //array('name'=>'access_start_date', 'index'=>'access_start_date', 'width'=>'60', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true')),
  2540. //array('name'=>'access_end_date', 'index'=>'access_end_date', 'width'=>'60', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true')),
  2541. //array('name'=>'coach_name', 'index'=>'coach_name', 'width'=>'70', 'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
  2542. //array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25', 'align'=>'left', 'search' => 'true', 'stype'=>'select',
  2543. //for the bottom bar
  2544. // 'searchoptions' => array(
  2545. // 'defaultValue' => '1',
  2546. // 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  2547. //for the top bar
  2548. //'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))
  2549. //),
  2550. //array('name'=>'course_code', 'index'=>'course_code', 'width'=>'40', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  2551. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  2552. //array('name'=>'course_title', 'index'=>'course_title', 'width'=>'50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  2553. );
  2554. break;
  2555. case 'complete':
  2556. $columns = array(
  2557. get_lang('Name'),
  2558. get_lang('SessionDisplayStartDate'),
  2559. get_lang('SessionDisplayEndDate'),
  2560. //get_lang('SessionCategoryName'),
  2561. get_lang('Coach'),
  2562. get_lang('Status'),
  2563. get_lang('Visibility'),
  2564. get_lang('CourseTitle'),
  2565. );
  2566. $column_model = array (
  2567. array('name'=>'name', 'index'=>'name', 'width'=>'200', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
  2568. array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
  2569. 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)),
  2570. // array('name'=>'category_name', 'index'=>'category_name', 'hidden' => 'true', 'width'=>'70', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true', 'sopt' => $operators)),
  2571. //array('name'=>'access_start_date', 'index'=>'access_start_date', 'width'=>'60', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true')),
  2572. //array('name'=>'access_end_date', 'index'=>'access_end_date', 'width'=>'60', 'align'=>'left', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true')),
  2573. array('name'=>'coach_name', 'index'=>'coach_name', 'width'=>'70', 'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
  2574. array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25', 'align'=>'left', 'search' => 'true', 'stype'=>'select',
  2575. //for the bottom bar
  2576. 'searchoptions' => array(
  2577. 'defaultValue' => '1',
  2578. 'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
  2579. //for the top bar
  2580. 'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))
  2581. ),
  2582. //array('name'=>'course_code', 'index'=>'course_code', 'width'=>'40', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  2583. array('name'=>'visibility', 'index'=>'visibility', 'width'=>'40', 'align'=>'left', 'search' => 'false'),
  2584. array('name'=>'course_title', 'index'=>'course_title', 'width'=>'50', 'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
  2585. );
  2586. break;
  2587. }
  2588. // Inject extra session fields
  2589. $session_field = new SessionField();
  2590. $rules = $session_field->getRules($columns, $column_model);
  2591. $column_model[] = array('name'=>'actions', 'index'=>'actions', 'width'=>'80', 'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false');
  2592. $columns[] = get_lang('Actions');
  2593. foreach ($column_model as $col_model) {
  2594. $simple_column_name[] = $col_model['name'];
  2595. }
  2596. $return_array = array(
  2597. 'columns' => $columns,
  2598. 'column_model' => $column_model,
  2599. 'rules' => $rules,
  2600. 'simple_column_name' => $simple_column_name
  2601. );
  2602. return $return_array;
  2603. }
  2604. static function getSessionsByCategory($categoryId)
  2605. {
  2606. $categoryId = intval($categoryId);
  2607. $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
  2608. $sql = "select * FROM $tableSession WHERE session_category_id = $categoryId";
  2609. $result = Database::query($sql);
  2610. return Database::store_result($result);
  2611. }
  2612. }