Просмотр исходного кода

Admin: Add charts for several statistics pages - loosely refs #2717

Yannick Warnier 6 лет назад
Родитель
Сommit
237f9bb6dc
3 измененных файлов с 208 добавлено и 53 удалено
  1. 116 48
      main/admin/statistics/index.php
  2. 62 4
      main/inc/ajax/statistics.ajax.php
  3. 30 1
      main/inc/lib/statistics.lib.php

+ 116 - 48
main/admin/statistics/index.php

@@ -16,54 +16,114 @@ $interbreadcrumb[] = ['url' => '../index.php', 'name' => get_lang('PlatformAdmin
 $report = isset($_REQUEST['report']) ? $_REQUEST['report'] : '';
 $sessionDuration = isset($_GET['session_duration']) ? (int) $_GET['session_duration'] : '';
 
-if ($report == 'recentlogins') {
+if (
+    in_array(
+        $report,
+        ['recentlogins', 'tools', 'courses', 'coursebylanguage', 'users']
+    )
+   ) {
     $htmlHeadXtra[] = api_get_js('chartjs/Chart.min.js');
-    $htmlHeadXtra[] = '
-    <script>
-    $(document).ready(function() {
-        $.ajax({
-            url: "'.api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=recent_logins&session_duration='.$sessionDuration.'",
-            type: "POST",
-            success: function(data) {
-                Chart.defaults.global.responsive = true;
-                var ctx = document.getElementById("canvas").getContext("2d");
-                var myLoginChart = new Chart(ctx, {
-                    type: "line",
-                    data: data
-                });
-            }
-        });
-    });
-    </script>';
-}
-if ($report == 'tools') {
-    $htmlHeadXtra[] = api_get_js('chartjs/Chart.min.js');
-    $htmlHeadXtra[] = '
-    <script>
-    $(document).ready(function() {
-        $.ajax({
-            url: "'.api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=tools_usage",
-            type: "POST",
-            success: function(data) {
-                Chart.defaults.global.responsive = true;
-                var ctx = document.getElementById("canvas").getContext("2d");
-                var myLoginChart = new Chart(ctx, {
-                    type: "pie",
-                    data: data,
-                    options: {
-                      legend: {
-                        position: "left"
-                      },
-                      title: {
-                        text: "'.get_lang('PlatformToolAccess').'",
-                        display: true
-                      }
-                    }
-                });
-            }
-        });
-    });
-    </script>';
+    // Prepare variables for the JS charts
+    $url = $reportName = $reportType = $reportOptions = '';
+    switch ($report) {
+        case 'recentlogins':
+            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=recent_logins&session_duration='.$sessionDuration;
+            $reportName = '';
+            $reportType = 'line';
+            $reportOptions = '';
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
+            break;
+        case 'tools':
+            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=tools_usage';
+            $reportName = 'PlatformToolAccess';
+            $reportType = 'pie';
+            $reportOptions = '
+                legend: {
+                    position: "left"
+                },
+                title: {
+                    text: "'.get_lang($reportName).'",
+                    display: true
+                },
+                cutoutPercentage: 25
+                ';
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
+            break;
+        case 'courses':
+            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=courses';
+            $reportName = 'CountCours';
+            $reportType = 'pie';
+            $reportOptions = '
+                legend: {
+                    position: "left"
+                },
+                title: {
+                    text: "'.get_lang($reportName).'",
+                    display: true
+                },
+                cutoutPercentage: 25
+                ';
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
+            break;
+         case 'coursebylanguage':
+            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=courses_by_language';
+            $reportName = 'CountCourseByLanguage';
+            $reportType = 'pie';
+            $reportOptions = '
+                legend: {
+                    position: "left"
+                },
+                title: {
+                    text: "'.get_lang($reportName).'",
+                    display: true
+                },
+                cutoutPercentage: 25
+                ';
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
+            break;
+         case 'users':
+            $invisible = isset($_GET['count_invisible_courses']) ? intval($_GET['count_invisible_courses']) : null;
+            $urlBase = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?';
+            $url1 = $urlBase.'a=users&count_invisible='.$invisible;
+            $url2 = $urlBase.'a=users_teachers&count_invisible='.$invisible;
+            $url3 = $urlBase.'a=users_students&count_invisible='.$invisible;
+            $reportName1 = get_lang('NumberOfUsers');
+            $reportName2 = get_lang('Teachers');
+            $reportName3 = get_lang('Students');
+            $reportType = 'pie';
+            $reportOptions = '
+                legend: {
+                    position: "left"
+                },
+                title: {
+                    text: "%s",
+                    display: true
+                },
+                cutoutPercentage: 25
+                ';
+            $reportOptions1 = sprintf($reportOptions, $reportName1);
+            $reportOptions2 = sprintf($reportOptions, $reportName2);
+            $reportOptions3 = sprintf($reportOptions, $reportName3);
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
+                $url1,
+                $reportType,
+                $reportOptions1,
+                'canvas1'
+            );
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
+                $url2,
+                $reportType,
+                $reportOptions2,
+                'canvas2'
+            );
+            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
+                $url3,
+                $reportType,
+                $reportOptions3,
+                'canvas3'
+            );
+            break;
+    }
 }
 
 if ($report == 'user_session') {
@@ -223,6 +283,7 @@ switch ($report) {
 
         break;
     case 'courses':
+        echo '<canvas class="col-md-12" id="canvas" height="300px" style="margin-bottom: 20px"></canvas>';
         // total amount of courses
         foreach ($course_categories as $code => $name) {
             $courses[$name] = Statistics::countCourses($code);
@@ -235,12 +296,19 @@ switch ($report) {
         Statistics::printToolStats();
         break;
     case 'coursebylanguage':
-        Statistics::printCourseByLanguageStats();
+        echo '<canvas class="col-md-12" id="canvas" height="300px" style="margin-bottom: 20px"></canvas>';
+        $result = Statistics::printCourseByLanguageStats();
+        Statistics::printStats(get_lang('CountCourseByLanguage'), $result, true);
         break;
     case 'courselastvisit':
         Statistics::printCourseLastVisit();
         break;
     case 'users':
+        echo '<div class="row">';
+        echo '<div class="col-md-4"><canvas id="canvas1" style="margin-bottom: 20px"></canvas></div>';
+        echo '<div class="col-md-4"><canvas id="canvas2" style="margin-bottom: 20px"></canvas></div>';
+        echo '<div class="col-md-4"><canvas id="canvas3" style="margin-bottom: 20px"></canvas></div>';
+        echo '</div>';
         // total amount of users
         $teachers = $students = [];
         $countInvisible = isset($_GET['count_invisible_courses']) ? intval($_GET['count_invisible_courses']) : null;

+ 62 - 4
main/inc/ajax/statistics.ajax.php

@@ -145,18 +145,76 @@ switch ($action) {
         echo json_encode($list);
         break;
     case 'tools_usage':
+    case 'courses':
+    case 'courses_by_language':
+    case 'users':
+    case 'users_teachers':
+    case 'users_students':
         // Give a JSON array to the stats page main/admin/statistics/index.php
         // for global tools usage (number of clicks)
         header('Content-type: application/json');
         $list = [];
-        $all = Statistics::getToolsStats();
+        $palette = ChamiloApi::getColorPalette(true, true);
+        if ($action == 'tools_usage') {
+            $statsName = 'Tools';
+            $all = Statistics::getToolsStats();
+        } elseif ($action == 'courses') {
+            $statsName = 'CountCours';
+            $course_categories = Statistics::getCourseCategories();
+            // total amount of courses
+            $all = [];
+            foreach ($course_categories as $code => $name) {
+                $all[$name] = Statistics::countCourses($code);
+            }
+        } elseif ($action == 'courses_by_language') {
+            $statsName = 'CountCourseByLanguage';
+            $all = Statistics::printCourseByLanguageStats();
+            // use slightly different colors than previous chart
+            for ($k = 0; $k < 3; $k++) {
+                $item = array_shift($palette);
+                array_push($palette, $item);
+            }
+        } elseif ($action == 'users') {
+            $statsName = 'NumberOfUsers';
+            $countInvisible = isset($_GET['count_invisible']) ? (int) $_GET['count_invisible'] : null;
+            $all = [
+                get_lang('Teachers') => Statistics::countUsers(COURSEMANAGER, null, $countInvisible),
+                get_lang('Students') => Statistics::countUsers(STUDENT, null, $countInvisible),
+            ];
+        } elseif ($action == 'users_teachers') {
+            $statsName = 'Teachers';
+            $course_categories = Statistics::getCourseCategories();
+            $countInvisible = isset($_GET['count_invisible']) ? (int) $_GET['count_invisible'] : null;
+            $all = [];
+            foreach ($course_categories as $code => $name) {
+                $name = str_replace(get_lang('Department'), "", $name);
+                $all[$name] = Statistics::countUsers(COURSEMANAGER, $code, $countInvisible);
+            }
+            // use slightly different colors than previous chart
+            for ($k = 0; $k < 3; $k++) {
+                $item = array_shift($palette);
+                array_push($palette, $item);
+            }
+        } elseif ($action == 'users_students') {
+            $statsName = 'Students';
+            $course_categories = Statistics::getCourseCategories();
+            $countInvisible = isset($_GET['count_invisible']) ? (int) $_GET['count_invisible'] : null;
+            $all = [];
+            foreach ($course_categories as $code => $name) {
+                $name = str_replace(get_lang('Department'), "", $name);
+                $all[$name] = Statistics::countUsers(STUDENT, $code, $countInvisible);
+            }
+            // use slightly different colors than previous chart
+            for ($k = 0; $k < 6; $k++) {
+                $item = array_shift($palette);
+                array_push($palette, $item);
+            }
+        }
         foreach ($all as $tick => $tock) {
             $list['labels'][] = $tick;
         }
 
-        $palette = ChamiloApi::getColorPalette(true, true);
-
-        $list['datasets'][0]['label'] = get_lang('Tools');
+        $list['datasets'][0]['label'] = get_lang($statsName);
         $list['datasets'][0]['borderColor'] = 'rgba(255,255,255,1)';
 
         $i = 0;

+ 30 - 1
main/inc/lib/statistics.lib.php

@@ -766,7 +766,7 @@ class Statistics
         while ($obj = Database::fetch_object($res)) {
             $result[$obj->course_language] = $obj->number_of_courses;
         }
-        self::printStats(get_lang('CountCourseByLanguage'), $result, true);
+        return $result;
     }
 
     /**
@@ -1112,4 +1112,33 @@ class Statistics
         }
         return $list;
     }
+    /**
+     * Prepare the JS code to load a chart
+     * @param string $url URL for AJAX data generator
+     * @param string $type bar, line, pie, etc
+     * @param string $options Additional options to the chart (see chart-specific library)
+     * @param string A JS code for loading the chart together with a call to AJAX data generator
+     */
+    public static function getJSChartTemplate($url, $type = 'pie', $options = '', $elementId = 'canvas')
+    { 
+        $chartCode = '
+        <script>
+        $(document).ready(function() {
+            $.ajax({
+                url: "'.$url.'",
+                type: "POST",
+                success: function(data) {
+                    Chart.defaults.global.responsive = true;
+                    var ctx = document.getElementById("'.$elementId.'").getContext("2d");
+                    var myLoginChart = new Chart(ctx, {
+                        type: "'.$type.'",
+                        data: data,
+                        options: {'.$options.'}
+                    });
+                }
+            });
+        });
+        </script>';
+        return $chartCode;
+    }
 }