myspace.lib.php 128 KB

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