Browse Source

Add pagination to course session catalogue - refs #7273

Daniel Barreto 10 years ago
parent
commit
61f286a01d

+ 8 - 44
main/auth/courses.php

@@ -80,6 +80,9 @@ $actions = array('sortmycourses', 'createcoursecategory', 'subscribe', 'deleteco
 $action = CoursesAndSessionsCatalog::is(CATALOG_SESSIONS) ? 'display_sessions' : 'display_random_courses';
 $nameTools = get_lang('SortMyCourses');
 
+// Get Limit values
+$limit = getLimitArray();
+
 if (isset($_GET['action']) && in_array($_GET['action'],$actions)) {
 	$action = $_GET['action'];
 }
@@ -169,7 +172,7 @@ if (isset($_POST['create_course_category']) && isset($_POST['title_course_catego
 if (isset($_REQUEST['search_course'])) {
     //echo "<p><strong>".get_lang('SearchResultsFor')." ".api_htmlentities($_POST['search_term'], ENT_QUOTES, api_get_system_encoding())."</strong><br />";
     if ($ctok == $_REQUEST['sec_token']) {
-        $courses_controller->search_courses($_REQUEST['search_term']);
+        $courses_controller->search_courses($_REQUEST['search_term'], null, null, null, $limit);
     }
 }
 
@@ -209,6 +212,8 @@ switch ($action) {
         $courses_controller->courses_list($action);
         break;
     case 'subscribe':
+        $courses_controller->courses_categories($action, $_GET['category_code'], null, null, null, $limit);
+        break;
     case 'display_random_courses':
         if ($user_can_view_page) {
             $courses_controller->courses_categories($action);
@@ -217,50 +222,9 @@ switch ($action) {
         }
         break;
     case 'display_courses':
-        $courses_controller->courses_categories($action, $_GET['category_code']);
+        $courses_controller->courses_categories($action, $_GET['category_code'], null, null, null, $limit);
         break;
     case 'display_sessions':
-        $date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
-        $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
-
-        $authModel = new Auth();
-        $sessions = $authModel->browseSessions($date);
-
-        $sessionsBlocks = array();
-
-        foreach ($sessions as $session) {
-            $sessionsBlocks[] = array(
-                'id' => $session['id'],
-                'name' => $session['name'],
-                'nbr_courses' => $session['nbr_courses'],
-                'nbr_users' => $session['nbr_users'],
-                'coach_name' => $session['coach_name'],
-                'is_subscribed' => $session['is_subscribed'],
-                'icon' => $courses_controller->getSessionIcon($session['name']),
-                'date' => SessionManager::getSessionFormattedDate($session),
-                'subscribe_button' => $courses_controller->getRegisterInSessionButton($session['name'])
-            );
-        }
-
-        $tpl = new Template();
-        $tpl->assign('action', $action);
-        $tpl->assign('showCourses', CoursesAndSessionsCatalog::showCourses());
-        $tpl->assign('showSessions', CoursesAndSessionsCatalog::showSessions());
-        $tpl->assign('api_get_self', api_get_self());
-        $tpl->assign('nameTools', $nameTools);
-
-        $tpl->assign('coursesCategoriesList', $courses_controller->getCoursesCategoriesBlock());
-
-        $tpl->assign('hiddenLinks', $hiddenLinks);
-        $tpl->assign('searchToken', Security::get_token());
-
-        $tpl->assign('searchDate', $date);
-        $tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH) . 'course.ajax.php');
-        $tpl->assign('sessions_blocks', $sessionsBlocks);
-        $tpl->assign('already_subscribed_label', $courses_controller->getAlreadyRegisterInSessionLabel());
-
-        $conentTemplate = $tpl->get_template('auth/sessions_catalog.tpl');
-
-        $tpl->display($conentTemplate);
+        $courses_controller->sessionsList($action, $nameTools, $limit);
         break;
 }

+ 132 - 14
main/auth/courses_controller.php

@@ -75,23 +75,32 @@ class CoursesController
     /**
      * It's used for listing courses with categories,
      * render to courses_categories view
-     * @param string   	action
-     * @param string    Category code (optional)
+     * @param $action
+     * @param null $category_code
+     * @param string $message
+     * @param string $error
+     * @param null $content
+     * @param array $limit will be used if $random_value is not set.
+     * This array should contains 'start' and 'length' keys
+     * @internal param \action $string
+     * @internal param \Category $string code (optional)
      */
-    public function courses_categories($action, $category_code = null, $message = '', $error = '', $content = null)
+    public function courses_categories($action, $category_code = null, $message = '', $error = '', $content = null, $limit = array())
     {
         $data = array();
         $browse_course_categories = $this->model->browse_course_categories();
         
         global $_configuration;
 
+        $data['countCoursesInCategory'] = $this->model->count_courses_in_category($category_code);
         if ($action == 'display_random_courses') {
+            // Random value is used instead limit filter
             $data['browse_courses_in_category'] = $this->model->browse_courses_in_category(null, 10);
         } else {
             if (!isset($category_code)) {
                 $category_code = $browse_course_categories[0][1]['code']; // by default first category
             }
-            $data['browse_courses_in_category'] = $this->model->browse_courses_in_category($category_code);
+            $data['browse_courses_in_category'] = $this->model->browse_courses_in_category($category_code, null, $limit);
         }
 
         $data['browse_course_categories'] = $browse_course_categories;
@@ -140,14 +149,15 @@ class CoursesController
      * @param string $message
      * @param string $error
      * @param string $content
+     * @param $limit
      */
-    public function search_courses($search_term, $message = '', $error = '', $content = null)
+    public function search_courses($search_term, $message = '', $error = '', $content = null, $limit = array())
     {
         $data = array();
 
         $browse_course_categories = $this->model->browse_course_categories();
-
-        $data['browse_courses_in_category'] = $this->model->search_courses($search_term);
+        $data['countCoursesInCategory'] = $this->model->count_courses_in_category('ALL', $search_term);
+        $data['browse_courses_in_category'] = $this->model->search_courses($search_term, $limit);
         $data['browse_course_categories']   = $browse_course_categories;
 
         $data['search_term'] = Security::remove_XSS($search_term); //filter before showing in template
@@ -328,21 +338,22 @@ class CoursesController
             $this->courses_categories('subcribe', $category_code, $message, $error);
         }
     }
-    
+
     /**
      * Get the html block for courses categories
      * @param string $code Current category code
      * @param boolean $hiddenLinks Whether hidden links
+     * @param array $limit
      * @return string The HTML block
      */
-    public function getCoursesCategoriesBlock($code = null, $hiddenLinks = false)
+    public function getCoursesCategoriesBlock($code = null, $hiddenLinks = false, $limit = null)
     {
         $categories = $this->model->browse_course_categories();
 
         $html = '';
 
         if (!empty($categories)) {
-
+            $action = 'display_courses';
             foreach ($categories[0] as $category) {
                 $categoryName = $category['name'];
                 $categoryCode = $category['code'];
@@ -356,7 +367,13 @@ class CoursesController
                     $html .= '</strong>';
                 } else {
                     if (!empty($categoryCourses)) {
-                        $html .= '<a href="' . api_get_self() . '?action=display_courses&category_code=' . $categoryCode . '&hidden_links=' . $hiddenLinks . '">';
+                        $html .= '<a href="' . getCourseCategoryUrl(
+                                1,
+                                $limit['length'],
+                                $categoryCode,
+                                $hiddenLinks,
+                                $action
+                            ) . '">';
                         $html .= "$categoryName ($categoryCourses)";
                         $html .= '</a>';
                     } else {
@@ -377,7 +394,13 @@ class CoursesController
                         if ($code == $subCategory1Code) {
                             $html .= "<strong>$subCategory1Name ($subCategory1Courses)</strong>";
                         } else {
-                            $html .= '<a href="' . api_get_self() . '?action=display_courses&category_code=' . $subCategory1Code . '&hidden_links=' . $hiddenLinks . '">';
+                            $html .= '<a href="' . getCourseCategoryUrl(
+                                    1,
+                                    $limit['length'],
+                                    $categoryCode,
+                                    $hiddenLinks,
+                                    $action
+                                ) . '">';
                             $html .= "$subCategory1Name ($subCategory1Courses)";
                             $html .= '</a>';
                         }
@@ -395,7 +418,13 @@ class CoursesController
                                 if ($code == $subCategory2Code) {
                                     $html .= "<strong>$subCategory2Name ($subCategory2Courses)</strong>";
                                 } else {
-                                    $html .= '<a href="' . api_get_self() . '?action=display_courses&category_code=' . $subCategory2Code . '&hidden_links=' . $hiddenLinks . '">';
+                                    $html .= '<a href="' . getCourseCategoryUrl(
+                                            1,
+                                            $limit['length'],
+                                            $categoryCode,
+                                            $hiddenLinks,
+                                            $action
+                                        ) . '">';
                                     $html .= "$subCategory2Name ($subCategory2Courses)";
                                     $html .= '</a>';
                                 }
@@ -413,7 +442,13 @@ class CoursesController
                                         if ($code == $subCategory3Code) {
                                             $html .= "<strong>$subCategory3Name ($subCategory3Courses)</strong>";
                                         } else {
-                                            $html .= '<a href="' . api_get_self() . '?action=display_courses&category_code=' . $subCategory3Code . '&hidden_links=' . $hiddenLinks . '">';
+                                            $html .= '<a href="' . getCourseCategoryUrl(
+                                                    1,
+                                                    $limit['length'],
+                                                    $categoryCode,
+                                                    $hiddenLinks,
+                                                    $action
+                                                ) . '">';
                                             $html .= "$subCategory3Name ($subCategory3Courses)";
                                             $html .= '</a>';
                                         }
@@ -480,4 +515,87 @@ class CoursesController
         return Display::return_icon('window_list.png', $sessionName, null, ICON_SIZE_LARGE);
     }
 
+    /**
+     * @param string $courseCategory
+     * @param string $searchTerm
+     * @return int
+     */
+    public function getCountCourses($courseCategory = '', $searchTerm = '')
+    {
+        return countCoursesInCategory($courseCategory, $searchTerm);
+    }
+
+    /**
+     * Return Session Catalogue rendered view
+     * @param string $action
+     * @param string $nameTools
+     * @param array $limit
+     */
+    public function sessionsList($action, $nameTools, $limit = array())
+    {
+        $date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
+        $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
+        if (
+            !empty($limit) &&
+            is_array($limit) &&
+            isset($limit['start']) &&
+            isset($limit['current']) &&
+            isset($limit['length'])
+        ) {
+            // Nothing to do
+        } else {
+            $limit = getLimitArray();
+        }
+
+        $countSessions = $this->model->countSessions($date);
+        $sessions = $this->model->browseSessions($date, $limit);
+
+        $pageTotal = intval(ceil(intval($countSessions) / $limit['length']));
+        $cataloguePagination = $pageTotal > 1 ?
+            getCataloguePagination($limit['current'], $limit['length'], $pageTotal) :
+            '' . print_r($limit, 1) . ' ' . $pageTotal;
+        $sessionsBlocks = array();
+
+        $sessionUrl = getCourseCategoryUrl(1, $limit['length'], null, 0, 'display_sessions');
+        $courseUrl = getCourseCategoryUrl(1, $limit['length'], null, 0, 'subscribe');
+
+        foreach ($sessions as $session) {
+            $sessionsBlocks[] = array(
+                'id' => $session['id'],
+                'name' => $session['name'],
+                'nbr_courses' => $session['nbr_courses'],
+                'nbr_users' => $session['nbr_users'],
+                'coach_name' => $session['coach_name'],
+                'is_subscribed' => $session['is_subscribed'],
+                'icon' => $this->getSessionIcon($session['name']),
+                'date' => SessionManager::getSessionFormattedDate($session),
+                'subscribe_button' => $this->getRegisterInSessionButton($session['name'])
+            );
+        }
+
+        $tpl = new Template();
+        $tpl->assign('action', $action);
+        $tpl->assign('showCourses', CoursesAndSessionsCatalog::showCourses());
+        $tpl->assign('showSessions', CoursesAndSessionsCatalog::showSessions());
+        $tpl->assign('api_get_self', api_get_self());
+        $tpl->assign('sessionUrl', $sessionUrl);
+        $tpl->assign('courseUrl', $courseUrl);
+        $tpl->assign('nameTools', $nameTools);
+
+        $tpl->assign('coursesCategoriesList', $this->getCoursesCategoriesBlock(null, false, $limit));
+        $tpl->assign('cataloguePagination', $cataloguePagination);
+
+        $tpl->assign('hiddenLinks', $hiddenLinks);
+        $tpl->assign('searchToken', Security::get_token());
+
+        $tpl->assign('searchDate', $date);
+        $tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH) . 'course.ajax.php');
+        $tpl->assign('sessions_blocks', $sessionsBlocks);
+        $tpl->assign('already_subscribed_label', $this->getAlreadyRegisterInSessionLabel());
+
+        $contentTemplate = $tpl->get_template('auth/sessions_catalog.tpl');
+
+        $tpl->display($contentTemplate);
+    }
+
 }

+ 66 - 18
main/inc/lib/auth.lib.php

@@ -391,12 +391,13 @@ class Auth
 
     /**
      * Counts the number of courses in a given course category
-     * @param   string  $categoryCode Category code
+     * @param   string $categoryCode Category code
+     * @param $searchTerm
      * @return  int     Count of courses
      */
-    public function count_courses_in_category($categoryCode)
+    public function count_courses_in_category($categoryCode, $searchTerm = '')
     {
-        return countCoursesInCategory($categoryCode);
+        return countCoursesInCategory($categoryCode, $searchTerm);
     }
 
     /**
@@ -410,26 +411,32 @@ class Auth
 
     /**
      * Display all the courses in the given course category. I could have used a parameter here
-     * @param   string  $categoryCode Category code
-     * @return  array   Courses data
+     * @param string $categoryCode Category code
+     * @param null $randomValue
+     * @param array $limit will be used if $random_value is not set.
+     * This array should contains 'start' and 'length' keys
+     * @return array Courses data
      */
-    public function browse_courses_in_category($categoryCode, $randomValue = null)
+    public function browse_courses_in_category($categoryCode, $randomValue = null, $limit = array())
     {
-        return browseCoursesInCategory($categoryCode, $randomValue);
+        return browseCoursesInCategory($categoryCode, $randomValue, $limit);
     }
 
     /**
      * Search the courses database for a course that matches the search term.
      * The search is done on the code, title and tutor field of the course table.
-     * @param string $search_term: the string that the user submitted, what we are looking for
+     * @param string $search_term : the string that the user submitted, what we are looking for
+     * @param array $limit
      * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... ) matching the the search term.
      */
-    public function search_courses($search_term)
+    public function search_courses($search_term, $limit)
     {
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
 
+        $limitFilter = getLimitFilterFromArray($limit);
+
         // get course list auto-register
         $sql = "SELECT course_code FROM $TABLE_COURSE_FIELD_VALUE tcfv INNER JOIN $TABLE_COURSE_FIELD tcf ON tcfv.field_id =  tcf.id
                 WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
@@ -447,16 +454,25 @@ class Auth
         }
 
         $search_term_safe = Database::escape_string($search_term);
-        $sql_find = "SELECT * FROM $TABLECOURS WHERE (code LIKE '%" . $search_term_safe . "%' OR title LIKE '%" . $search_term_safe . "%' OR tutor_name LIKE '%" . $search_term_safe . "%') $without_special_courses ORDER BY title, visual_code ASC";
+        $sql_find = "SELECT * FROM $TABLECOURS WHERE (code LIKE '%" .
+            $search_term_safe . "%' OR title LIKE '%" . $search_term_safe .
+            "%' OR tutor_name LIKE '%" . $search_term_safe . "%')" .
+            $without_special_courses . "ORDER BY title, visual_code ASC " .
+            $limitFilter;
 
         global $_configuration;
         if ($_configuration['multiple_access_urls']) {
             $url_access_id = api_get_current_access_url_id();
             if ($url_access_id != -1) {
                 $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-                $sql_find = "SELECT * FROM $TABLECOURS as course INNER JOIN $tbl_url_rel_course as url_rel_course
-                                        ON (url_rel_course.course_code=course.code)
-                                        WHERE access_url_id = $url_access_id AND  (code LIKE '%" . $search_term_safe . "%' OR title LIKE '%" . $search_term_safe . "%' OR tutor_name LIKE '%" . $search_term_safe . "%' ) $without_special_courses ORDER BY title, visual_code ASC ";
+                $sql_find = "SELECT * FROM $TABLECOURS as course INNER JOIN" .
+                    $tbl_url_rel_course . "as url_rel_course ON
+                    (url_rel_course.course_code=course.code) WHERE access_url_id = " .
+                    $url_access_id . "AND (code LIKE '%" . $search_term_safe . "%'
+                    OR title LIKE '%" . $search_term_safe . "%'
+                    OR tutor_name LIKE '%" . $search_term_safe . "%' )
+                    $without_special_courses ORDER BY title, visual_code ASC " .
+                    $limitFilter;
             }
         }
         $result_find = Database::query($sql_find);
@@ -535,13 +551,14 @@ class Auth
             return array('message' => $message, 'content' => $content);
         }
     }
-    
+
     /**
-     * List the sessions 
+     * List the sessions
      * @param date $date (optional) The date of sessions
+     * @param array $limit
      * @return array The session list
      */
-    public function browseSessions($date = null)
+    public function browseSessions($date = null, $limit = array())
     {
         require_once api_get_path(LIBRARY_PATH) . 'sessionmanager.lib.php';
 
@@ -551,19 +568,25 @@ class Auth
         $sessionsToBrowse = array();
         $userId = api_get_user_id();
 
+        $limitFilter = getLimitFilterFromArray($limit);
+
         $sql = "SELECT s.id, s.name, s.nbr_courses, s.nbr_users, s.date_start, s.date_end, u.lastname, u.firstname, u.username "
                 . "FROM $sessionTable AS s "
                 . "INNER JOIN $userTable AS u "
-                . "ON s.id_coach = u.user_id ";
+                . "ON s.id_coach = u.user_id "
+                . "WHERE 1 = 1 ";
 
         if (!is_null($date)) {
             $date = Database::escape_string($date);
             
-            $sql .= "WHERE ('$date' BETWEEN s.date_start AND s.date_end) "
+            $sql .= "AND ('$date' BETWEEN s.date_start AND s.date_end) "
                     . "OR (s.date_end = '0000-00-00') "
                     . "OR (s.date_start = '0000-00-00' AND s.date_end != '0000-00-00' AND s.date_end > '$date')";
         }
 
+        // Add limit filter to do pagination
+        $sql .= $limitFilter;
+
         $sessionResult = Database::query($sql);
 
         if ($sessionResult != false) {
@@ -580,4 +603,29 @@ class Auth
 
         return $sessionsToBrowse;
     }
+
+    /**
+     * Return a COUNT from Session table
+     * @param date $date in Y-m-d format
+     * @return int
+     */
+    function countSessions($date = null)
+    {
+        $count = 0;
+        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
+        $date = Database::escape_string($date);
+        $dateFilter = '';
+        if (!empty($date)) {
+            $dateFilter = ' AND ("' . $date . '" BETWEEN s.date_start AND s.date_end) ' .
+                'OR (s.date_end = "0000-00-00") ' .
+                'OR (s.date_start = "0000-00-00" AND ' .
+                's.date_end != "0000-00-00" AND s.date_end > "' . $date . '") ';
+        }
+        $sql = "SELECT COUNT(*) FROM $sessionTable s WHERE 1 = 1 $dateFilter";
+        $res = Database::query($sql);
+        if ($res !== false && Database::num_rows($res) > 0) {
+            $count = current(Database::fetch_row($res));
+        }
+        return $count;
+    }
 }

+ 269 - 11
main/inc/lib/course_category.lib.php

@@ -482,14 +482,19 @@ function browseCourseCategories()
 
 /**
  * @param string $category_code
+ * @param string $searchTerm
  * @return int
  */
-function countCoursesInCategory($category_code="")
+function countCoursesInCategory($category_code="", $searchTerm = '')
 {   
     global $_configuration;
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
     $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+    $categoryCode = Database::escape_string($category_code);
+    $searchTerm = Database::escape_string($searchTerm);
+    $categoryFilter = '';
+    $searchFilter = '';
 
     // get course list auto-register
     $sql = "SELECT course_code
@@ -509,7 +514,7 @@ function countCoursesInCategory($category_code="")
     if (!empty($special_course_list)) {
         $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
     }
-    
+
     if (isset($_configuration['course_catalog_hide_private'])) {
         if ($_configuration['course_catalog_hide_private'] == true) {
             $courseInfo = api_get_course_info();
@@ -517,8 +522,25 @@ function countCoursesInCategory($category_code="")
             $visibilityCondition = ' AND course.visibility <> 1';
         }
     }
+
+    if ($categoryCode == 'ALL') {
+        // Nothing to do
+    } elseif ($categoryCode == 'NONE') {
+        $categoryFilter =  ' AND category_code = "" ';
+    } else {
+        $categoryFilter =  ' AND category_code = "' . $categoryCode . '" ';
+    }
+
+    if (!empty($searchTerm)) {
+        $searchFilter = ' AND (code LIKE "%' . $searchTerm . '%"
+            OR title LIKE "%' . $searchTerm . '%"
+            OR tutor_name LIKE "%' . $searchTerm . '%") ';
+    }
+
     $sql = "SELECT * FROM $tbl_course
-            WHERE visibility != '0' AND visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses. $visibilityCondition;
+        WHERE visibility != '0' AND visibility != '4'".
+        $categoryFilter . $searchFilter .
+        $without_special_courses . $visibilityCondition;
     // Showing only the courses of the current portal access_url_id.
 
     if (api_is_multiple_url_enabled()) {
@@ -526,9 +548,11 @@ function countCoursesInCategory($category_code="")
         if ($url_access_id != -1) {
             $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
             $sql = "SELECT * FROM $tbl_course as course
-                    INNER JOIN $tbl_url_rel_course as url_rel_course
-                    ON (url_rel_course.course_code=course.code)
-                    WHERE access_url_id = $url_access_id AND course.visibility != '0' AND course.visibility != '4' AND category_code" . "='" . $category_code . "'" . $without_special_courses. $visibilityCondition;
+                INNER JOIN $tbl_url_rel_course as url_rel_course
+                ON (url_rel_course.course_code=course.code)
+                WHERE access_url_id = $url_access_id AND course.visibility != '0'
+                AND course.visibility != '4' AND category_code" . "='" . $category_code . "'" .
+                $searchTerm . $without_special_courses. $visibilityCondition;
         }
     }
     return Database::num_rows(Database::query($sql));
@@ -537,9 +561,11 @@ function countCoursesInCategory($category_code="")
 /**
  * @param string $category_code
  * @param string $random_value
+ * @param array $limit will be used if $random_value is not set.
+ * This array should contains 'start' and 'length' keys
  * @return array
  */
-function browseCoursesInCategory($category_code, $random_value = null)
+function browseCoursesInCategory($category_code, $random_value = null, $limit = array())
 {   
     global $_configuration;
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
@@ -613,14 +639,15 @@ function browseCoursesInCategory($category_code, $random_value = null)
         }
         $sql = "SELECT * FROM $tbl_course WHERE id IN($id_in)";
     } else {
+        $limitFilter = getLimitFilterFromArray($limit);
         $category_code = Database::escape_string($category_code);
         if (empty($category_code) || $category_code == "ALL") {
-            $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses $visibilityCondition ORDER BY title ";
+            $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses $visibilityCondition ORDER BY title $limitFilter";
         } else {
             if ($category_code == 'NONE') {
                 $category_code = '';
             }
-            $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses $visibilityCondition ORDER BY title ";
+            $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses $visibilityCondition ORDER BY title $limitFilter";
         }
 
         //showing only the courses of the current Chamilo access_url_id
@@ -631,12 +658,12 @@ function browseCoursesInCategory($category_code, $random_value = null)
                 $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
                     ON (url_rel_course.course_code=course.code)
                     WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses $visibilityCondition
-                    ORDER BY title";    
+                    ORDER BY title $limitFilter";
             } else{
                 $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
                     ON (url_rel_course.course_code=course.code)
                     WHERE access_url_id = $url_access_id $without_special_courses $visibilityCondition
-                    ORDER BY title";
+                    ORDER BY title $limitFilter";
             }
             
         }
@@ -787,6 +814,237 @@ function searchCategoryById($list)
     return Database::store_result($result, 'ASSOC');
 }
 
+/**
+ * Return an array with pagination data: 'start', 'current', 'length'
+ * @return array
+ */
+function getLimitArray()
+{
+    $pageCurrent = isset($_REQUEST['pageCurrent']) ?
+        intval($_GET['pageCurrent']) :
+        1;
+    $pageLength = isset($_REQUEST['pageLength']) ?
+        intval($_GET['pageLength']) :
+        10;
+    return array(
+        'start' => ($pageCurrent - 1) * $pageLength,
+        'current' => $pageCurrent,
+        'length' => $pageLength,
+    );
+}
+
+/**
+ * Return LIMIT to filter SQL query
+ * @param array $limit
+ * @return string
+ */
+function getLimitFilterFromArray($limit)
+{
+    $limitFilter = '';
+    if (!empty($limit) && is_array($limit)) {
+        $limitStart = isset($limit['start']) ? $limit['start'] : 0;
+        $limitLength = isset($limit['length']) ? $limit['length'] : 10;
+        $limitFilter = 'LIMIT ' . $limitStart . ', ' . $limitLength;
+    }
+
+    return $limitFilter;
+}
+
+/**
+ * Get Pagination HTML div
+ * @param $pageCurrent
+ * @param $pageLength
+ * @param $pageTotal
+ * @return string
+ */
+function getCataloguePagination($pageCurrent, $pageLength, $pageTotal)
+{
+    $pageDiv = '';
+    if (1 === $pageCurrent) {
+        $pageAnchor = Display::tag(
+            'a',
+            '<'
+        );
+        $pageAnchorFirst = Display::tag(
+            'a',
+            '<<'
+        );
+        $pageItemAttributes = array(
+            'class' => 'disabled'
+        );
+    } else {
+        $pageAnchor = Display::tag(
+            'a',
+            '<',
+            array(
+                'href' => getCourseCategoryUrl(
+                    $pageCurrent - 1,
+                    $pageLength
+                ),
+            )
+        );
+        $pageAnchorFirst = Display::tag(
+            'a',
+            '<<',
+            array(
+                'href' => getCourseCategoryUrl(
+                    1,
+                    $pageLength
+                ),
+            )
+        );
+        $pageItemAttributes = array();
+    }
+    $pageDiv .= Display::tag(
+        'li',
+        $pageAnchorFirst,
+        $pageItemAttributes
+    );
+    $pageDiv .= Display::tag(
+        'li',
+        $pageAnchor,
+        $pageItemAttributes
+    );
+    for (
+        $i = max(1, $pageCurrent - 3);
+        $i <= min($pageTotal, $pageCurrent + 3);
+        $i++
+    ) {
+        $pageUrl = getCourseCategoryUrl(
+            $i,
+            $pageLength
+        );
+        if ($i === $pageCurrent) {
+            $pageAnchor = Display::tag(
+                'a',
+                $i
+            );
+            $pageItemAttributes = array(
+                'class' => 'active'
+            );
+        } else {
+            $pageAnchor = Display::tag(
+                'a',
+                $i,
+                array(
+                    'href' => $pageUrl,
+                )
+            );
+            $pageItemAttributes = array();
+        }
+        $pageDiv .= Display::tag(
+            'li',
+            $pageAnchor,
+            $pageItemAttributes
+        );
+    }
+    if ($pageTotal == $pageCurrent) {
+        $pageAnchor = Display::tag(
+            'a',
+            '>'
+        );
+        $pageAnchorLast = Display::tag(
+            'a',
+            '>>'
+        );
+        $pageItemAttributes = array(
+            'class' => 'disabled'
+        );
+    } else {
+        $pageAnchor = Display::tag(
+            'a',
+            '>',
+            array(
+                'href' => getCourseCategoryUrl(
+                    $pageCurrent + 1,
+                    $pageLength
+                ),
+            )
+        );
+        $pageAnchorLast = Display::tag(
+            'a',
+            '>>',
+            array(
+                'href' => getCourseCategoryUrl(
+                    $pageTotal,
+                    $pageLength
+                ),
+            )
+
+        );
+        $pageItemAttributes = array();
+    }
+    $pageDiv .= Display::tag(
+        'li',
+        $pageAnchor,
+        $pageItemAttributes
+    );
+    $pageDiv .= Display::tag(
+        'li',
+        $pageAnchorLast,
+        $pageItemAttributes
+    );
+    $pageDiv = Display::div(
+        Display::tag(
+            'ul',
+            $pageDiv
+        ),
+        array(
+            'class' => 'pagination pagination-centered',
+        )
+    );
+
+    return $pageDiv;
+}
+
+
+    /**
+     * Return URL to course catalog
+     * @param $pageCurrent
+     * @param $pageLength
+     * @param null $categoryCode
+     * @param null $hiddenLinks
+     * @param null $action
+     * @return null|string
+     */
+    function getCourseCategoryUrl(
+        $pageCurrent,
+        $pageLength,
+        $categoryCode = null,
+        $hiddenLinks = null,
+        $action = null
+    )
+    {
+        $action = isset($action) ? Security::remove_XSS($action) :
+            Security::remove_XSS($_REQUEST['action']);
+        $pageUrl = api_get_self() .
+            '?action=' . $action .
+            '&category_code=' . (
+            isset($categoryCode) ? $categoryCode :
+                Security::remove_XSS($_REQUEST['category_code'])
+            ) .
+            '&hidden_links=' . (
+            isset($hiddenLinks) ? $hiddenLinks :
+                Security::remove_XSS($_REQUEST['hidden_links'])
+            ).
+            '&pageCurrent=' . $pageCurrent .
+            '&pageLength=' . $pageLength
+        ;
+        switch ($action) {
+            case 'subscribe' :
+                $pageUrl .=
+                    '&search_term=' . $_REQUEST['search_term'] .
+                    '&search_course=1' .
+                    '&sec_token=' . $_SESSION['sec_token'];
+                break;
+            case 'display_courses' :
+                // No break
+            default :
+                break;
+
+        }
+        return $pageUrl;
+}
 /**
  CREATE TABLE IF NOT EXISTS access_url_rel_course_category (access_url_id int unsigned NOT NULL, course_category_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, course_category_id));
  */

+ 56 - 8
main/template/default/auth/courses_categories.php

@@ -6,10 +6,23 @@
 * @author Christian Fasanando <christian1827@gmail.com> - Beeznest
 * @package chamilo.auth
 */
-$stok = Security::get_token();
+
+if (Security::remove_XSS($_REQUEST['action']) !== 'subscribe') {
+    $stok = Security::get_token();
+} else {
+    $stok = $_SESSION['sec_token'];
+}
 
 $showCourses = CoursesAndSessionsCatalog::showCourses();
 $showSessions = CoursesAndSessionsCatalog::showSessions();
+$pageCurrent = isset($pageCurrent) ? $pageCurrent :
+    isset($_GET['pageCurrent']) ? intval($_GET['pageCurrent']) :
+        1;
+$pageLength = isset($pageLength) ? $pageLength :
+    isset($_GET['pageLength']) ? intval($_GET['pageLength']) :
+        10;
+$pageTotal = intval(ceil(intval($countCoursesInCategory) / $pageLength));
+$cataloguePagination = getCataloguePagination($pageCurrent, $pageLength, $pageTotal);
 
 if ($showSessions && isset($_POST['date'])) {
     $date = $_POST['date'];
@@ -98,7 +111,7 @@ $userInfo = api_get_user_info();
             <ul class="nav nav-list">
                 <?php if ($showCourses) { ?>
                 <?php if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) { ?>
-                <form class="form-search" method="post" action="<?php echo api_get_self(); ?>?action=subscribe&amp;hidden_links=0">
+                <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
                     <fieldset>
                         <input type="hidden" name="sec_token" value="<?php echo $stok; ?>">
                         <input type="hidden" name="search_course" value="1" />
@@ -127,6 +140,7 @@ $userInfo = api_get_user_info();
 
                 echo '<li class="nav-header">'.get_lang('CourseCategories').'</li>';
 
+                $action = 'display_courses';
                 // level 1
                 foreach ($browse_course_categories[0] as $category) {
                     $category_name = $category['name'];
@@ -137,7 +151,14 @@ $userInfo = api_get_user_info();
                         $category_link = '<strong>'.$category_name.' ('.$count_courses_lv1.')</strong>';
                     } else {
                         if (!empty($count_courses_lv1)) {
-                            $category_link = '<a href="'. api_get_self().'?action=display_courses&amp;category_code='.$category_code.'&amp;hidden_links='.$hidden_links.'">'.$category_name.' ('.$count_courses_lv1.') </a>';
+                            $category_link = '<a href="' .
+                                getCourseCategoryUrl(
+                                    1,
+                                    $pageLength,
+                                    $category_code,
+                                    $hidden_links,
+                                    $action
+                                ) .'">'.$category_name.' ('.$count_courses_lv1.') </a>';
                         } else {
                             $category_link = ''.$category_name.' ('.$count_courses_lv1.')';
                         }
@@ -153,7 +174,14 @@ $userInfo = api_get_user_info();
                             if ($code == $subcategory1_code) {
                                 $subcategory1_link = '<strong>'.$subcategory1_name.' ('.$count_courses_lv2.')</strong>';
                             } else {
-                                $subcategory1_link = '<a href="'. api_get_self().'?action=display_courses&amp;category_code='.$subcategory1_code.'&amp;hidden_links='.$hidden_links.'">'.$subcategory1_name.' ('.$count_courses_lv2.') </a> ';
+                                $subcategory1_link = '<a href="' .
+                                    getCourseCategoryUrl(
+                                        1,
+                                        $pageLength,
+                                        $subcategory1_code,
+                                        $hidden_links,
+                                        $action
+                                    ) . '">'.$subcategory1_name.' ('.$count_courses_lv2.') </a> ';
                             }
                             echo '<li style="margin-left:20px;">'.$subcategory1_link.'</li>';
 
@@ -166,7 +194,14 @@ $userInfo = api_get_user_info();
                                     if ($code == $subcategory2_code) {
                                         $subcategory2_link = '<strong>'.$subcategory2_name.' ('.$count_courses_lv3.')</strong>';
                                     } else {
-                                        $subcategory2_link = '<a href="'. api_get_self().'?action=display_courses&amp;category_code='.$subcategory2_code.'&amp;hidden_links='.$hidden_links.'">'.$subcategory2_name.'</a> ('.$count_courses_lv3.')';
+                                        $subcategory2_link = '<a href="' .
+                                            getCourseCategoryUrl(
+                                                1,
+                                                $pageLength,
+                                                $subcategory2_code,
+                                                $hidden_links,
+                                                $action
+                                            ) . '">'.$subcategory2_name.'</a> ('.$count_courses_lv3.')';
                                     }
                                     echo '<li style="margin-left:40px;">'.$subcategory2_link.'</li>';
 
@@ -179,7 +214,14 @@ $userInfo = api_get_user_info();
                                             if ($code == $subcategory3_code) {
                                                 $subcategory3_link = '<strong>'.$subcategory3_name.' ('.$count_courses_lv4.')</strong>';
                                             } else {
-                                                $subcategory3_link = '<a href="'. api_get_self().'?action=display_courses&amp;category_code='.$subcategory3_code.'&amp;hidden_links='.$hidden_links.'">'.$subcategory3_name.' ('.$count_courses_lv4.') </a>';
+                                                $subcategory3_link = '<a href="' .
+                                                    getCourseCategoryUrl(
+                                                        1,
+                                                        $pageLength,
+                                                        $subcategory3_code,
+                                                        $hidden_links,
+                                                        $action
+                                                    ) . '">'.$subcategory3_name.' ('.$count_courses_lv4.') </a>';
                                             }
                                             echo '<li style="margin-left:60px;">'.$subcategory3_link.'</li>';
                                         }
@@ -198,11 +240,11 @@ $userInfo = api_get_user_info();
                         <?php if ($action == 'display_sessions' && $_SERVER['REQUEST_METHOD'] != 'POST') { ?>
                             <strong><?php echo get_lang('SessionList'); ?></strong>
                         <?php } else { ?>
-                            <a href="<?php echo api_get_self() ?>?action=display_sessions"><?php echo get_lang('SessionList'); ?></a>
+                            <a href="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>"><?php echo get_lang('SessionList'); ?></a>
                         <?php } ?>
                     </li>
                     <li class="nav-header"><?php echo get_lang('SearchActiveSessions') ?></li>
-                    <form class="form-search" method="post" action="<?php echo api_get_self(); ?>?action=display_sessions">
+                    <form class="form-search" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>">
                         <div class="input-append">
                             <?php echo Display::input('date', 'date', $date, array(
                                 'class' => 'span2',
@@ -217,6 +259,9 @@ $userInfo = api_get_user_info();
     </div>
 
     <div class="span9">
+        <?php
+            echo $cataloguePagination;
+        ?>
         <?php if ($showCourses && $action != 'display_sessions') { ?>
         <?php if (!empty($message)) { Display::display_confirmation_message($message, false); }
         if (!empty($error)) { Display::display_error_message($error, false); }
@@ -313,6 +358,9 @@ $userInfo = api_get_user_info();
             }
         } ?>
         <?php } ?>
+        <?php
+            echo $cataloguePagination;
+        ?>
     </div>
 </div>
 

+ 4 - 2
main/template/default/auth/sessions_catalog.tpl

@@ -47,7 +47,7 @@
         {% if showCourses %}
             <div class="well">
                 {% if not hiddenLinks %}
-                    <form class="form-search" method="post" action="{{ api_get_self }}?action=subscribe&amp;hidden_links=0">
+                    <form class="form-search" method="post" action="{{ courseUrl }}">
                         <fieldset>
                             <input type="hidden" name="sec_token" value="{{ searchToken }}">
                             <input type="hidden" name="search_course" value="1" />
@@ -88,7 +88,7 @@
                     </li>
                     <li class="nav-header">{{ 'SearchSessions' | get_lang }}</li>
                 </ul>
-                <form class="form-search" method="post" action="{{ api_get_self }}?action=display_sessions">
+                <form class="form-search" method="post" action="{{ sessionUrl }}">
                     <div class="input-append">
                         <input type="date" name="date" id="date" class="span2" value="{{ searchDate }}" readonly>
                         <button class="btn" type="submit">{{ 'Search' | get_lang }}</button>
@@ -102,6 +102,7 @@
             <h2>{{ nameTools }}</h2>
         </div>
 
+        {{ cataloguePagination }}
         {% for session in sessions_blocks %}
             <div class="well" id="session-{{ session.id }}">
                 <div class="row">
@@ -142,6 +143,7 @@
                 </div>
             </div>
         {% endfor %}
+        {{ cataloguePagination }}
     </div>
 
 {% endblock %}