myspace.lib.php 123 KB

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