statistics.lib.php 41 KB

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