statistics.lib.php 37 KB

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