myspace.lib.php 123 KB

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