statistics.lib.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This class provides some functions for statistics.
  5. *
  6. * @package chamilo.statistics
  7. */
  8. class Statistics
  9. {
  10. /**
  11. * Converts a number of bytes in a formatted string.
  12. *
  13. * @param int $size
  14. *
  15. * @return string Formatted file size
  16. */
  17. public static function makeSizeString($size)
  18. {
  19. if ($size < pow(2, 10)) {
  20. return $size." bytes";
  21. }
  22. if ($size >= pow(2, 10) && $size < pow(2, 20)) {
  23. return round($size / pow(2, 10), 0)." KB";
  24. }
  25. if ($size >= pow(2, 20) && $size < pow(2, 30)) {
  26. return round($size / pow(2, 20), 1)." MB";
  27. }
  28. if ($size > pow(2, 30)) {
  29. return round($size / pow(2, 30), 2)." GB";
  30. }
  31. }
  32. /**
  33. * Count courses.
  34. *
  35. * @param string $categoryCode Code of a course category.
  36. * Default: count all courses.
  37. *
  38. * @return int Number of courses counted
  39. */
  40. public static function countCourses($categoryCode = null)
  41. {
  42. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  43. $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  44. $urlId = api_get_current_access_url_id();
  45. if (api_is_multiple_url_enabled()) {
  46. $sql = "SELECT COUNT(*) AS number
  47. FROM ".$course_table." as c, $access_url_rel_course_table as u
  48. WHERE u.c_id = c.id AND access_url_id='".$urlId."'";
  49. if (isset($categoryCode)) {
  50. $sql .= " AND category_code = '".Database::escape_string($categoryCode)."'";
  51. }
  52. } else {
  53. $sql = "SELECT COUNT(*) AS number
  54. FROM $course_table";
  55. if (isset($categoryCode)) {
  56. $sql .= " WHERE category_code = '".Database::escape_string($categoryCode)."'";
  57. }
  58. }
  59. $res = Database::query($sql);
  60. $obj = Database::fetch_object($res);
  61. return $obj->number;
  62. }
  63. /**
  64. * Count courses by visibility.
  65. *
  66. * @param int $visibility visibility (0 = closed, 1 = private, 2 = open, 3 = public) all courses
  67. *
  68. * @return int Number of courses counted
  69. */
  70. public static function countCoursesByVisibility($visibility = null)
  71. {
  72. if (!isset($visibility)) {
  73. return 0;
  74. }
  75. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  76. $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  77. $urlId = api_get_current_access_url_id();
  78. if (api_is_multiple_url_enabled()) {
  79. $sql = "SELECT COUNT(*) AS number
  80. FROM $course_table as c, $access_url_rel_course_table as u
  81. WHERE u.c_id = c.id AND access_url_id='".$urlId."'";
  82. if (isset($visibility)) {
  83. $sql .= " AND visibility = ".intval($visibility);
  84. }
  85. } else {
  86. $sql = "SELECT COUNT(*) AS number FROM $course_table ";
  87. if (isset($visibility)) {
  88. $sql .= " WHERE visibility = ".intval($visibility);
  89. }
  90. }
  91. $res = Database::query($sql);
  92. $obj = Database::fetch_object($res);
  93. return $obj->number;
  94. }
  95. /**
  96. * Count users.
  97. *
  98. * @param int $status user status (COURSEMANAGER or STUDENT) if not setted it'll count all users
  99. * @param string $categoryCode course category code. Default: count only users without filtering category
  100. * @param bool $countInvisibleCourses Count invisible courses (todo)
  101. * @param bool $onlyActive Count only active users (false to only return currently active users)
  102. *
  103. * @return int Number of users counted
  104. */
  105. public static function countUsers(
  106. $status = null,
  107. $categoryCode = null,
  108. $countInvisibleCourses = true,
  109. $onlyActive = false
  110. ) {
  111. // Database table definitions
  112. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  113. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  114. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  115. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  116. $urlId = api_get_current_access_url_id();
  117. $active_filter = $onlyActive ? ' AND active=1' : '';
  118. $status_filter = isset($status) ? ' AND status = '.intval($status) : '';
  119. if (api_is_multiple_url_enabled()) {
  120. $sql = "SELECT COUNT(DISTINCT(u.user_id)) AS number
  121. FROM $user_table as u, $access_url_rel_user_table as url
  122. WHERE
  123. u.user_id = url.user_id AND
  124. access_url_id = '".$urlId."'
  125. $status_filter $active_filter";
  126. if (isset($categoryCode)) {
  127. $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number
  128. FROM $course_user_table cu, $course_table c, $access_url_rel_user_table as url
  129. WHERE
  130. c.id = cu.c_id AND
  131. c.category_code = '".Database::escape_string($categoryCode)."' AND
  132. cu.user_id = url.user_id AND
  133. access_url_id='".$urlId."'
  134. $status_filter $active_filter";
  135. }
  136. } else {
  137. $sql = "SELECT COUNT(DISTINCT(user_id)) AS number
  138. FROM $user_table
  139. WHERE 1=1 $status_filter $active_filter";
  140. if (isset($categoryCode)) {
  141. $status_filter = isset($status) ? ' AND status = '.intval($status) : '';
  142. $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number
  143. FROM $course_user_table cu, $course_table c
  144. WHERE
  145. c.id = cu.c_id AND
  146. c.category_code = '".Database::escape_string($categoryCode)."'
  147. $status_filter
  148. $active_filter
  149. ";
  150. }
  151. }
  152. $res = Database::query($sql);
  153. $obj = Database::fetch_object($res);
  154. return $obj->number;
  155. }
  156. /**
  157. * Count activities from track_e_default_table.
  158. *
  159. * @return int Number of activities counted
  160. */
  161. public static function getNumberOfActivities($courseId = 0, $sessionId = 0)
  162. {
  163. // Database table definitions
  164. $track_e_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  165. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  166. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  167. $urlId = api_get_current_access_url_id();
  168. if (api_is_multiple_url_enabled()) {
  169. $sql = "SELECT count(default_id) AS total_number_of_items
  170. FROM $track_e_default, $table_user user, $access_url_rel_user_table url
  171. WHERE
  172. default_user_id = user.user_id AND
  173. user.user_id=url.user_id AND
  174. access_url_id = '".$urlId."'";
  175. } else {
  176. $sql = "SELECT count(default_id) AS total_number_of_items
  177. FROM $track_e_default, $table_user user
  178. WHERE default_user_id = user.user_id ";
  179. }
  180. if (!empty($courseId)) {
  181. $courseId = (int) $courseId;
  182. $sql .= " AND c_id = $courseId";
  183. $sql .= api_get_session_condition($sessionId);
  184. }
  185. if (isset($_GET['keyword'])) {
  186. $keyword = Database::escape_string(trim($_GET['keyword']));
  187. $sql .= " AND (
  188. user.username LIKE '%".$keyword."%' OR
  189. default_event_type LIKE '%".$keyword."%' OR
  190. default_value_type LIKE '%".$keyword."%' OR
  191. default_value LIKE '%".$keyword."%') ";
  192. }
  193. $res = Database::query($sql);
  194. $obj = Database::fetch_object($res);
  195. return $obj->total_number_of_items;
  196. }
  197. /**
  198. * Get activities data to display.
  199. *
  200. * @param int $from
  201. * @param int $numberOfItems
  202. * @param int $column
  203. * @param string $direction
  204. * @param int $courseId
  205. * @param int $sessionId
  206. *
  207. * @return array
  208. */
  209. public static function getActivitiesData(
  210. $from,
  211. $numberOfItems,
  212. $column,
  213. $direction,
  214. $courseId = 0,
  215. $sessionId = 0
  216. ) {
  217. $track_e_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
  218. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  219. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  220. $urlId = api_get_current_access_url_id();
  221. $column = intval($column);
  222. $from = intval($from);
  223. $numberOfItems = intval($numberOfItems);
  224. $direction = strtoupper($direction);
  225. if (!in_array($direction, ['ASC', 'DESC'])) {
  226. $direction = 'DESC';
  227. }
  228. if (api_is_multiple_url_enabled()) {
  229. $sql = "SELECT
  230. default_event_type as col0,
  231. default_value_type as col1,
  232. default_value as col2,
  233. c_id as col3,
  234. session_id as col4,
  235. user.username as col5,
  236. user.user_id as col6,
  237. default_date as col7
  238. FROM $track_e_default as track_default,
  239. $table_user as user,
  240. $access_url_rel_user_table as url
  241. WHERE
  242. track_default.default_user_id = user.user_id AND
  243. url.user_id = user.user_id AND
  244. access_url_id= $urlId ";
  245. } else {
  246. $sql = "SELECT
  247. default_event_type as col0,
  248. default_value_type as col1,
  249. default_value as col2,
  250. c_id as col3,
  251. session_id as col4,
  252. user.username as col5,
  253. user.user_id as col6,
  254. default_date as col7
  255. FROM $track_e_default track_default, $table_user user
  256. WHERE track_default.default_user_id = user.user_id ";
  257. }
  258. if (!empty($_GET['keyword'])) {
  259. $keyword = Database::escape_string(trim($_GET['keyword']));
  260. $sql .= " AND (user.username LIKE '%".$keyword."%' OR
  261. default_event_type LIKE '%".$keyword."%' OR
  262. default_value_type LIKE '%".$keyword."%' OR
  263. default_value LIKE '%".$keyword."%') ";
  264. }
  265. if (!empty($courseId)) {
  266. $courseId = (int) $courseId;
  267. $sql .= " AND c_id = $courseId";
  268. $sql .= api_get_session_condition($sessionId);
  269. }
  270. if (!empty($column) && !empty($direction)) {
  271. $sql .= " ORDER BY col$column $direction";
  272. } else {
  273. $sql .= " ORDER BY col7 DESC ";
  274. }
  275. $sql .= " LIMIT $from, $numberOfItems ";
  276. $res = Database::query($sql);
  277. $activities = [];
  278. while ($row = Database::fetch_row($res)) {
  279. if (strpos($row[1], '_object') === false &&
  280. strpos($row[1], '_array') === false
  281. ) {
  282. $row[2] = $row[2];
  283. } else {
  284. if (!empty($row[2])) {
  285. $originalData = str_replace('\\', '', $row[2]);
  286. $row[2] = UnserializeApi::unserialize('not_allowed_classes', $originalData);
  287. if (is_array($row[2]) && !empty($row[2])) {
  288. $row[2] = implode_with_key(', ', $row[2]);
  289. } else {
  290. $row[2] = $originalData;
  291. }
  292. }
  293. }
  294. if (!empty($row['default_date'])) {
  295. $row['default_date'] = api_get_local_time($row['default_date']);
  296. } else {
  297. $row['default_date'] = '-';
  298. }
  299. if (!empty($row[5])) {
  300. // Course
  301. if (!empty($row[3])) {
  302. $row[3] = Display::url(
  303. $row[3],
  304. api_get_path(WEB_CODE_PATH).'admin/course_edit.php?id='.$row[3]
  305. );
  306. } else {
  307. $row[3] = '-';
  308. }
  309. // session
  310. if (!empty($row[4])) {
  311. $row[4] = Display::url(
  312. $row[4],
  313. api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$row[4]
  314. );
  315. } else {
  316. $row[4] = '-';
  317. }
  318. // User id.
  319. $row[5] = Display::url(
  320. $row[5],
  321. api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$row[6],
  322. ['class' => 'ajax']
  323. );
  324. $row[6] = Tracking::get_ip_from_user_event(
  325. $row[6],
  326. $row[7],
  327. true
  328. );
  329. if (empty($row[6])) {
  330. $row[6] = get_lang('Unknown');
  331. }
  332. }
  333. $activities[] = $row;
  334. }
  335. return $activities;
  336. }
  337. /**
  338. * Get all course categories.
  339. *
  340. * @return array All course categories (code => name)
  341. */
  342. public static function getCourseCategories()
  343. {
  344. $categoryTable = Database::get_main_table(TABLE_MAIN_CATEGORY);
  345. $sql = "SELECT code, name
  346. FROM $categoryTable
  347. ORDER BY tree_pos";
  348. $res = Database::query($sql);
  349. $categories = [];
  350. while ($category = Database::fetch_object($res)) {
  351. $categories[$category->code] = $category->name;
  352. }
  353. return $categories;
  354. }
  355. /**
  356. * Rescale data.
  357. *
  358. * @param array $data The data that should be rescaled
  359. * @param int $max The maximum value in the rescaled data (default = 500);
  360. *
  361. * @return array The rescaled data, same key as $data
  362. */
  363. public static function rescale($data, $max = 500)
  364. {
  365. $data_max = 1;
  366. foreach ($data as $index => $value) {
  367. $data_max = ($data_max < $value ? $value : $data_max);
  368. }
  369. reset($data);
  370. $result = [];
  371. $delta = $max / $data_max;
  372. foreach ($data as $index => $value) {
  373. $result[$index] = (int) round($value * $delta);
  374. }
  375. return $result;
  376. }
  377. /**
  378. * Show statistics.
  379. *
  380. * @param string $title The title
  381. * @param array $stats
  382. * @param bool $showTotal
  383. * @param bool $isFileSize
  384. */
  385. public static function printStats(
  386. $title,
  387. $stats,
  388. $showTotal = true,
  389. $isFileSize = false
  390. ) {
  391. $total = 0;
  392. $data = self::rescale($stats);
  393. echo '<table class="data_table" cellspacing="0" cellpadding="3">
  394. <tr><th colspan="'.($showTotal ? '4' : '3').'">'.$title.'</th></tr>';
  395. $i = 0;
  396. foreach ($stats as $subtitle => $number) {
  397. $total += $number;
  398. }
  399. foreach ($stats as $subtitle => $number) {
  400. if (!$isFileSize) {
  401. $number_label = number_format($number, 0, ',', '.');
  402. } else {
  403. $number_label = self::makeSizeString($number);
  404. }
  405. $percentage = ($total > 0 ? number_format(100 * $number / $total, 1, ',', '.') : '0');
  406. echo '<tr class="row_'.($i % 2 == 0 ? 'odd' : 'even').'">
  407. <td width="150">'.$subtitle.'</td>
  408. <td width="550">'.Display::bar_progress($percentage, false).'</td>
  409. <td align="right">'.$number_label.'</td>';
  410. if ($showTotal) {
  411. echo '<td align="right"> '.$percentage.'%</td>';
  412. }
  413. echo '</tr>';
  414. $i++;
  415. }
  416. if ($showTotal) {
  417. if (!$isFileSize) {
  418. $total_label = number_format($total, 0, ',', '.');
  419. } else {
  420. $total_label = self::makeSizeString($total);
  421. }
  422. echo '<tr><th colspan="4" align="right">'.get_lang('Total').': '.$total_label.'</td></tr>';
  423. }
  424. echo '</table>';
  425. }
  426. /**
  427. * Show some stats about the number of logins.
  428. *
  429. * @param string $type month, hour or day
  430. */
  431. public static function printLoginStats($type)
  432. {
  433. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  434. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  435. $urlId = api_get_current_access_url_id();
  436. $table_url = null;
  437. $where_url = null;
  438. $now = api_get_utc_datetime();
  439. $where_url_last = ' WHERE login_date > DATE_SUB("'.$now.'",INTERVAL 1 %s)';
  440. if (api_is_multiple_url_enabled()) {
  441. $table_url = ", $access_url_rel_user_table";
  442. $where_url = " WHERE login_user_id=user_id AND access_url_id='".$urlId."'";
  443. $where_url_last = ' AND login_date > DATE_SUB("'.$now.'",INTERVAL 1 %s)';
  444. }
  445. $period = get_lang('PeriodMonth');
  446. $periodCollection = api_get_months_long();
  447. $sql = "SELECT
  448. DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date ,
  449. count( login_id ) AS number_of_logins
  450. FROM $table $table_url $where_url
  451. GROUP BY stat_date
  452. ORDER BY login_date DESC";
  453. $sql_last_x = null;
  454. switch ($type) {
  455. case 'hour':
  456. $period = get_lang('PeriodHour');
  457. $sql = "SELECT
  458. DATE_FORMAT( login_date, '%H') AS stat_date,
  459. count( login_id ) AS number_of_logins
  460. FROM $table $table_url $where_url
  461. GROUP BY stat_date
  462. ORDER BY stat_date ";
  463. $sql_last_x = "SELECT
  464. DATE_FORMAT( login_date, '%H' ) AS stat_date,
  465. count( login_id ) AS number_of_logins
  466. FROM $table $table_url $where_url ".sprintf($where_url_last, 'DAY')."
  467. GROUP BY stat_date
  468. ORDER BY stat_date ";
  469. break;
  470. case 'day':
  471. $periodCollection = api_get_week_days_long();
  472. $period = get_lang('PeriodDay');
  473. $sql = "SELECT DATE_FORMAT( login_date, '%w' ) AS stat_date ,
  474. count( login_id ) AS number_of_logins
  475. FROM $table $table_url $where_url
  476. GROUP BY stat_date
  477. ORDER BY DATE_FORMAT( login_date, '%w' ) ";
  478. $sql_last_x = "SELECT
  479. DATE_FORMAT( login_date, '%w' ) AS stat_date,
  480. count( login_id ) AS number_of_logins
  481. FROM $table $table_url $where_url ".sprintf($where_url_last, 'WEEK')."
  482. GROUP BY stat_date
  483. ORDER BY DATE_FORMAT( login_date, '%w' ) ";
  484. break;
  485. }
  486. if ($sql_last_x) {
  487. $res_last_x = Database::query($sql_last_x);
  488. $result_last_x = [];
  489. while ($obj = Database::fetch_object($res_last_x)) {
  490. $stat_date = ($type === 'day') ? $periodCollection[$obj->stat_date] : $obj->stat_date;
  491. $result_last_x[$stat_date] = $obj->number_of_logins;
  492. }
  493. self::printStats(get_lang('LastLogins').' ('.$period.')', $result_last_x, true);
  494. flush(); //flush web request at this point to see something already while the full data set is loading
  495. echo '<br />';
  496. }
  497. $res = Database::query($sql);
  498. $result = [];
  499. while ($obj = Database::fetch_object($res)) {
  500. $stat_date = $obj->stat_date;
  501. switch ($type) {
  502. case 'month':
  503. $stat_date = explode('-', $stat_date);
  504. $stat_date[1] = $periodCollection[$stat_date[1] - 1];
  505. $stat_date = implode(' ', $stat_date);
  506. break;
  507. case 'day':
  508. $stat_date = $periodCollection[$stat_date];
  509. break;
  510. }
  511. $result[$stat_date] = $obj->number_of_logins;
  512. }
  513. self::printStats(get_lang('AllLogins').' ('.$period.')', $result, true);
  514. }
  515. /**
  516. * Print the number of recent logins.
  517. *
  518. * @param bool $distinct whether to only give distinct users stats, or *all* logins
  519. * @param int $sessionDuration
  520. */
  521. public static function printRecentLoginStats($distinct = false, $sessionDuration = 0)
  522. {
  523. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  524. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  525. $urlId = api_get_current_access_url_id();
  526. $table_url = '';
  527. $where_url = '';
  528. if (api_is_multiple_url_enabled()) {
  529. $table_url = ", $access_url_rel_user_table";
  530. $where_url = " AND login_user_id=user_id AND access_url_id='".$urlId."'";
  531. }
  532. $now = api_get_utc_datetime();
  533. $field = 'login_id';
  534. if ($distinct) {
  535. $field = 'DISTINCT(login_user_id)';
  536. }
  537. $days = [1, 7, 15, 31];
  538. $sqlList = [];
  539. $sessionDuration = (int) $sessionDuration;
  540. foreach ($days as $day) {
  541. $date = new DateTime($now);
  542. $startDate = $date->format('Y-m-d').' 00:00:00';
  543. $endDate = $date->format('Y-m-d').' 23:59:59';
  544. if ($day > 1) {
  545. $startDate = $date->sub(new DateInterval('P'.$day.'D'));
  546. $startDate = $startDate->format('Y-m-d').' 00:00:00';
  547. }
  548. $localDate = api_get_local_time($startDate, null, null, false, false);
  549. $localEndDate = api_get_local_time($endDate, null, null, false, false);
  550. $label = sprintf(get_lang('LastXDays'), $day);
  551. if ($day == 1) {
  552. $label = get_lang('Today');
  553. }
  554. $label .= " <br /> $localDate - $localEndDate";
  555. $sql = "SELECT count($field) AS number
  556. FROM $table $table_url
  557. WHERE
  558. UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date) > $sessionDuration AND
  559. login_date BETWEEN '$startDate' AND '$endDate'
  560. $where_url";
  561. $sqlList[$label] = $sql;
  562. }
  563. $sql = "SELECT count($field) AS number
  564. FROM $table $table_url
  565. WHERE UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date) > $sessionDuration $where_url
  566. ";
  567. $sqlList[get_lang('Total')] = $sql;
  568. $totalLogin = [];
  569. foreach ($sqlList as $label => $query) {
  570. $res = Database::query($query);
  571. $obj = Database::fetch_object($res);
  572. $totalLogin[$label] = $obj->number;
  573. }
  574. if ($distinct) {
  575. self::printStats(get_lang('DistinctUsersLogins'), $totalLogin, false);
  576. } else {
  577. self::printStats(get_lang('Logins'), $totalLogin, false);
  578. }
  579. }
  580. /**
  581. * get the number of recent logins.
  582. *
  583. * @param bool $distinct Whether to only give distinct users stats, or *all* logins
  584. * @param int $sessionDuration
  585. * @param bool $completeMissingDays Whether to fill the daily gaps (if any) when getting a list of logins
  586. *
  587. * @return array
  588. */
  589. public static function getRecentLoginStats($distinct = false, $sessionDuration = 0, $completeMissingDays = true)
  590. {
  591. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  592. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  593. $urlId = api_get_current_access_url_id();
  594. $table_url = '';
  595. $where_url = '';
  596. if (api_is_multiple_url_enabled()) {
  597. $table_url = ", $access_url_rel_user_table";
  598. $where_url = " AND login_user_id=user_id AND access_url_id='".$urlId."'";
  599. }
  600. $now = api_get_utc_datetime();
  601. $date = new DateTime($now);
  602. $date->sub(new DateInterval('P15D'));
  603. $newDate = $date->format('Y-m-d h:i:s');
  604. $totalLogin = self::buildDatesArray($newDate, $now, true);
  605. $field = 'login_id';
  606. if ($distinct) {
  607. $field = 'DISTINCT(login_user_id)';
  608. }
  609. $sessionDuration = (int) $sessionDuration;
  610. $sql = "SELECT count($field) AS number, date(login_date) as login_date
  611. FROM $table $table_url
  612. WHERE
  613. UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date) > $sessionDuration AND
  614. login_date >= '$newDate' $where_url
  615. GROUP BY date(login_date)";
  616. $res = Database::query($sql);
  617. while ($row = Database::fetch_array($res, 'ASSOC')) {
  618. $monthAndDay = substr($row['login_date'], 5, 5);
  619. $totalLogin[$monthAndDay] = $row['number'];
  620. }
  621. return $totalLogin;
  622. }
  623. /**
  624. * Get course tools usage statistics for the whole platform (by URL if multi-url).
  625. */
  626. public static function getToolsStats()
  627. {
  628. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  629. $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  630. $urlId = api_get_current_access_url_id();
  631. $tools = [
  632. 'announcement',
  633. 'assignment',
  634. 'calendar_event',
  635. 'chat',
  636. 'course_description',
  637. 'document',
  638. 'dropbox',
  639. 'group',
  640. 'learnpath',
  641. 'link',
  642. 'quiz',
  643. 'student_publication',
  644. 'user',
  645. 'forum',
  646. ];
  647. $tool_names = [];
  648. foreach ($tools as $tool) {
  649. $tool_names[$tool] = get_lang(ucfirst($tool), '');
  650. }
  651. if (api_is_multiple_url_enabled()) {
  652. $sql = "SELECT access_tool, count( access_id ) AS number_of_logins
  653. FROM $table t , $access_url_rel_course_table a
  654. WHERE
  655. access_tool IN ('".implode("','", $tools)."') AND
  656. t.c_id = a.c_id AND
  657. access_url_id='".$urlId."'
  658. GROUP BY access_tool
  659. ";
  660. } else {
  661. $sql = "SELECT access_tool, count( access_id ) AS number_of_logins
  662. FROM $table
  663. WHERE access_tool IN ('".implode("','", $tools)."')
  664. GROUP BY access_tool ";
  665. }
  666. $res = Database::query($sql);
  667. $result = [];
  668. while ($obj = Database::fetch_object($res)) {
  669. $result[$tool_names[$obj->access_tool]] = $obj->number_of_logins;
  670. }
  671. return $result;
  672. }
  673. /**
  674. * Show some stats about the accesses to the different course tools.
  675. *
  676. * @param array $result If defined, this serves as data. Otherwise, will get the data from getToolsStats()
  677. */
  678. public static function printToolStats($result = null)
  679. {
  680. if (empty($result)) {
  681. $result = self::getToolsStats();
  682. }
  683. self::printStats(get_lang('PlatformToolAccess'), $result, true);
  684. }
  685. /**
  686. * Show some stats about the number of courses per language.
  687. */
  688. public static function printCourseByLanguageStats()
  689. {
  690. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  691. $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  692. $urlId = api_get_current_access_url_id();
  693. if (api_is_multiple_url_enabled()) {
  694. $sql = "SELECT course_language, count( c.code ) AS number_of_courses
  695. FROM $table as c, $access_url_rel_course_table as u
  696. WHERE u.c_id = c.id AND access_url_id='".$urlId."'
  697. GROUP BY course_language
  698. ORDER BY number_of_courses DESC";
  699. } else {
  700. $sql = "SELECT course_language, count( code ) AS number_of_courses
  701. FROM $table GROUP BY course_language
  702. ORDER BY number_of_courses DESC";
  703. }
  704. $res = Database::query($sql);
  705. $result = [];
  706. while ($obj = Database::fetch_object($res)) {
  707. $result[$obj->course_language] = $obj->number_of_courses;
  708. }
  709. return $result;
  710. }
  711. /**
  712. * Shows the number of users having their picture uploaded in Dokeos.
  713. */
  714. public static function printUserPicturesStats()
  715. {
  716. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  717. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  718. $urlId = api_get_current_access_url_id();
  719. $url_condition = null;
  720. $url_condition2 = null;
  721. $table = null;
  722. if (api_is_multiple_url_enabled()) {
  723. $url_condition = ", $access_url_rel_user_table as url WHERE url.user_id=u.user_id AND access_url_id='".$urlId."'";
  724. $url_condition2 = " AND url.user_id=u.user_id AND access_url_id='".$urlId."'";
  725. $table = ", $access_url_rel_user_table as url ";
  726. }
  727. $sql = "SELECT COUNT(*) AS n FROM $user_table as u ".$url_condition;
  728. $res = Database::query($sql);
  729. $count1 = Database::fetch_object($res);
  730. $sql = "SELECT COUNT(*) AS n FROM $user_table as u $table ".
  731. "WHERE LENGTH(picture_uri) > 0 $url_condition2";
  732. $res = Database::query($sql);
  733. $count2 = Database::fetch_object($res);
  734. // #users without picture
  735. $result[get_lang('No')] = $count1->n - $count2->n;
  736. $result[get_lang('Yes')] = $count2->n; // #users with picture
  737. self::printStats(get_lang('CountUsers').' ('.get_lang('UserPicture').')', $result, true);
  738. }
  739. /**
  740. * Important activities.
  741. */
  742. public static function printActivitiesStats()
  743. {
  744. echo '<h4>'.get_lang('ImportantActivities').'</h4>';
  745. // Create a search-box
  746. $form = new FormValidator(
  747. 'search_simple',
  748. 'get',
  749. api_get_path(WEB_CODE_PATH).'admin/statistics/index.php',
  750. '',
  751. 'width=200px',
  752. false
  753. );
  754. $renderer = &$form->defaultRenderer();
  755. $renderer->setCustomElementTemplate('<span>{element}</span> ');
  756. $form->addHidden('report', 'activities');
  757. $form->addHidden('activities_direction', 'DESC');
  758. $form->addHidden('activities_column', '4');
  759. $form->addElement('text', 'keyword', get_lang('Keyword'));
  760. $form->addButtonSearch(get_lang('Search'), 'submit');
  761. echo '<div class="actions">';
  762. $form->display();
  763. echo '</div>';
  764. $table = new SortableTable(
  765. 'activities',
  766. ['Statistics', 'getNumberOfActivities'],
  767. ['Statistics', 'getActivitiesData'],
  768. 7,
  769. 50,
  770. 'DESC'
  771. );
  772. $parameters = [];
  773. $parameters['report'] = 'activities';
  774. if (isset($_GET['keyword'])) {
  775. $parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
  776. }
  777. $table->set_additional_parameters($parameters);
  778. $table->set_header(0, get_lang('EventType'));
  779. $table->set_header(1, get_lang('DataType'));
  780. $table->set_header(2, get_lang('Value'));
  781. $table->set_header(3, get_lang('Course'));
  782. $table->set_header(4, get_lang('Session'));
  783. $table->set_header(5, get_lang('UserName'));
  784. $table->set_header(6, get_lang('IPAddress'));
  785. $table->set_header(7, get_lang('Date'));
  786. $table->display();
  787. }
  788. /**
  789. * Shows statistics about the time of last visit to each course.
  790. */
  791. public static function printCourseLastVisit()
  792. {
  793. $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  794. $urlId = api_get_current_access_url_id();
  795. $columns[0] = 't.c_id';
  796. $columns[1] = 'access_date';
  797. $sql_order[SORT_ASC] = 'ASC';
  798. $sql_order[SORT_DESC] = 'DESC';
  799. $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
  800. $page_nr = isset($_GET['page_nr']) ? intval($_GET['page_nr']) : 1;
  801. $column = isset($_GET['column']) ? intval($_GET['column']) : 0;
  802. $direction = isset($_GET['direction']) ? $_GET['direction'] : SORT_ASC;
  803. if (!in_array($direction, [SORT_ASC, SORT_DESC])) {
  804. $direction = SORT_ASC;
  805. }
  806. $form = new FormValidator('courselastvisit', 'get');
  807. $form->addElement('hidden', 'report', 'courselastvisit');
  808. $form->addText('date_diff', get_lang('Days'), true);
  809. $form->addRule('date_diff', 'InvalidNumber', 'numeric');
  810. $form->addButtonSearch(get_lang('Search'), 'submit');
  811. if (!isset($_GET['date_diff'])) {
  812. $defaults['date_diff'] = 60;
  813. } else {
  814. $defaults['date_diff'] = Security::remove_XSS($_GET['date_diff']);
  815. }
  816. $form->setDefaults($defaults);
  817. $form->display();
  818. $values = $form->exportValues();
  819. $date_diff = $values['date_diff'];
  820. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  821. if (api_is_multiple_url_enabled()) {
  822. $sql = "SELECT * FROM $table t , $access_url_rel_course_table a
  823. WHERE
  824. t.c_id = a.c_id AND
  825. access_url_id='".$urlId."'
  826. GROUP BY t.c_id
  827. HAVING t.c_id <> ''
  828. AND DATEDIFF( '".api_get_utc_datetime()."' , access_date ) <= ".$date_diff;
  829. } else {
  830. $sql = "SELECT * FROM $table t
  831. GROUP BY t.c_id
  832. HAVING t.c_id <> ''
  833. AND DATEDIFF( '".api_get_utc_datetime()."' , access_date ) <= ".$date_diff;
  834. }
  835. $sql .= ' ORDER BY '.$columns[$column].' '.$sql_order[$direction];
  836. $from = ($page_nr - 1) * $per_page;
  837. $sql .= ' LIMIT '.$from.','.$per_page;
  838. echo '<p>'.get_lang('LastAccess').' &gt;= '.$date_diff.' '.get_lang('Days').'</p>';
  839. $res = Database::query($sql);
  840. if (Database::num_rows($res) > 0) {
  841. $courses = [];
  842. while ($obj = Database::fetch_object($res)) {
  843. $courseInfo = api_get_course_info_by_id($obj->c_id);
  844. $course = [];
  845. $course[] = '<a href="'.api_get_path(WEB_COURSE_PATH).$courseInfo['code'].'">'.$courseInfo['code'].' <a>';
  846. // Allow sort by date hiding the numerical date
  847. $course[] = '<span style="display:none;">'.$obj->access_date.'</span>'.api_convert_and_format_date($obj->access_date);
  848. $courses[] = $course;
  849. }
  850. $parameters['date_diff'] = $date_diff;
  851. $parameters['report'] = 'courselastvisit';
  852. $table_header[] = [get_lang("CourseCode"), true];
  853. $table_header[] = [get_lang("LastAccess"), true];
  854. Display:: display_sortable_table(
  855. $table_header,
  856. $courses,
  857. ['column' => $column, 'direction' => $direction],
  858. [],
  859. $parameters
  860. );
  861. } else {
  862. echo get_lang('NoSearchResults');
  863. }
  864. }
  865. /**
  866. * Displays the statistics of the messages sent and received by each user in the social network.
  867. *
  868. * @param string $messageType Type of message: 'sent' or 'received'
  869. *
  870. * @return array Message list
  871. */
  872. public static function getMessages($messageType)
  873. {
  874. $message_table = Database::get_main_table(TABLE_MESSAGE);
  875. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  876. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  877. $urlId = api_get_current_access_url_id();
  878. switch ($messageType) {
  879. case 'sent':
  880. $field = 'user_sender_id';
  881. break;
  882. case 'received':
  883. $field = 'user_receiver_id';
  884. break;
  885. }
  886. if (api_is_multiple_url_enabled()) {
  887. $sql = "SELECT lastname, firstname, username, COUNT($field) AS count_message
  888. FROM $access_url_rel_user_table as url, $message_table m
  889. LEFT JOIN $user_table u ON m.$field = u.user_id
  890. WHERE url.user_id = m.$field AND access_url_id='".$urlId."'
  891. GROUP BY m.$field
  892. ORDER BY count_message DESC ";
  893. } else {
  894. $sql = "SELECT lastname, firstname, username, COUNT($field) AS count_message
  895. FROM $message_table m
  896. LEFT JOIN $user_table u ON m.$field = u.user_id
  897. GROUP BY m.$field ORDER BY count_message DESC ";
  898. }
  899. $res = Database::query($sql);
  900. $messages_sent = [];
  901. while ($messages = Database::fetch_array($res)) {
  902. if (empty($messages['username'])) {
  903. $messages['username'] = get_lang('Unknown');
  904. }
  905. $users = api_get_person_name(
  906. $messages['firstname'],
  907. $messages['lastname']
  908. ).'<br />('.$messages['username'].')';
  909. $messages_sent[$users] = $messages['count_message'];
  910. }
  911. return $messages_sent;
  912. }
  913. /**
  914. * Count the number of friends for social network users.
  915. */
  916. public static function getFriends()
  917. {
  918. $user_friend_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
  919. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  920. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  921. $urlId = api_get_current_access_url_id();
  922. if (api_is_multiple_url_enabled()) {
  923. $sql = "SELECT lastname, firstname, username, COUNT(friend_user_id) AS count_friend
  924. FROM $access_url_rel_user_table as url, $user_friend_table uf
  925. LEFT JOIN $user_table u
  926. ON (uf.user_id = u.user_id)
  927. WHERE
  928. uf.relation_type <> '".USER_RELATION_TYPE_RRHH."' AND
  929. uf.user_id = url.user_id AND
  930. access_url_id = '".$urlId."'
  931. GROUP BY uf.user_id
  932. ORDER BY count_friend DESC ";
  933. } else {
  934. $sql = "SELECT lastname, firstname, username, COUNT(friend_user_id) AS count_friend
  935. FROM $user_friend_table uf
  936. LEFT JOIN $user_table u
  937. ON (uf.user_id = u.user_id)
  938. WHERE uf.relation_type <> '".USER_RELATION_TYPE_RRHH."'
  939. GROUP BY uf.user_id
  940. ORDER BY count_friend DESC ";
  941. }
  942. $res = Database::query($sql);
  943. $list_friends = [];
  944. while ($friends = Database::fetch_array($res)) {
  945. $users = api_get_person_name($friends['firstname'], $friends['lastname']).'<br />('.$friends['username'].')';
  946. $list_friends[$users] = $friends['count_friend'];
  947. }
  948. return $list_friends;
  949. }
  950. /**
  951. * Print the number of users that didn't login for a certain period of time.
  952. */
  953. public static function printUsersNotLoggedInStats()
  954. {
  955. $totalLogin = [];
  956. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  957. $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  958. $urlId = api_get_current_access_url_id();
  959. $total = self::countUsers();
  960. if (api_is_multiple_url_enabled()) {
  961. $table_url = ", $access_url_rel_user_table";
  962. $where_url = " AND login_user_id=user_id AND access_url_id='".$urlId."'";
  963. } else {
  964. $table_url = '';
  965. $where_url = '';
  966. }
  967. $now = api_get_utc_datetime();
  968. $sql[get_lang('ThisDay')] =
  969. "SELECT count(distinct(login_user_id)) AS number ".
  970. " FROM $table $table_url ".
  971. " WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= '$now' $where_url";
  972. $sql[get_lang('Last7days')] =
  973. "SELECT count(distinct(login_user_id)) AS number ".
  974. " FROM $table $table_url ".
  975. " WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= '$now' $where_url";
  976. $sql[get_lang('Last31days')] =
  977. "SELECT count(distinct(login_user_id)) AS number ".
  978. " FROM $table $table_url ".
  979. " WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= '$now' $where_url";
  980. $sql[sprintf(get_lang('LastXMonths'), 6)] =
  981. "SELECT count(distinct(login_user_id)) AS number ".
  982. " FROM $table $table_url ".
  983. " WHERE DATE_ADD(login_date, INTERVAL 6 MONTH) >= '$now' $where_url";
  984. $sql[get_lang('NeverConnected')] =
  985. "SELECT count(distinct(login_user_id)) AS number ".
  986. " FROM $table $table_url WHERE 1=1 $where_url";
  987. foreach ($sql as $index => $query) {
  988. $res = Database::query($query);
  989. $obj = Database::fetch_object($res);
  990. $r = $total - $obj->number;
  991. $totalLogin[$index] = $r < 0 ? 0 : $r;
  992. }
  993. self::printStats(
  994. get_lang('StatsUsersDidNotLoginInLastPeriods'),
  995. $totalLogin,
  996. false
  997. );
  998. }
  999. /**
  1000. * Returns an array with indexes as the 'yyyy-mm-dd' format of each date
  1001. * within the provided range (including limits). Dates are assumed to be
  1002. * given in UTC.
  1003. *
  1004. * @param string $startDate Start date, in Y-m-d or Y-m-d h:i:s format
  1005. * @param string $endDate End date, in Y-m-d or Y-m-d h:i:s format
  1006. * @param bool $removeYear Whether to remove the year in the results (for easier reading)
  1007. *
  1008. * @return array|bool False on error in the params, array of [date1 => 0, date2 => 0, ...] otherwise
  1009. */
  1010. public static function buildDatesArray($startDate, $endDate, $removeYear = false)
  1011. {
  1012. if (strlen($startDate) > 10) {
  1013. $startDate = substr($startDate, 0, 10);
  1014. }
  1015. if (strlen($endDate) > 10) {
  1016. $endDate = substr($endDate, 0, 10);
  1017. }
  1018. if (!preg_match('/\d\d\d\d-\d\d-\d\d/', $startDate)) {
  1019. return false;
  1020. }
  1021. if (!preg_match('/\d\d\d\d-\d\d-\d\d/', $startDate)) {
  1022. return false;
  1023. }
  1024. $startTimestamp = strtotime($startDate);
  1025. $endTimestamp = strtotime($endDate);
  1026. $list = [];
  1027. for ($time = $startTimestamp; $time < $endTimestamp; $time += 86400) {
  1028. $datetime = api_get_utc_datetime($time);
  1029. if ($removeYear) {
  1030. $datetime = substr($datetime, 5, 5);
  1031. } else {
  1032. $dateTime = substr($datetime, 0, 10);
  1033. }
  1034. $list[$datetime] = 0;
  1035. }
  1036. return $list;
  1037. }
  1038. /**
  1039. * Prepare the JS code to load a chart.
  1040. *
  1041. * @param string $url URL for AJAX data generator
  1042. * @param string $type bar, line, pie, etc
  1043. * @param string $options Additional options to the chart (see chart-specific library)
  1044. * @param string A JS code for loading the chart together with a call to AJAX data generator
  1045. */
  1046. public static function getJSChartTemplate($url, $type = 'pie', $options = '', $elementId = 'canvas')
  1047. {
  1048. $chartCode = '
  1049. <script>
  1050. $(function() {
  1051. $.ajax({
  1052. url: "'.$url.'",
  1053. type: "POST",
  1054. success: function(data) {
  1055. Chart.defaults.global.responsive = true;
  1056. var ctx = document.getElementById("'.$elementId.'").getContext("2d");
  1057. var myLoginChart = new Chart(ctx, {
  1058. type: "'.$type.'",
  1059. data: data,
  1060. options: {'.$options.'}
  1061. });
  1062. }
  1063. });
  1064. });
  1065. </script>';
  1066. return $chartCode;
  1067. }
  1068. /**
  1069. * Display the Logins By Date report and allow export its result to XLS.
  1070. */
  1071. public static function printLoginsByDate()
  1072. {
  1073. if (isset($_GET['export']) && 'xls' === $_GET['export']) {
  1074. $result = self::getLoginsByDate($_GET['start'], $_GET['end']);
  1075. $data = [[get_lang('Username'), get_lang('FirstName'), get_lang('LastName'), get_lang('TotalTime')]];
  1076. foreach ($result as $i => $item) {
  1077. $data[] = [
  1078. $item['username'],
  1079. $item['firstname'],
  1080. $item['lastname'],
  1081. api_time_to_hms($item['time_count']),
  1082. ];
  1083. }
  1084. Export::arrayToXls($data);
  1085. exit;
  1086. }
  1087. echo Display::page_header(get_lang('LoginsByDate'));
  1088. $actions = '';
  1089. $content = '';
  1090. $form = new FormValidator('frm_logins_by_date', 'get');
  1091. $form->addDateRangePicker(
  1092. 'daterange',
  1093. get_lang('DateRange'),
  1094. true,
  1095. ['format' => 'YYYY-MM-DD', 'timePicker' => 'false', 'validate_format' => 'Y-m-d']
  1096. );
  1097. $form->addHidden('report', 'logins_by_date');
  1098. $form->addButtonFilter(get_lang('Search'));
  1099. if ($form->validate()) {
  1100. $values = $form->exportValues();
  1101. $result = self::getLoginsByDate($values['daterange_start'], $values['daterange_end']);
  1102. if (!empty($result)) {
  1103. $actions = Display::url(
  1104. Display::return_icon('excel.png', get_lang('ExportToXls'), [], ICON_SIZE_MEDIUM),
  1105. api_get_self().'?'.http_build_query(
  1106. [
  1107. 'report' => 'logins_by_date',
  1108. 'export' => 'xls',
  1109. 'start' => Security::remove_XSS($values['daterange_start']),
  1110. 'end' => Security::remove_XSS($values['daterange_end']),
  1111. ]
  1112. )
  1113. );
  1114. }
  1115. $table = new HTML_Table(['class' => 'data_table']);
  1116. $table->setHeaderContents(0, 0, get_lang('Username'));
  1117. $table->setHeaderContents(0, 1, get_lang('FirstName'));
  1118. $table->setHeaderContents(0, 2, get_lang('LastName'));
  1119. $table->setHeaderContents(0, 3, get_lang('TotalTime'));
  1120. foreach ($result as $i => $item) {
  1121. $table->setCellContents($i + 1, 0, $item['username']);
  1122. $table->setCellContents($i + 1, 1, $item['firstname']);
  1123. $table->setCellContents($i + 1, 2, $item['lastname']);
  1124. $table->setCellContents($i + 1, 3, api_time_to_hms($item['time_count']));
  1125. }
  1126. $table->setColAttributes(0, ['class' => 'text-center']);
  1127. $table->setColAttributes(3, ['class' => 'text-center']);
  1128. $content = $table->toHtml();
  1129. }
  1130. $form->display();
  1131. if (!empty($actions)) {
  1132. echo Display::toolbarAction('logins_by_date_toolbar', [$actions]);
  1133. }
  1134. echo $content;
  1135. }
  1136. /**
  1137. * @param string $startDate
  1138. * @param string $endDate
  1139. *
  1140. * @return array
  1141. */
  1142. private static function getLoginsByDate($startDate, $endDate)
  1143. {
  1144. /** @var DateTime $startDate */
  1145. $startDate = api_get_utc_datetime("$startDate 00:00:00");
  1146. /** @var DateTime $endDate */
  1147. $endDate = api_get_utc_datetime("$endDate 23:59:59");
  1148. if (empty($startDate) || empty($endDate)) {
  1149. return [];
  1150. }
  1151. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  1152. $tblLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1153. $urlJoin = '';
  1154. $urlWhere = '';
  1155. if (api_is_multiple_url_enabled()) {
  1156. $tblUrlUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1157. $urlJoin = "INNER JOIN $tblUrlUser au ON u.id = au.user_id";
  1158. $urlWhere = 'AND au.access_url_id = '.api_get_current_access_url_id();
  1159. }
  1160. $sql = "SELECT u.id,
  1161. u.firstname,
  1162. u.lastname,
  1163. u.username,
  1164. SUM(TIMESTAMPDIFF(SECOND, l.login_date, l.logout_date)) AS time_count
  1165. FROM $tblUser u
  1166. INNER JOIN $tblLogin l ON u.id = l.login_user_id
  1167. $urlJoin
  1168. WHERE l.login_date BETWEEN '$startDate' AND '$endDate'
  1169. $urlWhere
  1170. GROUP BY u.id";
  1171. $stmt = Database::query($sql);
  1172. $result = Database::store_result($stmt, 'ASSOC');
  1173. return $result;
  1174. }
  1175. }