myspace.lib.php 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use CpChart\Chart\Cache as pCache;
  4. use CpChart\Chart\Data as pData;
  5. use CpChart\Chart\Image as pImage;
  6. /**
  7. * Class MySpace
  8. * @package chamilo.reporting
  9. */
  10. class MySpace
  11. {
  12. /**
  13. * Get admin actions
  14. * @return string
  15. */
  16. public static function getAdminActions()
  17. {
  18. $actions = array(
  19. //array('url' => api_get_path(WEB_CODE_PATH).'mySpace/index.php', 'content' => get_lang('Home')),
  20. array(
  21. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php?display=coaches',
  22. 'content' => get_lang('DisplayCoaches'),
  23. ),
  24. array(
  25. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php?display=user',
  26. 'content' => get_lang('DisplayUserOverview'),
  27. ),
  28. array(
  29. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php?display=session',
  30. 'content' => get_lang('DisplaySessionOverview'),
  31. ),
  32. array(
  33. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php?display=course',
  34. 'content' => get_lang('DisplayCourseOverview'),
  35. ),
  36. array(
  37. 'url' => api_get_path(WEB_CODE_PATH).'tracking/question_course_report.php?view=admin',
  38. 'content' => get_lang('LPQuestionListResults'),
  39. ),
  40. array(
  41. 'url' => api_get_path(WEB_CODE_PATH).'tracking/course_session_report.php?view=admin',
  42. 'content' => get_lang('LPExerciseResultsBySession'),
  43. ),
  44. [
  45. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php?display=accessoverview',
  46. 'content' => get_lang('DisplayAccessOverview').' ('.get_lang('Beta').')',
  47. ],
  48. );
  49. return Display::actions($actions, null);
  50. }
  51. public static function getTopMenu()
  52. {
  53. $menu_items = array();
  54. $menu_items[] = Display::url(
  55. Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM),
  56. api_get_path(WEB_CODE_PATH)."auth/my_progress.php"
  57. );
  58. $menu_items[] = Display::url(
  59. Display::return_icon('teacher.png', get_lang('TeacherInterface'), array(), 32),
  60. api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher'
  61. );
  62. $menu_items[] = Display::url(Display::return_icon('star_na.png', get_lang('AdminInterface'), array(), 32), '#');
  63. $menu_items[] = Display::url(
  64. Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), 32),
  65. api_get_path(WEB_CODE_PATH).'tracking/exams.php'
  66. );
  67. $menu = null;
  68. foreach ($menu_items as $item) {
  69. $menu .= $item;
  70. }
  71. $menu .= '<br />';
  72. return $menu;
  73. }
  74. /**
  75. * This function serves exporting data in CSV format.
  76. * @param array $header The header labels.
  77. * @param array $data The data array.
  78. * @param string $file_name The name of the file which contains exported data.
  79. * @return string mixed Returns a message (string) if an error occurred.
  80. */
  81. public function export_csv($header, $data, $file_name = 'export.csv')
  82. {
  83. $archive_path = api_get_path(SYS_ARCHIVE_PATH);
  84. $archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive=';
  85. if (!$open = fopen($archive_path.$file_name, 'w+')) {
  86. $message = get_lang('noOpen');
  87. } else {
  88. $info = '';
  89. foreach ($header as $value) {
  90. $info .= $value.';';
  91. }
  92. $info .= "\r\n";
  93. foreach ($data as $row) {
  94. foreach ($row as $value) {
  95. $info .= $value.';';
  96. }
  97. $info .= "\r\n";
  98. }
  99. fwrite($open, $info);
  100. fclose($open);
  101. @chmod($file_name, api_get_permissions_for_new_files());
  102. header("Location:".$archive_url.$file_name);
  103. }
  104. return $message;
  105. }
  106. /**
  107. * Gets the connections to a course as an array of login and logout time
  108. *
  109. * @param int $userId User id
  110. * @param int $courseId
  111. * @param int $sessionId Session id (optional, default = 0)
  112. * @return array Connections
  113. */
  114. public static function get_connections_to_course($userId, $courseId, $sessionId = 0)
  115. {
  116. // Database table definitions
  117. $tbl_track_course = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  118. // protect data
  119. $userId = (int) $userId;
  120. $courseId = (int) $courseId;
  121. $sessionId = (int) $sessionId;
  122. $sql = 'SELECT login_course_date, logout_course_date
  123. FROM ' . $tbl_track_course . '
  124. WHERE
  125. user_id = '.$userId.' AND
  126. c_id = '.$courseId.' AND
  127. session_id = '.$sessionId.'
  128. ORDER BY login_course_date ASC';
  129. $rs = Database::query($sql);
  130. $connections = array();
  131. while ($row = Database::fetch_array($rs)) {
  132. $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
  133. $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
  134. $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date);
  135. }
  136. return $connections;
  137. }
  138. /**
  139. * @param $user_id
  140. * @param $course_list
  141. * @param int $session_id
  142. * @return array|bool
  143. */
  144. public static function get_connections_from_course_list(
  145. $user_id,
  146. $course_list,
  147. $session_id = 0
  148. ) {
  149. // Database table definitions
  150. $tbl_track_course = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  151. if (empty($course_list)) {
  152. return false;
  153. }
  154. // protect data
  155. $user_id = intval($user_id);
  156. $session_id = intval($session_id);
  157. $new_course_list = array();
  158. foreach ($course_list as $course_item) {
  159. $courseInfo = api_get_course_info($course_item['code']);
  160. $courseId = $courseInfo['real_id'];
  161. $new_course_list[] = '"'.$courseId.'"';
  162. }
  163. $course_list = implode(', ', $new_course_list);
  164. if (empty($course_list)) {
  165. return false;
  166. }
  167. $sql = 'SELECT login_course_date, logout_course_date, c_id
  168. FROM ' . $tbl_track_course . '
  169. WHERE
  170. user_id = '.$user_id.' AND
  171. c_id IN ('.$course_list.') AND
  172. session_id = '.$session_id.'
  173. ORDER BY login_course_date ASC';
  174. $rs = Database::query($sql);
  175. $connections = array();
  176. while ($row = Database::fetch_array($rs)) {
  177. $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
  178. $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
  179. $connections[] = array(
  180. 'login' => $timestamp_login_date,
  181. 'logout' => $timestamp_logout_date,
  182. 'c_id' => $row['c_id']
  183. );
  184. }
  185. return $connections;
  186. }
  187. /**
  188. * Creates a small table in the last column of the table with the user overview
  189. *
  190. * @param integer $user_id the id of the user
  191. * @param array $url_params additonal url parameters
  192. * @param array $row the row information (the other columns)
  193. * @return string html code
  194. */
  195. public static function course_info_tracking_filter($user_id, $url_params, $row)
  196. {
  197. // the table header
  198. $return = '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  199. // database table definition
  200. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  201. // getting all the courses of the user
  202. $sql = "SELECT * FROM $tbl_course_user
  203. WHERE
  204. user_id = '".intval($user_id)."' AND
  205. relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
  206. $result = Database::query($sql);
  207. while ($row = Database::fetch_array($result)) {
  208. $courseInfo = api_get_course_info_by_id($row['c_id']);
  209. if (empty($courseInfo)) {
  210. continue;
  211. }
  212. $courseCode = $courseInfo['code'];
  213. $courseId = $courseInfo['real_id'];
  214. $return .= '<tr>';
  215. // course code
  216. $return .= ' <td width="157px" >'.cut($courseCode, 20, true).'</td>';
  217. // time spent in the course
  218. $return .= ' <td><div>'.api_time_to_hms(Tracking::get_time_spent_on_the_course($user_id, $courseId)).'</div></td>';
  219. // student progress in course
  220. $return .= ' <td><div>'.round(Tracking::get_avg_student_progress($user_id, $courseCode), 2).'</div></td>';
  221. // student score
  222. $avg_score = Tracking::get_avg_student_score($user_id, $courseCode);
  223. if (is_numeric($avg_score)) {
  224. $avg_score = round($avg_score,2);
  225. } else {
  226. $$avg_score = '-';
  227. }
  228. $return .= ' <td><div>'.$avg_score.'</div></td>';
  229. // student tes score
  230. //$return .= ' <td><div style="width:40px">'.round(Tracking::get_avg_student_exercise_score ($user_id, $courseCode),2).'%</div></td>';
  231. // student messages
  232. $return .= ' <td><div>'.Tracking::count_student_messages($user_id, $courseCode).'</div></td>';
  233. // student assignments
  234. $return .= ' <td><div>'.Tracking::count_student_assignments($user_id, $courseCode).'</div></td>';
  235. // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
  236. $exercises_results = self::exercises_results($user_id, $courseCode);
  237. $return .= ' <td width="105px"><div>'.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'</div></td>';
  238. $return .= ' <td><div>'.$exercises_results['questions_answered'].'</div></td>';
  239. $return .= ' <td><div>'.Tracking::get_last_connection_date_on_the_course($user_id, $courseInfo).'</div></td>';
  240. $return .= '<tr>';
  241. }
  242. $return .= '</table>';
  243. return $return;
  244. }
  245. /**
  246. * Display a sortable table that contains an overview off all the
  247. * reporting progress of all users and all courses the user is subscribed to
  248. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  249. * @version Dokeos 1.8.6
  250. * @since October 2008
  251. */
  252. public static function display_tracking_user_overview()
  253. {
  254. self::display_user_overview_export_options();
  255. $t_head = '<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  256. $t_head .= '<tr>';
  257. $t_head .= '<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
  258. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
  259. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
  260. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
  261. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
  262. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
  263. $t_head .= '<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
  264. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
  265. $t_head .= '<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
  266. $t_head .= '</tr></table>';
  267. $addparams = array('view' => 'admin', 'display' => 'user');
  268. $table = new SortableTable(
  269. 'tracking_user_overview',
  270. array('MySpace', 'get_number_of_users_tracking_overview'),
  271. array('MySpace', 'get_user_data_tracking_overview'),
  272. 0
  273. );
  274. $table->additional_parameters = $addparams;
  275. $table->set_header(0, get_lang('OfficialCode'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  276. if (api_is_western_name_order()) {
  277. $table->set_header(1, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  278. $table->set_header(2, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  279. } else {
  280. $table->set_header(1, get_lang('LastName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  281. $table->set_header(2, get_lang('FirstName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  282. }
  283. $table->set_header(3, get_lang('LoginName'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  284. $table->set_header(4, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
  285. $table->set_column_filter(4, array('MySpace','course_info_tracking_filter'));
  286. $table->display();
  287. }
  288. /**
  289. * @param $export_csv
  290. */
  291. public static function display_tracking_coach_overview($export_csv)
  292. {
  293. if ($export_csv) {
  294. $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
  295. } else {
  296. $is_western_name_order = api_is_western_name_order();
  297. }
  298. $sort_by_first_name = api_sort_by_first_name();
  299. $tracking_column = isset($_GET['tracking_list_coaches_column']) ? $_GET['tracking_list_coaches_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
  300. $tracking_direction = (isset($_GET['tracking_list_coaches_direction']) && in_array(strtoupper($_GET['tracking_list_coaches_direction']), array('ASC', 'DESC', 'ASCENDING', 'DESCENDING', '0', '1'))) ? $_GET['tracking_list_coaches_direction'] : 'DESC';
  301. // Prepare array for column order - when impossible, use some of user names.
  302. if ($is_western_name_order) {
  303. $order = array(
  304. 0 => 'firstname',
  305. 1 => 'lastname',
  306. 2 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  307. 3 => 'login_date',
  308. 4 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  309. 5 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  310. );
  311. } else {
  312. $order = array(
  313. 0 => 'lastname',
  314. 1 => 'firstname',
  315. 2 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  316. 3 => 'login_date',
  317. 4 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  318. 5 => ($sort_by_first_name ? 'firstname' : 'lastname'),
  319. );
  320. }
  321. $table = new SortableTable(
  322. 'tracking_list_coaches_myspace',
  323. array('MySpace', 'count_coaches'),
  324. null,
  325. ($is_western_name_order xor $sort_by_first_name) ? 1 : 0
  326. );
  327. $parameters['view'] = 'admin';
  328. $table->set_additional_parameters($parameters);
  329. if ($is_western_name_order) {
  330. $table -> set_header(0, get_lang('FirstName'), true);
  331. $table -> set_header(1, get_lang('LastName'), true);
  332. } else {
  333. $table -> set_header(0, get_lang('LastName'), true);
  334. $table -> set_header(1, get_lang('FirstName'), true);
  335. }
  336. $table -> set_header(2, get_lang('TimeSpentOnThePlatform'), false);
  337. $table -> set_header(3, get_lang('LastConnexion'), false);
  338. $table -> set_header(4, get_lang('NbStudents'), false);
  339. $table -> set_header(5, get_lang('CountCours'), false);
  340. $table -> set_header(6, get_lang('NumberOfSessions'), false);
  341. $table -> set_header(7, get_lang('Sessions'), false);
  342. if ($is_western_name_order) {
  343. $csv_header[] = array (
  344. get_lang('FirstName'),
  345. get_lang('LastName'),
  346. get_lang('TimeSpentOnThePlatform'),
  347. get_lang('LastConnexion'),
  348. get_lang('NbStudents'),
  349. get_lang('CountCours'),
  350. get_lang('NumberOfSessions')
  351. );
  352. } else {
  353. $csv_header[] = array (
  354. get_lang('LastName'),
  355. get_lang('FirstName'),
  356. get_lang('TimeSpentOnThePlatform'),
  357. get_lang('LastConnexion'),
  358. get_lang('NbStudents'),
  359. get_lang('CountCours'),
  360. get_lang('NumberOfSessions')
  361. );
  362. }
  363. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  364. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  365. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  366. $tbl_sessions = Database::get_main_table(TABLE_MAIN_SESSION);
  367. $sqlCoachs = "SELECT DISTINCT
  368. scu.user_id as id_coach,
  369. u.id as user_id,
  370. lastname,
  371. firstname,
  372. MAX(login_date) as login_date
  373. FROM $tbl_user u, $tbl_session_course_user scu, $tbl_track_login
  374. WHERE
  375. scu.user_id = u.id AND scu.status=2 AND login_user_id=u.id
  376. GROUP BY user_id ";
  377. if (api_is_multiple_url_enabled()) {
  378. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  379. $access_url_id = api_get_current_access_url_id();
  380. if ($access_url_id != -1) {
  381. $sqlCoachs = "SELECT DISTINCT
  382. scu.user_id as id_coach,
  383. u.id as user_id,
  384. lastname,
  385. firstname,
  386. MAX(login_date) as login_date
  387. FROM $tbl_user u,
  388. $tbl_session_course_user scu,
  389. $tbl_track_login ,
  390. $tbl_session_rel_access_url session_rel_url
  391. WHERE
  392. scu.user_id = u.id AND
  393. scu.status = 2 AND
  394. login_user_id = u.id AND
  395. access_url_id = $access_url_id AND
  396. session_rel_url.session_id = scu.session_id
  397. GROUP BY u.id";
  398. }
  399. }
  400. if (!empty($order[$tracking_column])) {
  401. $sqlCoachs .= " ORDER BY ".$order[$tracking_column]." ".$tracking_direction;
  402. }
  403. $result_coaches = Database::query($sqlCoachs);
  404. $total_no_coaches = Database::num_rows($result_coaches);
  405. $global_coaches = array();
  406. while ($coach = Database::fetch_array($result_coaches)) {
  407. $global_coaches[$coach['user_id']] = $coach;
  408. }
  409. $sql_session_coach = 'SELECT session.id_coach, u.id as user_id, lastname, firstname, MAX(login_date) as login_date
  410. FROM '.$tbl_user.' u ,'.$tbl_sessions.' as session,'.$tbl_track_login.'
  411. WHERE id_coach = u.id AND login_user_id = u.id
  412. GROUP BY u.id
  413. ORDER BY login_date '.$tracking_direction;
  414. if (api_is_multiple_url_enabled()) {
  415. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  416. $access_url_id = api_get_current_access_url_id();
  417. if ($access_url_id != -1) {
  418. $sql_session_coach = 'SELECT session.id_coach, u.id as user_id, lastname, firstname, MAX(login_date) as login_date
  419. FROM '.$tbl_user.' u ,'.$tbl_sessions.' as session, '.$tbl_track_login.' , '.$tbl_session_rel_access_url.' as session_rel_url
  420. WHERE
  421. id_coach = u.id AND
  422. login_user_id = u.id AND
  423. access_url_id = '.$access_url_id.' AND
  424. session_rel_url.session_id = session.id
  425. GROUP BY u.id
  426. ORDER BY login_date '.$tracking_direction;
  427. }
  428. }
  429. $result_sessions_coach = Database::query($sql_session_coach);
  430. $total_no_coaches += Database::num_rows($result_sessions_coach);
  431. while ($coach = Database::fetch_array($result_sessions_coach)) {
  432. $global_coaches[$coach['user_id']] = $coach;
  433. }
  434. $all_datas = array();
  435. foreach ($global_coaches as $id_coach => $coaches) {
  436. $time_on_platform = api_time_to_hms(Tracking::get_time_spent_on_the_platform($coaches['user_id']));
  437. $last_connection = Tracking::get_last_connection_date($coaches['user_id']);
  438. $nb_students = count(Tracking::get_student_followed_by_coach($coaches['user_id']));
  439. $nb_courses = count(Tracking::get_courses_followed_by_coach($coaches['user_id']));
  440. $nb_sessions = count(Tracking::get_sessions_coached_by_user($coaches['user_id']));
  441. $table_row = array();
  442. if ($is_western_name_order) {
  443. $table_row[] = $coaches['firstname'];
  444. $table_row[] = $coaches['lastname'];
  445. } else {
  446. $table_row[] = $coaches['lastname'];
  447. $table_row[] = $coaches['firstname'];
  448. }
  449. $table_row[] = $time_on_platform;
  450. $table_row[] = $last_connection;
  451. $table_row[] = $nb_students;
  452. $table_row[] = $nb_courses;
  453. $table_row[] = $nb_sessions;
  454. $table_row[] = '<a href="session.php?id_coach='.$coaches['user_id'].'">
  455. '.Display::return_icon('2rightarrow.png').'
  456. </a>';
  457. $all_datas[] = $table_row;
  458. if ($is_western_name_order) {
  459. $csv_content[] = array(
  460. api_html_entity_decode($coaches['firstname'], ENT_QUOTES),
  461. api_html_entity_decode($coaches['lastname'], ENT_QUOTES),
  462. $time_on_platform,
  463. $last_connection,
  464. $nb_students,
  465. $nb_courses,
  466. $nb_sessions
  467. );
  468. } else {
  469. $csv_content[] = array(
  470. api_html_entity_decode($coaches['lastname'], ENT_QUOTES),
  471. api_html_entity_decode($coaches['firstname'], ENT_QUOTES),
  472. $time_on_platform,
  473. $last_connection,
  474. $nb_students,
  475. $nb_courses,
  476. $nb_sessions
  477. );
  478. }
  479. }
  480. if ($tracking_column != 3) {
  481. if ($tracking_direction == 'DESC') {
  482. usort($all_datas, array('MySpace','rsort_users'));
  483. } else {
  484. usort($all_datas, array('MySpace','sort_users'));
  485. }
  486. }
  487. if ($export_csv && $tracking_column != 3) {
  488. usort($csv_content, 'sort_users');
  489. }
  490. if ($export_csv) {
  491. $csv_content = array_merge($csv_header, $csv_content);
  492. }
  493. foreach ($all_datas as $row) {
  494. $table -> addRow($row, 'align="right"');
  495. }
  496. $table -> display();
  497. }
  498. public static function count_coaches() {
  499. global $total_no_coaches;
  500. return $total_no_coaches;
  501. }
  502. public static function sort_users($a, $b) {
  503. return api_strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
  504. }
  505. public static function rsort_users($a, $b) {
  506. return api_strcmp(trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
  507. }
  508. /**
  509. * Display a sortable table that contains an overview off all the progress of the user in a session
  510. * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
  511. */
  512. public static function display_tracking_lp_progress_overview($sessionId = '', $courseId = '', $date_from, $date_to)
  513. {
  514. $course = api_get_course_info_by_id($courseId);
  515. /**
  516. * Column name
  517. * The order is important you need to check the $column variable in the model.ajax.php file
  518. */
  519. $columns = array(
  520. get_lang('Username'),
  521. get_lang('FirstName'),
  522. get_lang('LastName'),
  523. );
  524. //add lessons of course
  525. $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
  526. //create columns array
  527. foreach ($lessons as $lesson_id => $lesson) {
  528. $columns[] = $lesson['name'];
  529. }
  530. $columns[] = get_lang('Total');
  531. /**
  532. * Column config
  533. */
  534. $column_model = array(
  535. array(
  536. 'name' => 'username',
  537. 'index' => 'username',
  538. 'align' => 'left',
  539. 'search' => 'true',
  540. 'wrap_cell' => "true",
  541. ),
  542. array(
  543. 'name' => 'firstname',
  544. 'index' => 'firstname',
  545. 'align' => 'left',
  546. 'search' => 'true',
  547. ),
  548. array(
  549. 'name' => 'lastname',
  550. 'index' => 'lastname',
  551. 'align' => 'left',
  552. 'search' => 'true',
  553. ),
  554. );
  555. // Get dinamic column names
  556. foreach ($lessons as $lesson_id => $lesson) {
  557. $column_model[] = array(
  558. 'name' => $lesson['id'],
  559. 'index' => $lesson['id'],
  560. 'align' => 'left',
  561. 'search' => 'true',
  562. );
  563. }
  564. $column_model[] = array(
  565. 'name' => 'total',
  566. 'index' => 'total',
  567. 'align' => 'left',
  568. 'search' => 'true',
  569. );
  570. $action_links = '';
  571. // jqgrid will use this URL to do the selects
  572. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_session_lp_progress&session_id=' . $sessionId . '&course_id=' . $courseId . '&date_to=' . $date_to . '&date_from=' . $date_from;
  573. //Table Id
  574. $tableId = 'lpProgress';
  575. //Autowidth
  576. $extra_params['autowidth'] = 'true';
  577. //height auto
  578. $extra_params['height'] = 'auto';
  579. $table = Display::grid_js(
  580. $tableId,
  581. $url,
  582. $columns,
  583. $column_model,
  584. $extra_params,
  585. array(),
  586. $action_links,
  587. true
  588. );
  589. $return = '<script>$(function() {'. $table .
  590. 'jQuery("#'.$tableId.'").jqGrid("navGrid","#'.$tableId.'_pager",{view:false, edit:false, add:false, del:false, search:false, excel:true});
  591. jQuery("#'.$tableId.'").jqGrid("navButtonAdd","#'.$tableId.'_pager",{
  592. caption:"",
  593. title:"' . get_lang('ExportExcel') . '",
  594. onClickButton : function () {
  595. jQuery("#'.$tableId.'").jqGrid("excelExport",{"url":"'.$url.'&export_format=xls"});
  596. }
  597. });
  598. });</script>';
  599. $return .= Display::grid_html($tableId);
  600. return $return;
  601. }
  602. /**
  603. * Display a sortable table that contains an overview off all the progress of the user in a session
  604. * @param int $sessionId The session ID
  605. * @param int $courseId The course ID
  606. * @param int $exerciseId The quiz ID
  607. * @param int $answer Answer status (0 = incorrect, 1 = correct, 2 = both)
  608. * @return string HTML array of results formatted for gridJS
  609. * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
  610. */
  611. public static function display_tracking_exercise_progress_overview(
  612. $sessionId = 0,
  613. $courseId = 0,
  614. $exerciseId = 0,
  615. $date_from = null,
  616. $date_to = null
  617. ) {
  618. $date_from = Security::remove_XSS($date_from);
  619. $date_to = Security::remove_XSS($date_to);
  620. /**
  621. * Column names
  622. * The column order is important. Check $column variable in the main/inc/ajax/model.ajax.php file
  623. */
  624. $columns = array(
  625. get_lang('Session'),
  626. get_lang('ExerciseId'),
  627. get_lang('ExerciseName'),
  628. get_lang('Username'),
  629. get_lang('LastName'),
  630. get_lang('FirstName'),
  631. get_lang('Time'),
  632. get_lang('QuestionId'),
  633. get_lang('QuestionTitle'),
  634. get_lang('WorkDescription'),
  635. get_lang('Answer'),
  636. get_lang('Correct')
  637. );
  638. /**
  639. * Column config
  640. */
  641. $column_model = array(
  642. array('name'=>'session', 'index'=>'session', 'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
  643. array('name'=>'exercise_id', 'index'=>'exercise_id', 'align'=>'left', 'search' => 'true'),
  644. array('name'=>'quiz_title', 'index'=>'quiz_title', 'align'=>'left', 'search' => 'true'),
  645. array('name'=>'username', 'index'=>'username', 'align'=>'left', 'search' => 'true'),
  646. array('name'=>'lastname', 'index'=>'lastname', 'align'=>'left', 'search' => 'true'),
  647. array('name'=>'firstname', 'index'=>'firstname', 'align'=>'left', 'search' => 'true'),
  648. array('name'=>'time', 'index'=>'time', 'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
  649. array('name'=>'question_id', 'index'=>'question_id', 'align'=>'left', 'search' => 'true'),
  650. array('name'=>'question', 'index'=>'question', 'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
  651. array('name'=>'description', 'index'=>'description', 'align'=>'left', 'width' => '550', 'search' => 'true', 'wrap_cell' => "true"),
  652. array('name'=>'answer', 'index'=>'answer', 'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
  653. array('name'=>'correct', 'index'=>'correct', 'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
  654. );
  655. //get dynamic column names
  656. // jqgrid will use this URL to do the selects
  657. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_exercise_progress&session_id=' . $sessionId . '&course_id=' . $courseId . '&exercise_id=' . $exerciseId . '&date_to=' . $date_to . '&date_from=' . $date_from;
  658. // Autowidth
  659. $extra_params['autowidth'] = 'true';
  660. // height auto
  661. $extra_params['height'] = 'auto';
  662. $tableId = 'exerciseProgressOverview';
  663. $table = Display::grid_js($tableId, $url, $columns, $column_model, $extra_params, array(), '', true);
  664. $return = '<script>$(function() {'. $table .
  665. 'jQuery("#'.$tableId.'").jqGrid("navGrid","#'.$tableId.'_pager",{view:false, edit:false, add:false, del:false, search:false, excel:true});
  666. jQuery("#'.$tableId.'").jqGrid("navButtonAdd","#'.$tableId.'_pager",{
  667. caption:"",
  668. title:"' . get_lang('ExportExcel') . '",
  669. onClickButton : function () {
  670. jQuery("#'.$tableId.'").jqGrid("excelExport",{"url":"'.$url.'&export_format=xls"});
  671. }
  672. });
  673. });</script>';
  674. $return .= Display::grid_html($tableId);
  675. return $return;
  676. }
  677. /**
  678. * Displays a form with all the additionally defined user fields of the profile
  679. * and give you the opportunity to include these in the CSV export
  680. *
  681. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  682. * @version 1.8.6
  683. * @since November 2008
  684. */
  685. public static function display_user_overview_export_options()
  686. {
  687. $message = '';
  688. // include the user manager and formvalidator library
  689. if (isset($_GET['export']) && $_GET['export'] == 'options') {
  690. // get all the defined extra fields
  691. $extrafields = UserManager::get_extra_fields(
  692. 0,
  693. 50,
  694. 5,
  695. 'ASC',
  696. false,
  697. 1
  698. );
  699. // creating the form with all the defined extra fields
  700. $form = new FormValidator(
  701. 'exportextrafields',
  702. 'post',
  703. api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export'])
  704. );
  705. if (is_array($extrafields) && count($extrafields) > 0) {
  706. foreach ($extrafields as $key => $extra) {
  707. $form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
  708. }
  709. $form->addButtonSave(get_lang('Ok'), 'submit');
  710. // setting the default values for the form that contains all the extra fields
  711. if (is_array($_SESSION['additional_export_fields'])) {
  712. foreach ($_SESSION['additional_export_fields'] as $key => $value) {
  713. $defaults['extra_export_field'.$value] = 1;
  714. }
  715. }
  716. $form->setDefaults($defaults);
  717. } else {
  718. $form->addElement('html', Display::display_warning_message(get_lang('ThereAreNotExtrafieldsAvailable')));
  719. }
  720. if ($form->validate()) {
  721. // exporting the form values
  722. $values = $form->exportValues();
  723. // re-initialising the session that contains the additional fields that need to be exported
  724. $_SESSION['additional_export_fields'] = array();
  725. // adding the fields that are checked to the session
  726. $message = '';
  727. foreach ($values as $field_ids => $value) {
  728. if ($value == 1 && strstr($field_ids,'extra_export_field')) {
  729. $_SESSION['additional_export_fields'][] = str_replace('extra_export_field', '', $field_ids);
  730. }
  731. }
  732. // adding the fields that will be also exported to a message string
  733. if (is_array($_SESSION['additional_export_fields'])) {
  734. foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
  735. $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
  736. }
  737. }
  738. // Displaying a feedback message
  739. if (!empty($_SESSION['additional_export_fields'])) {
  740. Display::display_confirmation_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
  741. } else {
  742. Display::display_confirmation_message(get_lang('NoAdditionalFieldsWillBeExported'), false);
  743. }
  744. } else {
  745. $form->display();
  746. }
  747. } else {
  748. if (!empty($_SESSION['additional_export_fields'])) {
  749. // get all the defined extra fields
  750. $extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  751. foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
  752. $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
  753. }
  754. Display::display_normal_message(get_lang('FollowingFieldsWillAlsoBeExported').': <br /><ul>'.$message.'</ul>', false);
  755. }
  756. }
  757. }
  758. /**
  759. * Display a sortable table that contains an overview of all the reporting progress of all courses
  760. */
  761. public static function display_tracking_course_overview()
  762. {
  763. $t_head = '<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  764. $t_head .= '<tr>';
  765. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
  766. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
  767. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
  768. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
  769. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
  770. $t_head .= '<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
  771. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
  772. $t_head .= '<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
  773. $t_head .= '</tr></table>';
  774. $addparams = array('view' => 'admin', 'display' => 'courseoverview');
  775. $table = new SortableTable(
  776. 'tracking_session_overview',
  777. array('MySpace', 'get_total_number_courses'),
  778. array('MySpace', 'get_course_data_tracking_overview'),
  779. 1
  780. );
  781. $table->additional_parameters = $addparams;
  782. $table->set_header(0, '', false, null, array('style' => 'display: none'));
  783. $table->set_header(1, get_lang('Course'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  784. $table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
  785. $table->set_column_filter(2, array('MySpace','course_tracking_filter'));
  786. $table->display();
  787. }
  788. /**
  789. * Get the total number of courses
  790. *
  791. * @return integer Total number of courses
  792. */
  793. public static function get_total_number_courses()
  794. {
  795. return CourseManager::count_courses(api_get_current_access_url_id());
  796. }
  797. /**
  798. * Get data for the courses
  799. *
  800. * @param int $from Inferior limit
  801. * @param int $numberItems Number of items to select
  802. * @param string $column Column to order on
  803. * @param string $direction Order direction
  804. * @return array Results
  805. */
  806. public static function get_course_data_tracking_overview($from, $numberItems, $column, $direction)
  807. {
  808. $courses = CourseManager::get_courses_list(
  809. $from,
  810. $numberItems,
  811. $column,
  812. $direction,
  813. -1,
  814. '',
  815. api_get_current_access_url_id()
  816. );
  817. $list = [];
  818. foreach ($courses as $course) {
  819. $list[] = [
  820. '0' => $course['code'],
  821. 'col0' => $course['code'],
  822. '1' => $course['title'],
  823. 'col1' => $course['title']
  824. ];
  825. }
  826. return $list;
  827. }
  828. /**
  829. * Fills in course reporting data
  830. *
  831. * @param integer course code
  832. * @param array $url_params additional url parameters
  833. * @param array $row the row information (the other columns)
  834. * @return string html code
  835. */
  836. public static function course_tracking_filter($course_code, $url_params, $row)
  837. {
  838. $course_code = $row[0];
  839. $courseInfo = api_get_course_info($course_code);
  840. $courseId = $courseInfo['real_id'];
  841. // the table header
  842. $return = '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  843. // database table definition
  844. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  845. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  846. // getting all the courses of the user
  847. $sql = "SELECT *
  848. FROM $tbl_user AS u
  849. INNER JOIN $tbl_course_rel_user AS cu
  850. ON cu.user_id = u.user_id
  851. WHERE cu.c_id = '".$courseId."'";
  852. $result = Database::query($sql);
  853. $time_spent = 0;
  854. $progress = 0;
  855. $nb_progress_lp = 0;
  856. $score = 0;
  857. $nb_score_lp = 0;
  858. $nb_messages = 0;
  859. $nb_assignments = 0;
  860. $last_login_date = false;
  861. $total_score_obtained = 0;
  862. $total_score_possible = 0;
  863. $total_questions_answered = 0;
  864. while ($row = Database::fetch_object($result)) {
  865. // get time spent in the course and session
  866. $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $courseInfo['real_id']);
  867. $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
  868. $progress += $progress_tmp[0];
  869. $nb_progress_lp += $progress_tmp[1];
  870. $score_tmp = Tracking::get_avg_student_score($row->user_id, $course_code, array(), null, true);
  871. if(is_array($score_tmp)) {
  872. $score += $score_tmp[0];
  873. $nb_score_lp += $score_tmp[1];
  874. }
  875. $nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
  876. $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
  877. $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course($row->user_id, $courseInfo, null, false);
  878. if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned
  879. $last_login_date = $last_login_date_tmp;
  880. } else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned.
  881. // Find the max and assign it to first_login_date
  882. if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
  883. $last_login_date = $last_login_date_tmp;
  884. }
  885. }
  886. $exercise_results_tmp = self::exercises_results($row->user_id, $course_code);
  887. $total_score_obtained += $exercise_results_tmp['score_obtained'];
  888. $total_score_possible += $exercise_results_tmp['score_possible'];
  889. $total_questions_answered += $exercise_results_tmp['questions_answered'];
  890. }
  891. if ($nb_progress_lp > 0) {
  892. $avg_progress = round($progress / $nb_progress_lp, 2);
  893. } else {
  894. $avg_progress = 0;
  895. }
  896. if ($nb_score_lp > 0) {
  897. $avg_score = round($score / $nb_score_lp, 2);
  898. } else {
  899. $avg_score = '-';
  900. }
  901. if ($last_login_date) {
  902. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
  903. } else {
  904. $last_login_date = '-';
  905. }
  906. if ($total_score_possible > 0) {
  907. $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
  908. } else {
  909. $total_score_percentage = 0;
  910. }
  911. if ($total_score_percentage > 0) {
  912. $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
  913. } else {
  914. $total_score = '-';
  915. }
  916. $return .= '<tr>';
  917. // time spent in the course
  918. $return .= ' <td style="width:164px;">'.api_time_to_hms($time_spent).'</td>';
  919. // student progress in course
  920. $return .= ' <td>'.$avg_progress.'</td>';
  921. // student score
  922. $return .= ' <td>'.$avg_score.'</td>';
  923. // student messages
  924. $return .= ' <td>'.$nb_messages.'</td>';
  925. // student assignments
  926. $return .= ' <td>'.$nb_assignments.'</td>';
  927. // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
  928. $return .= '<td width="105px;">'.$total_score.'</td>';
  929. $return .= '<td>'.$total_questions_answered.'</td>';
  930. // last connection
  931. $return .= ' <td>'.$last_login_date.'</td>';
  932. $return .= '</tr>';
  933. $return .= '</table>';
  934. return $return;
  935. }
  936. /**
  937. * This function exports the table that we see in display_tracking_course_overview()
  938. *
  939. */
  940. public static function export_tracking_course_overview()
  941. {
  942. // database table definition
  943. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  944. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  945. // the values of the sortable table
  946. if ($_GET['tracking_course_overview_page_nr']) {
  947. $from = $_GET['tracking_course_overview_page_nr'];
  948. } else {
  949. $from = 0;
  950. }
  951. if ($_GET['tracking_course_overview_column']) {
  952. $orderby = $_GET['tracking_course_overview_column'];
  953. } else {
  954. $orderby = 0;
  955. }
  956. if ($_GET['tracking_course_overview_direction']) {
  957. $direction = $_GET['tracking_course_overview_direction'];
  958. } else {
  959. $direction = 'ASC';
  960. }
  961. $course_data = self::get_course_data_tracking_overview($from, 1000, $orderby, $direction);
  962. $csv_content = array();
  963. // the first line of the csv file with the column headers
  964. $csv_row = array();
  965. $csv_row[] = get_lang('Course');
  966. $csv_row[] = get_lang('AvgTimeSpentInTheCourse');
  967. $csv_row[] = get_lang('AvgStudentsProgress');
  968. $csv_row[] = get_lang('AvgCourseScore');
  969. $csv_row[] = get_lang('TotalNumberOfMessages');
  970. $csv_row[] = get_lang('TotalNumberOfAssignments');
  971. $csv_row[] = get_lang('TotalExercisesScoreObtained');
  972. $csv_row[] = get_lang('TotalExercisesScorePossible');
  973. $csv_row[] = get_lang('TotalExercisesAnswered');
  974. $csv_row[] = get_lang('TotalExercisesScorePercentage');
  975. $csv_row[] = get_lang('LatestLogin');
  976. $csv_content[] = $csv_row;
  977. // the other lines (the data)
  978. foreach ($course_data as $key => $course) {
  979. $course_code = $course[0];
  980. $courseInfo = api_get_course_info($course_code);
  981. $course_title = $courseInfo['title'];
  982. $courseId = $courseInfo['real_id'];
  983. $csv_row = array();
  984. $csv_row[] = $course_title;
  985. // getting all the courses of the session
  986. $sql = "SELECT *
  987. FROM $tbl_user AS u
  988. INNER JOIN $tbl_course_rel_user AS cu
  989. ON cu.user_id = u.user_id
  990. WHERE cu.c_id = '".$courseId."'";
  991. $result = Database::query($sql);
  992. $time_spent = 0;
  993. $progress = 0;
  994. $nb_progress_lp = 0;
  995. $score = 0;
  996. $nb_score_lp = 0;
  997. $nb_messages = 0;
  998. $nb_assignments = 0;
  999. $last_login_date = false;
  1000. $total_score_obtained = 0;
  1001. $total_score_possible = 0;
  1002. $total_questions_answered = 0;
  1003. while ($row = Database::fetch_object($result)) {
  1004. // get time spent in the course and session
  1005. $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $courseId);
  1006. $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true);
  1007. $progress += $progress_tmp[0];
  1008. $nb_progress_lp += $progress_tmp[1];
  1009. $score_tmp = Tracking::get_avg_student_score($row->user_id, $course_code, array(), null, true);
  1010. if(is_array($score_tmp)) {
  1011. $score += $score_tmp[0];
  1012. $nb_score_lp += $score_tmp[1];
  1013. }
  1014. $nb_messages += Tracking::count_student_messages($row->user_id, $course_code);
  1015. $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code);
  1016. $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course($row->user_id, $courseInfo, null, false);
  1017. if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
  1018. $last_login_date = $last_login_date_tmp;
  1019. } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
  1020. // Find the max and assign it to first_login_date
  1021. if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
  1022. $last_login_date = $last_login_date_tmp;
  1023. }
  1024. }
  1025. $exercise_results_tmp = self::exercises_results($row->user_id, $course_code);
  1026. $total_score_obtained += $exercise_results_tmp['score_obtained'];
  1027. $total_score_possible += $exercise_results_tmp['score_possible'];
  1028. $total_questions_answered += $exercise_results_tmp['questions_answered'];
  1029. }
  1030. if($nb_progress_lp > 0) {
  1031. $avg_progress = round($progress / $nb_progress_lp, 2);
  1032. } else {
  1033. $avg_progress = 0;
  1034. }
  1035. if($nb_score_lp > 0) {
  1036. $avg_score = round($score / $nb_score_lp, 2);
  1037. } else {
  1038. $avg_score = '-';
  1039. }
  1040. if($last_login_date) {
  1041. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
  1042. } else {
  1043. $last_login_date = '-';
  1044. }
  1045. if($total_score_possible > 0) {
  1046. $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
  1047. } else {
  1048. $total_score_percentage = 0;
  1049. }
  1050. // time spent in the course
  1051. $csv_row[] = api_time_to_hms($time_spent);
  1052. // student progress in course
  1053. $csv_row[] = $avg_progress;
  1054. // student score
  1055. $csv_row[] = $avg_score;
  1056. // student messages
  1057. $csv_row[] = $nb_messages;
  1058. // student assignments
  1059. $csv_row[] = $nb_assignments;
  1060. // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
  1061. $csv_row[] = $total_score_obtained;
  1062. $csv_row[] = $total_score_possible;
  1063. $csv_row[] = $total_questions_answered;
  1064. $csv_row[] = $total_score_percentage;
  1065. // last connection
  1066. $csv_row[] = $last_login_date;
  1067. $csv_content[] = $csv_row;
  1068. }
  1069. Export::arrayToCsv($csv_content, 'reporting_course_overview');
  1070. exit;
  1071. }
  1072. /**
  1073. * Display a sortable table that contains an overview of all the reporting
  1074. * progress of all sessions and all courses the user is subscribed to
  1075. * @author Guillaume Viguier <guillaume@viguierjust.com>
  1076. */
  1077. public static function display_tracking_session_overview()
  1078. {
  1079. $t_head = '<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  1080. $t_head .= '<tr>';
  1081. $t_head .= '<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
  1082. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgTimeSpentInTheCourse'), 6, true).'</span></th>';
  1083. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgStudentsProgress'), 6, true).'</span></th>';
  1084. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('AvgCourseScore'), 6, true).'</span></th>';
  1085. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfMessages'), 6, true).'</span></th>';
  1086. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalNumberOfAssignments'), 6, true).'</span></th>';
  1087. $t_head .= '<th width="105px" style="border-bottom:0"><span>'.get_lang('TotalExercisesScoreObtained').'</span></th>';
  1088. $t_head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('TotalExercisesAnswered'), 6, true).'</span></th>';
  1089. $t_head .= '<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('LatestLogin').'</span></th>';
  1090. $t_head .= '</tr></table>';
  1091. $addparams = array('view' => 'admin', 'display' => 'sessionoverview');
  1092. $table = new SortableTable(
  1093. 'tracking_session_overview',
  1094. array('MySpace', 'get_total_number_sessions'),
  1095. array('MySpace', 'get_session_data_tracking_overview'),
  1096. 1
  1097. );
  1098. $table->additional_parameters = $addparams;
  1099. $table->set_header(0, '', false, null, array('style' => 'display: none'));
  1100. $table->set_header(1, get_lang('Session'), true, array('style' => 'font-size:8pt'), array('style' => 'font-size:8pt'));
  1101. $table->set_header(2, $t_head, false, array('style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'), array('style' => 'width:90%;padding:0;font-size:7.5pt;'));
  1102. $table->set_column_filter(2, array('MySpace', 'session_tracking_filter'));
  1103. $table->display();
  1104. }
  1105. /**
  1106. * Get the total number of sessions
  1107. *
  1108. * @return integer Total number of sessions
  1109. */
  1110. public static function get_total_number_sessions()
  1111. {
  1112. return SessionManager::count_sessions(api_get_current_access_url_id());
  1113. }
  1114. /**
  1115. * Get data for the sessions
  1116. *
  1117. * @param int $from Inferior limit
  1118. * @param int $numberItems Number of items to select
  1119. * @param string $column Column to order on
  1120. * @param string $direction Order direction
  1121. * @return array Results
  1122. */
  1123. public static function get_session_data_tracking_overview($from, $numberItems, $column, $direction)
  1124. {
  1125. $from = (int) $from;
  1126. $numberItems = (int) $numberItems;
  1127. $direction = Database::escape_string($direction);
  1128. $columnName = 'name';
  1129. if ($column === 1) {
  1130. $columnName = 'id';
  1131. }
  1132. $options = [
  1133. 'order' => " $columnName $direction",
  1134. 'limit' => " $from,$numberItems"
  1135. ];
  1136. $sessions = SessionManager::get_sessions_admin($options);
  1137. $list = [];
  1138. foreach ($sessions as $session) {
  1139. $list[] = [
  1140. '0' => $session['id'],
  1141. 'col0' => $session['id'],
  1142. '1' => strip_tags($session['name']),
  1143. 'col1' => strip_tags($session['name'])
  1144. ];
  1145. }
  1146. return $list;
  1147. }
  1148. /**
  1149. * Fills in session reporting data
  1150. *
  1151. * @param integer $user_id the id of the user
  1152. * @param array $url_params additonal url parameters
  1153. * @param array $row the row information (the other columns)
  1154. * @return string html code
  1155. */
  1156. public static function session_tracking_filter($session_id, $url_params, $row)
  1157. {
  1158. $session_id = $row[0];
  1159. // the table header
  1160. $return = '<table class="data_table" style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
  1161. // database table definition
  1162. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1163. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1164. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1165. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1166. // getting all the courses of the user
  1167. $sql = "SELECT * FROM $tbl_course AS c
  1168. INNER JOIN $tbl_session_rel_course AS sc
  1169. ON sc.c_id = c.id
  1170. WHERE sc.session_id = '".$session_id."'";
  1171. $result = Database::query($sql);
  1172. while ($row = Database::fetch_object($result)) {
  1173. $courseId = $row->c_id;
  1174. $courseInfo = api_get_course_info_by_id($courseId);
  1175. $return .= '<tr>';
  1176. // course code
  1177. $return .= ' <td width="157px" >'.$row->title.'</td>';
  1178. // get the users in the course
  1179. $sql = "SELECT u.user_id
  1180. FROM $tbl_user AS u
  1181. INNER JOIN $tbl_session_rel_course_rel_user AS scu
  1182. ON u.user_id = scu.user_id
  1183. WHERE scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'";
  1184. $result_users = Database::query($sql);
  1185. $time_spent = 0;
  1186. $progress = 0;
  1187. $nb_progress_lp = 0;
  1188. $score = 0;
  1189. $nb_score_lp = 0;
  1190. $nb_messages = 0;
  1191. $nb_assignments = 0;
  1192. $last_login_date = false;
  1193. $total_score_obtained = 0;
  1194. $total_score_possible = 0;
  1195. $total_questions_answered = 0;
  1196. while ($row_user = Database::fetch_object($result_users)) {
  1197. // get time spent in the course and session
  1198. $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id);
  1199. $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
  1200. $progress += $progress_tmp[0];
  1201. $nb_progress_lp += $progress_tmp[1];
  1202. $score_tmp = Tracking::get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
  1203. if (is_array($score_tmp)) {
  1204. $score += $score_tmp[0];
  1205. $nb_score_lp += $score_tmp[1];
  1206. }
  1207. $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id);
  1208. $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id);
  1209. $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course($row_user->user_id, $courseInfo, $session_id, false);
  1210. if ($last_login_date_tmp != false && $last_login_date == false) {
  1211. // TODO: To be cleaned.
  1212. $last_login_date = $last_login_date_tmp;
  1213. } else if($last_login_date_tmp != false && $last_login_date != false) {
  1214. // TODO: Repeated previous condition! To be cleaned.
  1215. // Find the max and assign it to first_login_date
  1216. if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
  1217. $last_login_date = $last_login_date_tmp;
  1218. }
  1219. }
  1220. $exercise_results_tmp = self::exercises_results($row_user->user_id, $row->code, $session_id);
  1221. $total_score_obtained += $exercise_results_tmp['score_obtained'];
  1222. $total_score_possible += $exercise_results_tmp['score_possible'];
  1223. $total_questions_answered += $exercise_results_tmp['questions_answered'];
  1224. }
  1225. if ($nb_progress_lp > 0) {
  1226. $avg_progress = round($progress / $nb_progress_lp, 2);
  1227. } else {
  1228. $avg_progress = 0;
  1229. }
  1230. if ($nb_score_lp > 0) {
  1231. $avg_score = round($score / $nb_score_lp, 2);
  1232. } else {
  1233. $avg_score = '-';
  1234. }
  1235. if ($last_login_date) {
  1236. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
  1237. } else {
  1238. $last_login_date = '-';
  1239. }
  1240. if ($total_score_possible > 0) {
  1241. $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
  1242. } else {
  1243. $total_score_percentage = 0;
  1244. }
  1245. if ($total_score_percentage > 0) {
  1246. $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
  1247. } else {
  1248. $total_score = '-';
  1249. }
  1250. // time spent in the course
  1251. $return .= ' <td><div>'.api_time_to_hms($time_spent).'</div></td>';
  1252. // student progress in course
  1253. $return .= ' <td><div>'.$avg_progress.'</div></td>';
  1254. // student score
  1255. $return .= ' <td><div>'.$avg_score.'</div></td>';
  1256. // student messages
  1257. $return .= ' <td><div>'.$nb_messages.'</div></td>';
  1258. // student assignments
  1259. $return .= ' <td><div>'.$nb_assignments.'</div></td>';
  1260. // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
  1261. $return .= '<td width="105px;">'.$total_score.'</td>';
  1262. $return .= '<td>'.$total_questions_answered.'</td>';
  1263. // last connection
  1264. $return .= ' <td><div>'.$last_login_date.'</div></td>';
  1265. $return .= '<tr>';
  1266. }
  1267. $return .= '</table>';
  1268. return $return;
  1269. }
  1270. /**
  1271. * This function exports the table that we see in display_tracking_session_overview()
  1272. *
  1273. */
  1274. public static function export_tracking_session_overview()
  1275. {
  1276. // database table definition
  1277. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1278. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1279. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1280. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1281. // the values of the sortable table
  1282. if ($_GET['tracking_session_overview_page_nr']) {
  1283. $from = $_GET['tracking_session_overview_page_nr'];
  1284. } else {
  1285. $from = 0;
  1286. }
  1287. if ($_GET['tracking_session_overview_column']) {
  1288. $orderby = $_GET['tracking_session_overview_column'];
  1289. } else {
  1290. $orderby = 0;
  1291. }
  1292. if ($_GET['tracking_session_overview_direction']) {
  1293. $direction = $_GET['tracking_session_overview_direction'];
  1294. } else {
  1295. $direction = 'ASC';
  1296. }
  1297. $session_data = self::get_session_data_tracking_overview($from, 1000, $orderby, $direction);
  1298. $csv_content = array();
  1299. // the first line of the csv file with the column headers
  1300. $csv_row = array();
  1301. $csv_row[] = get_lang('Session');
  1302. $csv_row[] = get_lang('Course');
  1303. $csv_row[] = get_lang('AvgTimeSpentInTheCourse');
  1304. $csv_row[] = get_lang('AvgStudentsProgress');
  1305. $csv_row[] = get_lang('AvgCourseScore');
  1306. $csv_row[] = get_lang('TotalNumberOfMessages');
  1307. $csv_row[] = get_lang('TotalNumberOfAssignments');
  1308. $csv_row[] = get_lang('TotalExercisesScoreObtained');
  1309. $csv_row[] = get_lang('TotalExercisesScorePossible');
  1310. $csv_row[] = get_lang('TotalExercisesAnswered');
  1311. $csv_row[] = get_lang('TotalExercisesScorePercentage');
  1312. $csv_row[] = get_lang('LatestLogin');
  1313. $csv_content[] = $csv_row;
  1314. // the other lines (the data)
  1315. foreach ($session_data as $key => $session) {
  1316. $session_id = $session[0];
  1317. $session_title = $session[1];
  1318. // getting all the courses of the session
  1319. $sql = "SELECT * FROM $tbl_course AS c
  1320. INNER JOIN $tbl_session_rel_course AS sc
  1321. ON sc.c_id = c.id
  1322. WHERE sc.session_id = '".$session_id."';";
  1323. $result = Database::query($sql);
  1324. while ($row = Database::fetch_object($result)) {
  1325. $courseId = $row->c_id;
  1326. $courseInfo = api_get_course_info_by_id($courseId);
  1327. $csv_row = array();
  1328. $csv_row[] = $session_title;
  1329. $csv_row[] = $row->title;
  1330. // get the users in the course
  1331. $sql = "SELECT scu.user_id
  1332. FROM $tbl_user AS u
  1333. INNER JOIN $tbl_session_rel_course_rel_user AS scu
  1334. ON u.user_id = scu.user_id
  1335. WHERE scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'";
  1336. $result_users = Database::query($sql);
  1337. $time_spent = 0;
  1338. $progress = 0;
  1339. $nb_progress_lp = 0;
  1340. $score = 0;
  1341. $nb_score_lp = 0;
  1342. $nb_messages = 0;
  1343. $nb_assignments = 0;
  1344. $last_login_date = false;
  1345. $total_score_obtained = 0;
  1346. $total_score_possible = 0;
  1347. $total_questions_answered = 0;
  1348. while($row_user = Database::fetch_object($result_users)) {
  1349. // get time spent in the course and session
  1350. $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id);
  1351. $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true);
  1352. $progress += $progress_tmp[0];
  1353. $nb_progress_lp += $progress_tmp[1];
  1354. $score_tmp = Tracking::get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true);
  1355. if (is_array($score_tmp)) {
  1356. $score += $score_tmp[0];
  1357. $nb_score_lp += $score_tmp[1];
  1358. }
  1359. $nb_messages += Tracking::count_student_messages(
  1360. $row_user->user_id,
  1361. $row->code,
  1362. $session_id
  1363. );
  1364. $nb_assignments += Tracking::count_student_assignments(
  1365. $row_user->user_id,
  1366. $row->code,
  1367. $session_id
  1368. );
  1369. $last_login_date_tmp = Tracking:: get_last_connection_date_on_the_course(
  1370. $row_user->user_id,
  1371. $courseInfo,
  1372. $session_id,
  1373. false
  1374. );
  1375. if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned.
  1376. $last_login_date = $last_login_date_tmp;
  1377. } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned.
  1378. // Find the max and assign it to first_login_date
  1379. if(strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
  1380. $last_login_date = $last_login_date_tmp;
  1381. }
  1382. }
  1383. $exercise_results_tmp = self::exercises_results($row_user->user_id, $row->code, $session_id);
  1384. $total_score_obtained += $exercise_results_tmp['score_obtained'];
  1385. $total_score_possible += $exercise_results_tmp['score_possible'];
  1386. $total_questions_answered += $exercise_results_tmp['questions_answered'];
  1387. }
  1388. if($nb_progress_lp > 0) {
  1389. $avg_progress = round($progress / $nb_progress_lp, 2);
  1390. } else {
  1391. $avg_progress = 0;
  1392. }
  1393. if($nb_score_lp > 0) {
  1394. $avg_score = round($score / $nb_score_lp, 2);
  1395. } else {
  1396. $avg_score = '-';
  1397. }
  1398. if($last_login_date) {
  1399. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT, date_default_timezone_get());
  1400. } else {
  1401. $last_login_date = '-';
  1402. }
  1403. if($total_score_possible > 0) {
  1404. $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
  1405. } else {
  1406. $total_score_percentage = 0;
  1407. }
  1408. if($total_score_percentage > 0) {
  1409. $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
  1410. } else {
  1411. $total_score = '-';
  1412. }
  1413. // time spent in the course
  1414. $csv_row[] = api_time_to_hms($time_spent);
  1415. // student progress in course
  1416. $csv_row[] = $avg_progress;
  1417. // student score
  1418. $csv_row[] = $avg_score;
  1419. // student messages
  1420. $csv_row[] = $nb_messages;
  1421. // student assignments
  1422. $csv_row[] = $nb_assignments;
  1423. // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
  1424. $csv_row[] = $total_score_obtained;
  1425. $csv_row[] = $total_score_possible;
  1426. $csv_row[] = $total_questions_answered;
  1427. $csv_row[] = $total_score_percentage;
  1428. // last connection
  1429. $csv_row[] = $last_login_date;
  1430. $csv_content[] = $csv_row;
  1431. }
  1432. }
  1433. Export::arrayToCsv($csv_content, 'reporting_session_overview');
  1434. exit;
  1435. }
  1436. /**
  1437. * Get general information about the exercise performance of the user
  1438. * the total obtained score (all the score on all the questions)
  1439. * the maximum score that could be obtained
  1440. * the number of questions answered
  1441. * the success percentage
  1442. * @param integer $user_id the id of the user
  1443. * @param string $course_code the course code
  1444. * @return array
  1445. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1446. * @version Dokeos 1.8.6
  1447. * @since November 2008
  1448. */
  1449. public static function exercises_results($user_id, $course_code, $session_id = false)
  1450. {
  1451. $courseId = api_get_course_int_id($course_code);
  1452. $sql = 'SELECT exe_result, exe_weighting
  1453. FROM '.Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES)."
  1454. WHERE
  1455. c_id = ' . $courseId . ' AND
  1456. exe_user_id = '".intval($user_id)."'";
  1457. if ($session_id !== false) {
  1458. $sql .= " AND session_id = '".$session_id."' ";
  1459. }
  1460. $result = Database::query($sql);
  1461. $score_obtained = 0;
  1462. $score_possible = 0;
  1463. $questions_answered = 0;
  1464. while ($row = Database::fetch_array($result)) {
  1465. $score_obtained += $row['exe_result'];
  1466. $score_possible += $row['exe_weighting'];
  1467. $questions_answered ++;
  1468. }
  1469. if ($score_possible != 0) {
  1470. $percentage = round(($score_obtained / $score_possible * 100), 2);
  1471. } else {
  1472. $percentage = null;
  1473. }
  1474. return array(
  1475. 'score_obtained' => $score_obtained,
  1476. 'score_possible' => $score_possible,
  1477. 'questions_answered' => $questions_answered,
  1478. 'percentage' => $percentage
  1479. );
  1480. }
  1481. /**
  1482. * This function exports the table that we see in display_tracking_user_overview()
  1483. *
  1484. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1485. * @version Dokeos 1.8.6
  1486. * @since October 2008
  1487. */
  1488. public static function export_tracking_user_overview()
  1489. {
  1490. // database table definitions
  1491. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1492. $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
  1493. // the values of the sortable table
  1494. if ($_GET['tracking_user_overview_page_nr']) {
  1495. $from = $_GET['tracking_user_overview_page_nr'];
  1496. } else {
  1497. $from = 0;
  1498. }
  1499. if ($_GET['tracking_user_overview_column']) {
  1500. $orderby = $_GET['tracking_user_overview_column'];
  1501. } else {
  1502. $orderby = 0;
  1503. }
  1504. if ($is_western_name_order != api_is_western_name_order() && ($orderby == 1 || $orderby == 2)) {
  1505. // Swapping the sorting column if name order for export is different than the common name order.
  1506. $orderby = 3 - $orderby;
  1507. }
  1508. if ($_GET['tracking_user_overview_direction']) {
  1509. $direction = $_GET['tracking_user_overview_direction'];
  1510. } else {
  1511. $direction = 'ASC';
  1512. }
  1513. $user_data = self::get_user_data_tracking_overview($from, 1000, $orderby, $direction);
  1514. // the first line of the csv file with the column headers
  1515. $csv_row = array();
  1516. $csv_row[] = get_lang('OfficialCode');
  1517. if ($is_western_name_order) {
  1518. $csv_row[] = get_lang('FirstName', '');
  1519. $csv_row[] = get_lang('LastName', '');
  1520. } else {
  1521. $csv_row[] = get_lang('LastName', '');
  1522. $csv_row[] = get_lang('FirstName', '');
  1523. }
  1524. $csv_row[] = get_lang('LoginName');
  1525. $csv_row[] = get_lang('CourseCode');
  1526. // the additional user defined fields (only those that were selected to be exported)
  1527. $fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  1528. if (is_array($_SESSION['additional_export_fields'])) {
  1529. foreach ($_SESSION['additional_export_fields'] as $key => $extra_field_export) {
  1530. $csv_row[] = $fields[$extra_field_export][3];
  1531. $field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
  1532. }
  1533. }
  1534. $csv_row[] = get_lang('AvgTimeSpentInTheCourse', '');
  1535. $csv_row[] = get_lang('AvgStudentsProgress', '');
  1536. $csv_row[] = get_lang('AvgCourseScore', '');
  1537. $csv_row[] = get_lang('AvgExercisesScore', '');
  1538. $csv_row[] = get_lang('AvgMessages', '');
  1539. $csv_row[] = get_lang('AvgAssignments', '');
  1540. $csv_row[] = get_lang('TotalExercisesScoreObtained', '');
  1541. $csv_row[] = get_lang('TotalExercisesScorePossible', '');
  1542. $csv_row[] = get_lang('TotalExercisesAnswered', '');
  1543. $csv_row[] = get_lang('TotalExercisesScorePercentage', '');
  1544. $csv_row[] = get_lang('FirstLogin', '');
  1545. $csv_row[] = get_lang('LatestLogin', '');
  1546. $csv_content[] = $csv_row;
  1547. // the other lines (the data)
  1548. foreach ($user_data as $key => $user) {
  1549. // getting all the courses of the user
  1550. $sql = "SELECT * FROM $tbl_course_user
  1551. WHERE user_id = '".intval($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
  1552. $result = Database::query($sql);
  1553. while ($row = Database::fetch_row($result)) {
  1554. $courseInfo = api_get_course_info($row['course_code']);
  1555. $courseId = $courseInfo['real_id'];
  1556. $csv_row = array();
  1557. // user official code
  1558. $csv_row[] = $user[0];
  1559. // user first|last name
  1560. $csv_row[] = $user[1];
  1561. // user last|first name
  1562. $csv_row[] = $user[2];
  1563. // user login name
  1564. $csv_row[] = $user[3];
  1565. // course code
  1566. $csv_row[] = $row[0];
  1567. // the additional defined user fields
  1568. $extra_fields = self::get_user_overview_export_extra_fields($user[4]);
  1569. if (is_array($field_names_to_be_exported)) {
  1570. foreach ($field_names_to_be_exported as $key => $extra_field_export) {
  1571. $csv_row[] = $extra_fields[$extra_field_export];
  1572. }
  1573. }
  1574. // time spent in the course
  1575. $csv_row[] = api_time_to_hms(Tracking::get_time_spent_on_the_course ($user[4], $courseId));
  1576. // student progress in course
  1577. $csv_row[] = round(Tracking::get_avg_student_progress ($user[4], $row[0]), 2);
  1578. // student score
  1579. $csv_row[] = round(Tracking::get_avg_student_score($user[4], $row[0]), 2);
  1580. // student tes score
  1581. $csv_row[] = round(Tracking::get_avg_student_exercise_score($user[4], $row[0]), 2);
  1582. // student messages
  1583. $csv_row[] = Tracking::count_student_messages($user[4], $row[0]);
  1584. // student assignments
  1585. $csv_row[] = Tracking::count_student_assignments ($user[4], $row[0]);
  1586. // student exercises results
  1587. $exercises_results = self::exercises_results($user[4], $row[0]);
  1588. $csv_row[] = $exercises_results['score_obtained'];
  1589. $csv_row[] = $exercises_results['score_possible'];
  1590. $csv_row[] = $exercises_results['questions_answered'];
  1591. $csv_row[] = $exercises_results['percentage'];
  1592. // first connection
  1593. $csv_row[] = Tracking::get_first_connection_date_on_the_course ($user[4], $courseId);
  1594. // last connection
  1595. $csv_row[] = strip_tags(Tracking::get_last_connection_date_on_the_course($user[4], $courseInfo));
  1596. $csv_content[] = $csv_row;
  1597. }
  1598. }
  1599. Export::arrayToCsv($csv_content, 'reporting_user_overview');
  1600. exit;
  1601. }
  1602. /**
  1603. * Get data for courses list in sortable with pagination
  1604. * @return array
  1605. */
  1606. public static function get_course_data($from, $number_of_items, $column, $direction)
  1607. {
  1608. global $courses, $csv_content, $charset, $session_id;
  1609. // definition database tables
  1610. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1611. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1612. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1613. $course_data = array();
  1614. $courses_code = array_keys($courses);
  1615. foreach ($courses_code as &$code) {
  1616. $code = "'$code'";
  1617. }
  1618. // get all courses with limit
  1619. $sql = "SELECT course.code as col1, course.title as col2
  1620. FROM $tbl_course course
  1621. WHERE course.code IN (".implode(',',$courses_code).")";
  1622. if (!in_array($direction, array('ASC','DESC'))) $direction = 'ASC';
  1623. $column = intval($column);
  1624. $from = intval($from);
  1625. $number_of_items = intval($number_of_items);
  1626. $sql .= " ORDER BY col$column $direction ";
  1627. $sql .= " LIMIT $from,$number_of_items";
  1628. $res = Database::query($sql);
  1629. while ($row_course = Database::fetch_row($res)) {
  1630. $course_code = $row_course[0];
  1631. $courseInfo = api_get_course_info($course_code);
  1632. $courseId = $courseInfo['real_id'];
  1633. $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
  1634. // students directly subscribed to the course
  1635. if (empty($session_id)) {
  1636. $sql = "SELECT user_id
  1637. FROM $tbl_course_user as course_rel_user
  1638. WHERE
  1639. course_rel_user.status='5' AND
  1640. course_rel_user.c_id = '$courseId'";
  1641. } else {
  1642. $sql = "SELECT user_id FROM $tbl_session_course_user srcu
  1643. WHERE
  1644. c_id = '$courseId' AND
  1645. session_id = '$session_id' AND
  1646. status<>2";
  1647. }
  1648. $rs = Database::query($sql);
  1649. $users = array();
  1650. while ($row = Database::fetch_array($rs)) {
  1651. $users[] = $row['user_id'];
  1652. }
  1653. if (count($users) > 0) {
  1654. $nb_students_in_course = count($users);
  1655. $avg_assignments_in_course = Tracking::count_student_assignments($users, $course_code, $session_id);
  1656. $avg_messages_in_course = Tracking::count_student_messages($users, $course_code, $session_id);
  1657. $avg_progress_in_course = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
  1658. $avg_score_in_course = Tracking::get_avg_student_score($users, $course_code, array(), $session_id);
  1659. $avg_score_in_exercise = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
  1660. $avg_time_spent_in_course = Tracking::get_time_spent_on_the_course($users, $courseInfo['real_id'], $session_id);
  1661. $avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
  1662. if (is_numeric($avg_score_in_course)) {
  1663. $avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
  1664. }
  1665. $avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
  1666. } else {
  1667. $avg_time_spent_in_course = null;
  1668. $avg_progress_in_course = null;
  1669. $avg_score_in_course = null;
  1670. $avg_score_in_exercise = null;
  1671. $avg_messages_in_course = null;
  1672. $avg_assignments_in_course = null;
  1673. }
  1674. $table_row = array();
  1675. $table_row[] = $row_course[1];
  1676. $table_row[] = $nb_students_in_course;
  1677. $table_row[] = $avg_time_spent_in_course;
  1678. $table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
  1679. $table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
  1680. $table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
  1681. $table_row[] = $avg_messages_in_course;
  1682. $table_row[] = $avg_assignments_in_course;
  1683. //set the "from" value to know if I access the Reporting by the chamilo tab or the course link
  1684. $table_row[] = '<center><a href="../../tracking/courseLog.php?cidReq=' .$course_code.'&from=myspace&id_session='.$session_id.'">
  1685. '.Display::return_icon('2rightarrow.png').'
  1686. </a>
  1687. </center>';
  1688. $csv_content[] = array(
  1689. api_html_entity_decode($row_course[1], ENT_QUOTES, $charset),
  1690. $nb_students_in_course,
  1691. $avg_time_spent_in_course,
  1692. is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
  1693. is_null($avg_score_in_course) ? null : is_numeric($avg_score_in_course) ? $avg_score_in_course.'%' : $avg_score_in_course ,
  1694. is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
  1695. $avg_messages_in_course,
  1696. $avg_assignments_in_course,
  1697. );
  1698. $course_data[] = $table_row;
  1699. }
  1700. return $course_data;
  1701. }
  1702. /**
  1703. * Get the number of users of the platform
  1704. *
  1705. * @return integer
  1706. *
  1707. */
  1708. public static function get_number_of_users_tracking_overview()
  1709. {
  1710. return UserManager::get_number_of_users(0, api_get_current_access_url_id());
  1711. }
  1712. /**
  1713. * Get all the data for the sortable table of the reporting progress of
  1714. * all users and all the courses the user is subscribed to.
  1715. *
  1716. * @param int $from
  1717. * @param int $numberItems
  1718. * @param int $column
  1719. * @param string $direction
  1720. */
  1721. public static function get_user_data_tracking_overview($from, $numberItems, $column, $direction)
  1722. {
  1723. $isWestern = api_is_western_name_order();
  1724. switch ($column) {
  1725. case '0':
  1726. $column = 'official_code';
  1727. break;
  1728. case '1':
  1729. $column = $isWestern ? 'firstname' : 'lastname';
  1730. break;
  1731. case '2':
  1732. $column = $isWestern ? 'lastname' : 'firstname';
  1733. break;
  1734. case '3':
  1735. $column = 'username';
  1736. break;
  1737. case '4':
  1738. $column = 'username';
  1739. break;
  1740. }
  1741. $order = [
  1742. "$column $direction"
  1743. ];
  1744. $userList = UserManager::get_user_list([], $order, $from, $numberItems);
  1745. $return = [];
  1746. foreach ($userList as $user) {
  1747. $firstPosition = $user['lastname'];
  1748. $secondPosition = $user['firstname'];
  1749. if ($isWestern) {
  1750. $firstPosition = $user['firstname'];
  1751. $secondPosition = $user['lastname'];
  1752. }
  1753. $return[] = [
  1754. '0' => $user['official_code'],
  1755. 'col0' => $user['official_code'],
  1756. '1' => $firstPosition,
  1757. 'col1' => $firstPosition,
  1758. '2' => $secondPosition,
  1759. 'col2' => $secondPosition,
  1760. '3' => $user['username'],
  1761. 'col3' => $user['username'],
  1762. '4' => $user['user_id'],
  1763. 'col4' => $user['user_id']
  1764. ];
  1765. }
  1766. return $return;
  1767. }
  1768. /**
  1769. * Get all information that the user with user_id = $user_data has
  1770. * entered in the additionally defined profile fields
  1771. * @param integer $user_id the id of the user
  1772. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  1773. * @version Dokeos 1.8.6
  1774. * @since November 2008
  1775. */
  1776. public static function get_user_overview_export_extra_fields($user_id)
  1777. {
  1778. // include the user manager
  1779. $extra_data = UserManager::get_extra_user_data($user_id, true);
  1780. return $extra_data;
  1781. }
  1782. /**
  1783. * Checks if a username exist in the DB otherwise it create a "double"
  1784. * i.e. if we look into for jmontoya but the user's name already exist we create the user jmontoya2
  1785. * the return array will be array(username=>'jmontoya', sufix='2')
  1786. * @param string firstname
  1787. * @param string lastname
  1788. * @param string username
  1789. * @return array with the username, the sufix
  1790. * @author Julio Montoya Armas
  1791. */
  1792. public static function make_username($firstname, $lastname, $username, $language = null, $encoding = null)
  1793. {
  1794. // if username exist
  1795. if (!UserManager::is_username_available($username) || empty($username)) {
  1796. $i = 0;
  1797. while (1) {
  1798. if ($i == 0) {
  1799. $sufix = '';
  1800. } else {
  1801. $sufix = $i;
  1802. }
  1803. $desired_username = UserManager::create_username(
  1804. $firstname,
  1805. $lastname,
  1806. $language,
  1807. $encoding
  1808. );
  1809. if (UserManager::is_username_available($desired_username.$sufix)) {
  1810. break;
  1811. } else {
  1812. $i++;
  1813. }
  1814. }
  1815. $username_array = array('username' => $desired_username , 'sufix' => $sufix);
  1816. return $username_array;
  1817. } else {
  1818. $username_array = array('username' => $username, 'sufix' => '');
  1819. return $username_array;
  1820. }
  1821. }
  1822. /**
  1823. * Checks if there are repeted users in a given array
  1824. * @param array $usernames list of the usernames in the uploaded file
  1825. * @param array $user_array['username'] and $user_array['sufix'] where sufix is the number part in a login i.e -> jmontoya2
  1826. * @return array with the $usernames array and the $user_array array
  1827. * @author Julio Montoya
  1828. */
  1829. public static function check_user_in_array($usernames, $user_array)
  1830. {
  1831. $user_list = array_keys($usernames);
  1832. $username = $user_array['username'].$user_array['sufix'];
  1833. if (in_array($username, $user_list)) {
  1834. $user_array['sufix'] += $usernames[$username];
  1835. $usernames[$username]++;
  1836. } else {
  1837. $usernames[$username] = 1;
  1838. }
  1839. $result_array = array($usernames, $user_array);
  1840. return $result_array;
  1841. }
  1842. /**
  1843. * Checks whether a username has been already subscribed in a session.
  1844. * @param string $username a given username
  1845. * @param array $course_list the array with the course list id
  1846. * @param int $id_session the session id
  1847. * @return int 0 if the user is not subscribed otherwise it returns the user_id of the given username
  1848. * @author Julio Montoya
  1849. */
  1850. public static function user_available_in_session($username, $course_list, $id_session)
  1851. {
  1852. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1853. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1854. $id_session = intval($id_session);
  1855. $username = Database::escape_string($username);
  1856. foreach ($course_list as $courseId) {
  1857. $courseId = intval($courseId);
  1858. $sql = " SELECT u.user_id FROM $tbl_session_rel_course_rel_user rel
  1859. INNER JOIN $table_user u
  1860. ON (rel.user_id = u.user_id)
  1861. WHERE
  1862. rel.session_id='$id_session' AND
  1863. u.status='5' AND
  1864. u.username ='$username' AND
  1865. rel.c_id='$courseId'";
  1866. $rs = Database::query($sql);
  1867. if (Database::num_rows($rs) > 0) {
  1868. return Database::result($rs, 0, 0);
  1869. } else {
  1870. return 0;
  1871. }
  1872. }
  1873. return 0;
  1874. }
  1875. /**
  1876. * This function checks whether some users in the uploaded file
  1877. * repeated and creates unique usernames if necesary.
  1878. * A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya)
  1879. * and the username fields are empty.
  1880. * Then, this function would create unique usernames based on the first and the last name.
  1881. * Two users wiould be created - jmontoya and jmontoya2.
  1882. * Of course, if in the database there is a user with the name jmontoya,
  1883. * the newly created two users registered would be jmontoya2 and jmontoya3.
  1884. * @param $users list of users
  1885. * @author Julio Montoya Armas
  1886. */
  1887. function check_all_usernames($users, $course_list, $id_session)
  1888. {
  1889. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1890. $usernames = array();
  1891. $new_users = array();
  1892. foreach ($users as $index => $user) {
  1893. $desired_username = array();
  1894. if (empty($user['UserName'])) {
  1895. $desired_username = self::make_username($user['FirstName'], $user['LastName'], '');
  1896. $pre_username = $desired_username['username'].$desired_username['sufix'];
  1897. $user['UserName'] = $pre_username;
  1898. $user['create'] = '1';
  1899. } else {
  1900. if (UserManager::is_username_available($user['UserName'])) {
  1901. $desired_username = self::make_username($user['FirstName'], $user['LastName'], $user['UserName']);
  1902. $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
  1903. $user['create'] = '1';
  1904. } else {
  1905. $is_session_avail = self::user_available_in_session($user['UserName'], $course_list, $id_session);
  1906. if ($is_session_avail == 0) {
  1907. $user_name = $user['UserName'];
  1908. $sql_select = "SELECT user_id FROM $table_user WHERE username ='$user_name' ";
  1909. $rs = Database::query($sql_select);
  1910. $user['create'] = Database::result($rs, 0, 0); // This should be the ID because the user exists.
  1911. } else {
  1912. $user['create'] = $is_session_avail;
  1913. }
  1914. }
  1915. }
  1916. // Usernames is the current list of users in the file.
  1917. $result_array = self::check_user_in_array($usernames, $desired_username);
  1918. $usernames = $result_array[0];
  1919. $desired_username = $result_array[1];
  1920. $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
  1921. $new_users[] = $user;
  1922. }
  1923. return $new_users;
  1924. }
  1925. /**
  1926. * This functions checks whether there are users that are already
  1927. * registered in the DB by different creator than the current coach.
  1928. * @param string a given username
  1929. * @param array the array with the course list ids
  1930. * @param the session id
  1931. * @author Julio Montoya Armas
  1932. */
  1933. public function get_user_creator($users)
  1934. {
  1935. $errors = array();
  1936. foreach ($users as $index => $user) {
  1937. // database table definition
  1938. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1939. $username = Database::escape_string($user['UserName']);
  1940. $sql = "SELECT creator_id FROM $table_user WHERE username='$username' ";
  1941. $rs = Database::query($sql);
  1942. $creator_id = Database::result($rs, 0, 0);
  1943. // check if we are the creators or not
  1944. if ($creator_id != '') {
  1945. if ($creator_id != api_get_user_id()) {
  1946. $user['error'] = get_lang('UserAlreadyRegisteredByOtherCreator');
  1947. $errors[] = $user;
  1948. }
  1949. }
  1950. }
  1951. return $errors;
  1952. }
  1953. /**
  1954. * Validates imported data.
  1955. * @param list of users
  1956. */
  1957. function validate_data($users, $id_session = null)
  1958. {
  1959. $errors = array();
  1960. $new_users = array();
  1961. foreach ($users as $index => $user) {
  1962. // 1. Check whether mandatory fields are set.
  1963. $mandatory_fields = array('LastName', 'FirstName');
  1964. if (api_get_setting('registration', 'email') == 'true') {
  1965. $mandatory_fields[] = 'Email';
  1966. }
  1967. foreach ($mandatory_fields as $key => $field) {
  1968. if (!isset ($user[$field]) || strlen($user[$field]) == 0) {
  1969. $user['error'] = get_lang($field.'Mandatory');
  1970. $errors[] = $user;
  1971. }
  1972. }
  1973. // 2. Check whether the username is too long.
  1974. if (UserManager::is_username_too_long($user['UserName'])) {
  1975. $user['error'] = get_lang('UserNameTooLong');
  1976. $errors[] = $user;
  1977. }
  1978. $user['UserName'] = trim($user['UserName']);
  1979. if (empty($user['UserName'])) {
  1980. $user['UserName'] = UserManager::create_username($user['FirstName'], $user['LastName']);
  1981. }
  1982. $new_users[] = $user;
  1983. }
  1984. $results = array('errors' => $errors, 'users' => $new_users);
  1985. return $results;
  1986. }
  1987. /**
  1988. * Adds missing user-information (which isn't required, like password, etc).
  1989. */
  1990. function complete_missing_data($user) {
  1991. // 1. Generate a password if it is necessary.
  1992. if (!isset ($user['Password']) || strlen($user['Password']) == 0) {
  1993. $user['Password'] = api_generate_password();
  1994. }
  1995. return $user;
  1996. }
  1997. /**
  1998. * Saves imported data.
  1999. */
  2000. public function save_data($users, $course_list, $id_session)
  2001. {
  2002. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2003. $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2004. $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2005. $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2006. $id_session = intval($id_session);
  2007. $sendMail = $_POST['sendMail'] ? 1 : 0;
  2008. // Adding users to the platform.
  2009. $new_users = array();
  2010. foreach ($users as $index => $user) {
  2011. $user = self::complete_missing_data($user);
  2012. // coach only will registered users
  2013. $default_status = STUDENT;
  2014. if ($user['create'] == COURSEMANAGER) {
  2015. $user['id'] = UserManager:: create_user(
  2016. $user['FirstName'],
  2017. $user['LastName'],
  2018. $default_status,
  2019. $user['Email'],
  2020. $user['UserName'],
  2021. $user['Password'],
  2022. $user['OfficialCode'],
  2023. api_get_setting('PlatformLanguage'),
  2024. $user['PhoneNumber'],
  2025. ''
  2026. );
  2027. $user['added_at_platform'] = 1;
  2028. } else {
  2029. $user['id'] = $user['create'];
  2030. $user['added_at_platform'] = 0;
  2031. }
  2032. $new_users[] = $user;
  2033. }
  2034. // Update user list.
  2035. $users = $new_users;
  2036. // Inserting users.
  2037. $super_list = array();
  2038. foreach ($course_list as $enreg_course) {
  2039. $nbr_users = 0;
  2040. $new_users = array();
  2041. $enreg_course = Database::escape_string($enreg_course);
  2042. foreach ($users as $index => $user) {
  2043. $userid = intval($user['id']);
  2044. $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id)
  2045. VALUES('$id_session','$enreg_course','$userid')";
  2046. $course_session = array('course' => $enreg_course, 'added' => 1);
  2047. $result = Database::query($sql);
  2048. if (Database::affected_rows($result)) {
  2049. $nbr_users++;
  2050. }
  2051. $new_users[] = $user;
  2052. }
  2053. $super_list[] = $new_users;
  2054. //update the nbr_users field
  2055. $sql_select = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user
  2056. WHERE session_id='$id_session' AND c_id='$enreg_course'";
  2057. $rs = Database::query($sql_select);
  2058. list($nbr_users) = Database::fetch_array($rs);
  2059. $sql_update = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users
  2060. WHERE session_id='$id_session' AND c_id='$enreg_course'";
  2061. Database::query($sql_update);
  2062. $sql_update = "UPDATE $tbl_session SET nbr_users= '$nbr_users' WHERE id='$id_session'";
  2063. Database::query($sql_update);
  2064. }
  2065. $new_users = array();
  2066. foreach ($users as $index => $user) {
  2067. $userid = $user['id'];
  2068. $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_user(session_id, user_id, registered_at)
  2069. VALUES ('$id_session','$userid', '" . api_get_utc_datetime() . "')";
  2070. Database::query($sql_insert);
  2071. $user['added_at_session'] = 1;
  2072. $new_users[] = $user;
  2073. }
  2074. $users = $new_users;
  2075. $registered_users = get_lang('FileImported').'<br /> Import file results : <br />';
  2076. // Sending emails.
  2077. $addedto = '';
  2078. if ($sendMail) {
  2079. $i = 0;
  2080. foreach ($users as $index => $user) {
  2081. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  2082. $emailbody = get_lang('Dear').' '.
  2083. api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".
  2084. get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".
  2085. get_lang('Username')." : $user[UserName]\n".
  2086. get_lang('Pass')." : $user[Password]\n\n".
  2087. get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path(WEB_PATH)." \n\n".
  2088. get_lang('Problem')."\n\n".
  2089. get_lang('SignatureFormula').",\n\n".
  2090. api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".
  2091. get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".
  2092. api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator');
  2093. api_mail_html(
  2094. api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS),
  2095. $user['Email'],
  2096. $emailsubject,
  2097. $emailbody
  2098. );
  2099. $userInfo = api_get_user_info($user['id']);
  2100. if (($user['added_at_platform'] == 1 && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
  2101. if ($user['added_at_platform'] == 1) {
  2102. $addedto = get_lang('UserCreatedPlatform');
  2103. } else {
  2104. $addedto = ' ';
  2105. }
  2106. if ($user['added_at_session'] == 1) {
  2107. $addedto .= get_lang('UserInSession');
  2108. }
  2109. } else {
  2110. $addedto = get_lang('UserNotAdded');
  2111. }
  2112. $registered_users .= UserManager::getUserProfileLink($userInfo)." - ".$addedto.'<br />';
  2113. }
  2114. } else {
  2115. $i = 0;
  2116. foreach ($users as $index => $user) {
  2117. $userInfo = api_get_user_info($user['id']);
  2118. if (($user['added_at_platform'] == 1 && $user['added_at_session'] == 1) || $user['added_at_session'] == 1) {
  2119. if ($user['added_at_platform'] == 1) {
  2120. $addedto = get_lang('UserCreatedPlatform');
  2121. } else {
  2122. $addedto = ' ';
  2123. }
  2124. if ($user['added_at_session'] == 1) {
  2125. $addedto .= ' '.get_lang('UserInSession');
  2126. }
  2127. } else {
  2128. $addedto = get_lang('UserNotAdded');
  2129. }
  2130. $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".api_get_person_name($user['FirstName'], $user['LastName'])."</a> - ".$addedto.'<br />';
  2131. }
  2132. }
  2133. Display::addFlash(Display::return_message($registered_users));
  2134. header('Location: course.php?id_session='.$id_session);
  2135. exit;
  2136. }
  2137. /**
  2138. * Reads CSV-file.
  2139. * @param string $file Path to the CSV-file
  2140. * @return array All userinformation read from the file
  2141. */
  2142. function parse_csv_data($file) {
  2143. $users = Import::csvToArray($file);
  2144. foreach ($users as $index => $user) {
  2145. if (isset ($user['Courses'])) {
  2146. $user['Courses'] = explode('|', trim($user['Courses']));
  2147. }
  2148. $users[$index] = $user;
  2149. }
  2150. return $users;
  2151. }
  2152. /**
  2153. * XML-parser: the handler at the beginning of element.
  2154. */
  2155. function element_start($parser, $data) {
  2156. $data = api_utf8_decode($data);
  2157. global $user;
  2158. global $current_tag;
  2159. switch ($data) {
  2160. case 'Contact' :
  2161. $user = array ();
  2162. break;
  2163. default:
  2164. $current_tag = $data;
  2165. }
  2166. }
  2167. /**
  2168. * XML-parser: the handler at the end of element.
  2169. */
  2170. function element_end($parser, $data) {
  2171. $data = api_utf8_decode($data);
  2172. global $user;
  2173. global $users;
  2174. global $current_value;
  2175. global $purification_option_for_usernames;
  2176. $user[$data] = $current_value;
  2177. switch ($data) {
  2178. case 'Contact' :
  2179. $user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
  2180. $users[] = $user;
  2181. break;
  2182. default:
  2183. $user[$data] = $current_value;
  2184. break;
  2185. }
  2186. }
  2187. /**
  2188. * XML-parser: the handler for character data.
  2189. */
  2190. function character_data($parser, $data) {
  2191. $data = trim(api_utf8_decode($data));
  2192. global $current_value;
  2193. $current_value = $data;
  2194. }
  2195. /**
  2196. * Reads XML-file.
  2197. * @param string $file Path to the XML-file
  2198. * @return array All userinformation read from the file
  2199. */
  2200. function parse_xml_data($file) {
  2201. global $current_tag;
  2202. global $current_value;
  2203. global $user;
  2204. global $users;
  2205. $users = array ();
  2206. $parser = xml_parser_create('UTF-8');
  2207. xml_set_element_handler($parser, array('MySpace','element_start'), array('MySpace','element_end'));
  2208. xml_set_character_data_handler($parser, "character_data");
  2209. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  2210. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  2211. xml_parser_free($parser);
  2212. return $users;
  2213. }
  2214. public static function displayTrackingAccessOverView($courseId, $sessionId, $studentId)
  2215. {
  2216. $courseId = intval($courseId);
  2217. $sessionId = intval($sessionId);
  2218. $studentId = intval($studentId);
  2219. $em = Database::getManager();
  2220. $sessionRepo = $em->getRepository('ChamiloCoreBundle:Session');
  2221. $courseList = [];
  2222. $sessionList = [];
  2223. $studentList = [];
  2224. if (!empty($courseId)) {
  2225. $course = $em->find('ChamiloCoreBundle:Course', $courseId);
  2226. $courseList[$course->getId()] = $course->getTitle();
  2227. }
  2228. if (!empty($sessionId)) {
  2229. $session = $em->find('ChamiloCoreBundle:Session', $sessionId);
  2230. $sessionList[$session->getId()] = $session->getName();
  2231. }
  2232. if (!empty($studentId)) {
  2233. $student = $em->find('ChamiloUserBundle:User', $studentId);
  2234. $studentList[$student->getId()] = $student->getCompleteName();
  2235. }
  2236. $form = new FormValidator('access_overview', 'GET');
  2237. $form->addElement(
  2238. 'select_ajax',
  2239. 'course_id',
  2240. get_lang('SearchCourse'),
  2241. $courseList,
  2242. [
  2243. 'url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?' . http_build_query([
  2244. 'a' => 'search_course_by_session_all',
  2245. 'session_id' => $sessionId
  2246. ])
  2247. ]
  2248. );
  2249. $form->addElement(
  2250. 'select_ajax',
  2251. 'session_id',
  2252. get_lang('SearchSession'),
  2253. $sessionList,
  2254. [
  2255. 'url_function' => "
  2256. function () {
  2257. var params = $.param({
  2258. a: 'search_session_by_course',
  2259. course_id: $('#course_id').val() || 0
  2260. });
  2261. return '" . api_get_path(WEB_AJAX_PATH) . "session.ajax.php?' + params;
  2262. }
  2263. "
  2264. ]
  2265. );
  2266. $form->addSelect(
  2267. 'profile',
  2268. get_lang('Profile'),
  2269. [
  2270. '' => get_lang('Select'),
  2271. STUDENT => get_lang('Student'),
  2272. COURSEMANAGER => get_lang('CourseManager'),
  2273. DRH => get_lang('Drh')
  2274. ],
  2275. ['id' => 'profile']
  2276. );
  2277. $form->addElement(
  2278. 'select_ajax',
  2279. 'student_id',
  2280. get_lang('SearchUsers'),
  2281. $studentList,
  2282. [
  2283. 'placeholder' => get_lang('All'),
  2284. 'url_function' => "
  2285. function () {
  2286. var params = $.param({
  2287. a: 'search_user_by_course',
  2288. session_id: $('#session_id').val(),
  2289. course_id: $('#course_id').val()
  2290. });
  2291. return '" . api_get_path(WEB_AJAX_PATH) . "course.ajax.php?' + params;
  2292. }
  2293. "
  2294. ]
  2295. );
  2296. $form->addDateRangePicker(
  2297. 'date',
  2298. get_lang('DateRange'),
  2299. true,
  2300. [
  2301. 'id' => 'date_range',
  2302. 'format' => 'YYYY-MM-DD',
  2303. 'timePicker' => 'false',
  2304. 'validate_format' => 'Y-m-d'
  2305. ]
  2306. );
  2307. $form->addHidden('display', 'accessoverview');
  2308. $form->addRule('course_id', get_lang('Required'), 'required');
  2309. $form->addRule('profile', get_lang('Required'), 'required');
  2310. $form->addButton('submit', get_lang('Generate'), 'gear', 'primary');
  2311. $table = null;
  2312. if ($form->validate()) {
  2313. $table = new SortableTable(
  2314. 'tracking_access_overview',
  2315. ['MySpace', 'getNumberOfTrackAccessOverview'],
  2316. ['MySpace', 'getUserDataAccessTrackingOverview'],
  2317. 0
  2318. );
  2319. $table->additional_parameters = $form->exportValues();
  2320. $table->set_header(0, get_lang('LoginDate'), true);
  2321. $table->set_header(1, get_lang('Username'), true);
  2322. if (api_is_western_name_order()) {
  2323. $table->set_header(2, get_lang('FirstName'), true);
  2324. $table->set_header(3, get_lang('LastName'), true);
  2325. } else {
  2326. $table->set_header(2, get_lang('LastName'), true);
  2327. $table->set_header(3, get_lang('FirstName'), true);
  2328. }
  2329. $table->set_header(4, get_lang('Clicks'), false);
  2330. $table->set_header(5, get_lang('IP'), false);
  2331. $table->set_header(6, get_lang('TimeLoggedIn'), false);
  2332. }
  2333. $template = new Template(null, false, false, false, false, false, false);
  2334. $template->assign('form', $form->returnForm());
  2335. $template->assign('table', $table ? $table->return_table() : null);
  2336. echo $template->fetch(
  2337. $template->get_template('my_space/accessoverview.tpl')
  2338. );
  2339. }
  2340. /**
  2341. * @return int
  2342. */
  2343. public static function getNumberOfTrackAccessOverview()
  2344. {
  2345. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2346. $sql = "SELECT COUNT(course_access_id) count FROM $table";
  2347. $result = Database::query($sql);
  2348. $row = Database::fetch_assoc($result);
  2349. return $row['count'];
  2350. }
  2351. /**
  2352. * @param $from
  2353. * @param $numberItems
  2354. * @param $column
  2355. * @param $orderDirection
  2356. * @return array
  2357. */
  2358. public static function getUserDataAccessTrackingOverview($from, $numberItems, $column, $orderDirection)
  2359. {
  2360. $user = Database::get_main_table(TABLE_MAIN_USER);
  2361. $course = Database::get_main_table(TABLE_MAIN_COURSE);
  2362. $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  2363. $track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2364. global $export_csv;
  2365. if ($export_csv) {
  2366. $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
  2367. } else {
  2368. $is_western_name_order = api_is_western_name_order();
  2369. }
  2370. //TODO add course name
  2371. $sql = "SELECT
  2372. a.login_course_date as col0,
  2373. u.username as col1,
  2374. " . (
  2375. $is_western_name_order ? "
  2376. u.firstname AS col2,
  2377. u.lastname AS col3,
  2378. " : "
  2379. u.lastname AS col2,
  2380. u.firstname AS col3,
  2381. " ) . "
  2382. a.logout_course_date,
  2383. c.title,
  2384. c.code,
  2385. u.user_id
  2386. FROM $track_e_course_access a
  2387. INNER JOIN $user u ON a.user_id = u.user_id
  2388. INNER JOIN $course c ON a.c_id = c.id";
  2389. if (isset($_GET['session_id']) && !empty($_GET['session_id'])) {
  2390. $sessionId = intval($_GET['session_id']);
  2391. $sql .= " WHERE a.session_id = " . $sessionId;
  2392. }
  2393. $sql .= " ORDER BY col$column $orderDirection ";
  2394. $sql .= " LIMIT $from,$numberItems";
  2395. $result = Database::query($sql);
  2396. //$clicks = Tracking::get_total_clicks_by_session();
  2397. $data = array();
  2398. while ($user = Database::fetch_assoc($result)) {
  2399. $data[] = $user;
  2400. }
  2401. $return = [];
  2402. //TODO: Dont use numeric index
  2403. foreach ($data as $key => $info) {
  2404. $start_date = $info['col0'];
  2405. $end_date = $info['logout_course_date'];
  2406. $return[$info['user_id']] = array(
  2407. $start_date,
  2408. $info['col1'],
  2409. $info['col2'],
  2410. $info['col3'],
  2411. $info['user_id'],
  2412. 'ip',
  2413. //TODO is not correct/precise, it counts the time not logged between two loggins
  2414. gmdate("H:i:s", strtotime($end_date) - strtotime($start_date))
  2415. );
  2416. }
  2417. foreach ($return as $key => $info) {
  2418. $ipResult = Database::select(
  2419. 'user_ip',
  2420. $track_e_login,
  2421. ['where' => [
  2422. '? BETWEEN login_date AND logout_date' => $info[0]
  2423. ]],
  2424. 'first'
  2425. );
  2426. $return[$key][5] = $ipResult['user_ip'];
  2427. }
  2428. return $return;
  2429. }
  2430. /**
  2431. * Gets the connections to a course as an array of login and logout time
  2432. *
  2433. * @param int $user_id
  2434. * @param int $courseId
  2435. * @author Jorge Frisancho Jibaja
  2436. * @author Julio Montoya <gugli100@gmail.com> fixing the function
  2437. * @version OCT-22- 2010
  2438. * @return array
  2439. */
  2440. public static function get_connections_to_course_by_date($user_id, $courseId, $start_date, $end_date)
  2441. {
  2442. // Database table definitions
  2443. $tbl_track_course = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2444. $course_info = api_get_course_info_by_id($courseId);
  2445. $user_id = intval($user_id);
  2446. $courseId = intval($courseId);
  2447. $connections = array();
  2448. if (!empty($course_info)) {
  2449. $end_date = add_day_to($end_date);
  2450. $sql = "SELECT login_course_date, logout_course_date
  2451. FROM $tbl_track_course
  2452. WHERE
  2453. user_id = $user_id AND
  2454. c_id = $courseId AND
  2455. login_course_date BETWEEN '$start_date' AND '$end_date' AND
  2456. logout_course_date BETWEEN '$start_date' AND '$end_date'
  2457. ORDER BY login_course_date ASC";
  2458. $rs = Database::query($sql);
  2459. while ($row = Database::fetch_array($rs)) {
  2460. $login_date = $row['login_course_date'];
  2461. $logout_date = $row['logout_course_date'];
  2462. $timestamp_login_date = strtotime($login_date);
  2463. $timestamp_logout_date = strtotime($logout_date);
  2464. $connections[] = array(
  2465. 'login' => $timestamp_login_date,
  2466. 'logout' => $timestamp_logout_date
  2467. );
  2468. }
  2469. }
  2470. return $connections;
  2471. }
  2472. }
  2473. /**
  2474. * @param $user_id
  2475. * @param int $courseId
  2476. * @param null $start_date
  2477. * @param null $end_date
  2478. * @return array
  2479. */
  2480. function get_stats($user_id, $courseId, $start_date = null, $end_date = null)
  2481. {
  2482. // Database table definitions
  2483. $tbl_track_course = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  2484. $course_info = api_get_course_info_by_id($courseId);
  2485. if (!empty($course_info)) {
  2486. $strg_sd = '';
  2487. $strg_ed = '';
  2488. if ($start_date != null && $end_date != null){
  2489. $end_date = add_day_to($end_date);
  2490. $strg_sd = "AND login_course_date BETWEEN '$start_date' AND '$end_date'";
  2491. $strg_ed = "AND logout_course_date BETWEEN '$start_date' AND '$end_date'";
  2492. }
  2493. $sql = 'SELECT
  2494. SEC_TO_TIME(avg(time_to_sec(timediff(logout_course_date,login_course_date)))) as avrg,
  2495. SEC_TO_TIME(sum(time_to_sec(timediff(logout_course_date,login_course_date)))) as total,
  2496. count(user_id) as times
  2497. FROM ' . $tbl_track_course . '
  2498. WHERE
  2499. user_id = ' . intval($user_id) . ' AND
  2500. c_id = ' . intval($courseId) . ' '.$strg_sd.' '.$strg_ed.' '.'
  2501. ORDER BY login_course_date ASC';
  2502. $rs = Database::query($sql);
  2503. $result = array();
  2504. if ($row = Database::fetch_array($rs)) {
  2505. $foo_avg = $row['avrg'];
  2506. $foo_total = $row['total'];
  2507. $foo_times = $row['times'];
  2508. $result = array('avg' => $foo_avg, 'total' => $foo_total, 'times' => $foo_times);
  2509. }
  2510. }
  2511. return $result;
  2512. }
  2513. function add_day_to($end_date) {
  2514. $foo_date = strtotime( $end_date );
  2515. $foo_date = strtotime(" +1 day", $foo_date);
  2516. $foo_date = date("Y-m-d", $foo_date);
  2517. return $foo_date;
  2518. }
  2519. /**
  2520. *
  2521. *
  2522. * @param array
  2523. * @author Jorge Frisancho Jibaja
  2524. * @version OCT-22- 2010
  2525. * @return array
  2526. */
  2527. function convert_to_array($sql_result){
  2528. $result_to_print = '<table>';
  2529. foreach ($sql_result as $key => $data) {
  2530. $result_to_print .= '<tr><td>'.date('d-m-Y (H:i:s)', $data['login']).'</td><td>'.api_time_to_hms($data['logout'] - $data['login']).'</tr></td>'."\n";
  2531. }
  2532. $result_to_print .= '</table>';
  2533. $result_to_print = array("result"=>$result_to_print);
  2534. return $result_to_print;
  2535. }
  2536. /**
  2537. * Converte an array to a table in html
  2538. *
  2539. * @param array $sql_result
  2540. * @author Jorge Frisancho Jibaja
  2541. * @version OCT-22- 2010
  2542. * @return string
  2543. */
  2544. function convert_to_string($sql_result){
  2545. $result_to_print = '<table>';
  2546. if (!empty($sql_result)) {
  2547. foreach ($sql_result as $key => $data) {
  2548. $result_to_print .= '<tr><td>'.date('d-m-Y (H:i:s)', $data['login']).'</td><td>'.api_time_to_hms($data['logout'] - $data['login']).'</tr></td>'."\n";
  2549. }
  2550. }
  2551. $result_to_print .= '</table>';
  2552. return $result_to_print;
  2553. }
  2554. /**
  2555. * This function draw the graphic to be displayed on the user view as an image
  2556. *
  2557. * @param array $sql_result
  2558. * @param string $start_date
  2559. * @param string $end_date
  2560. * @param string $type
  2561. * @author Jorge Frisancho Jibaja
  2562. * @version OCT-22- 2010
  2563. * @return string
  2564. */
  2565. function grapher($sql_result, $start_date, $end_date, $type = "")
  2566. {
  2567. if (empty($start_date)) { $start_date =""; }
  2568. if (empty($end_date)) { $end_date =""; }
  2569. if ($type == ""){ $type = 'day'; }
  2570. $main_year = $main_month_year = $main_day = [];
  2571. $period = new DatePeriod(
  2572. new DateTime($start_date),
  2573. new DateInterval('P1D'),
  2574. new DateTime($end_date)
  2575. );
  2576. foreach ($period as $date) {
  2577. $main_day[$date->format('d-m-Y')] = 0;
  2578. }
  2579. $period = new DatePeriod(
  2580. new DateTime($start_date),
  2581. new DateInterval('P1M'),
  2582. new DateTime($end_date)
  2583. );
  2584. foreach ($period as $date) {
  2585. $main_month_year[$date->format('m-Y')] = 0;
  2586. }
  2587. $i = 0;
  2588. if (is_array($sql_result) && count($sql_result) > 0) {
  2589. foreach ($sql_result as $key => $data) {
  2590. //creating the main array
  2591. if (isset($main_month_year[date('m-Y', $data['login'])])) {
  2592. $main_month_year[date('m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
  2593. }
  2594. if (isset($main_day[date('d-m-Y', $data['login'])])) {
  2595. $main_day[date('d-m-Y', $data['login'])] += float_format(($data['logout'] - $data['login']) / 60, 0);
  2596. }
  2597. if ($i > 500) {
  2598. break;
  2599. }
  2600. $i++;
  2601. }
  2602. switch ($type) {
  2603. case 'day':
  2604. $main_date = $main_day;
  2605. break;
  2606. case 'month':
  2607. $main_date = $main_month_year;
  2608. break;
  2609. case 'year':
  2610. $main_date = $main_year;
  2611. break;
  2612. }
  2613. // the nice graphics :D
  2614. $labels = array_keys($main_date);
  2615. if (count($main_date) == 1) {
  2616. $labels = $labels[0];
  2617. $main_date = $main_date[$labels];
  2618. }
  2619. /* Create and populate the pData object */
  2620. $myData = new pData();
  2621. $myData->addPoints($main_date, 'Serie1');
  2622. if (count($main_date)!= 1) {
  2623. $myData->addPoints($labels, 'Labels');
  2624. $myData->setSerieDescription('Labels', 'Months');
  2625. $myData->setAbscissa('Labels');
  2626. }
  2627. $myData->setSerieWeight('Serie1', 1);
  2628. $myData->setSerieDescription('Serie1', get_lang('MyResults'));
  2629. $myData->setAxisName(0, get_lang('Minutes'));
  2630. $myData->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  2631. // Cache definition
  2632. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  2633. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  2634. $chartHash = $myCache->getHash($myData);
  2635. if ($myCache->isInCache($chartHash)) {
  2636. //if we already created the img
  2637. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  2638. $myCache->saveFromCache($chartHash, $imgPath);
  2639. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  2640. } else {
  2641. /* Define width, height and angle */
  2642. $mainWidth = 760;
  2643. $mainHeight = 230;
  2644. $angle = 50;
  2645. /* Create the pChart object */
  2646. $myPicture = new pImage($mainWidth, $mainHeight, $myData);
  2647. /* Turn of Antialiasing */
  2648. $myPicture->Antialias = false;
  2649. /* Draw the background */
  2650. $settings = array("R" => 255, "G" => 255, "B" => 255);
  2651. $myPicture->drawFilledRectangle(0, 0, $mainWidth, $mainHeight, $settings);
  2652. /* Add a border to the picture */
  2653. $myPicture->drawRectangle(
  2654. 0,
  2655. 0,
  2656. $mainWidth - 1,
  2657. $mainHeight - 1,
  2658. array("R" => 0, "G" => 0, "B" => 0)
  2659. );
  2660. /* Set the default font */
  2661. $myPicture->setFontProperties(
  2662. array(
  2663. "FontName" => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  2664. "FontSize" => 10)
  2665. );
  2666. /* Write the chart title */
  2667. $myPicture->drawText(
  2668. $mainWidth / 2,
  2669. 30,
  2670. get_lang('TimeSpentInTheCourse'),
  2671. array(
  2672. "FontSize" => 12,
  2673. "Align" => TEXT_ALIGN_BOTTOMMIDDLE
  2674. )
  2675. );
  2676. /* Set the default font */
  2677. $myPicture->setFontProperties(
  2678. array(
  2679. "FontName" => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  2680. "FontSize" => 8
  2681. )
  2682. );
  2683. /* Define the chart area */
  2684. $myPicture->setGraphArea(50, 40, $mainWidth - 40, $mainHeight - 80);
  2685. /* Draw the scale */
  2686. $scaleSettings = array(
  2687. 'XMargin' => 10,
  2688. 'YMargin' => 10,
  2689. 'Floating' => true,
  2690. 'GridR' => 200,
  2691. 'GridG' => 200,
  2692. 'GridB' => 200,
  2693. 'DrawSubTicks' => true,
  2694. 'CycleBackground' => true,
  2695. 'LabelRotation' => $angle,
  2696. 'Mode' => SCALE_MODE_ADDALL_START0,
  2697. );
  2698. $myPicture->drawScale($scaleSettings);
  2699. /* Turn on Antialiasing */
  2700. $myPicture->Antialias = true;
  2701. /* Enable shadow computing */
  2702. $myPicture->setShadow(
  2703. true,
  2704. array(
  2705. "X" => 1,
  2706. "Y" => 1,
  2707. "R" => 0,
  2708. "G" => 0,
  2709. "B" => 0,
  2710. "Alpha" => 10
  2711. )
  2712. );
  2713. /* Draw the line chart */
  2714. $myPicture->setFontProperties(
  2715. array(
  2716. "FontName" => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  2717. "FontSize" => 10
  2718. )
  2719. );
  2720. $myPicture->drawSplineChart();
  2721. $myPicture->drawPlotChart(
  2722. array(
  2723. "DisplayValues" => true,
  2724. "PlotBorder" => true,
  2725. "BorderSize" => 1,
  2726. "Surrounding" => -60,
  2727. "BorderAlpha" => 80
  2728. )
  2729. );
  2730. /* Do NOT Write the chart legend */
  2731. /* Write and save into cache */
  2732. $myCache->writeToCache($chartHash, $myPicture);
  2733. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  2734. $myCache->saveFromCache($chartHash, $imgPath);
  2735. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  2736. }
  2737. $html = '<img src="' . $imgPath . '">';
  2738. return $html;
  2739. } else {
  2740. $foo_img = api_convert_encoding('<div id="messages" class="warning-message">'.get_lang('GraphicNotAvailable').'</div>','UTF-8');
  2741. return $foo_img;
  2742. }
  2743. }