myspace.lib.php 124 KB

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