Browse Source

Merge branch '1.10.x' into bootstrap

aragonc 9 years ago
parent
commit
835a969d19
82 changed files with 2472 additions and 2263 deletions
  1. 8 6
      main/admin/course_edit.php
  2. 10 12
      main/admin/course_list.php
  3. 2 1
      main/admin/statistics/index.php
  4. 11 7
      main/admin/system_announcements.php
  5. 24 6
      main/document/upload.php
  6. 18 5
      main/exercice/exercise_result.php
  7. 2 2
      main/inc/lib/AnnouncementEmail.php
  8. 82 41
      main/inc/lib/AnnouncementManager.php
  9. 0 1
      main/inc/lib/CoursesAndSessionsCatalog.class.php
  10. 1 0
      main/inc/lib/GamificationUtils.php
  11. 8 5
      main/inc/lib/TeacherTimeReport.php
  12. 5 1
      main/inc/lib/VideoChat.php
  13. 13 14
      main/inc/lib/agenda.lib.php
  14. 6 2
      main/inc/lib/api.lib.php
  15. 78 73
      main/inc/lib/app_view.php
  16. 29 21
      main/inc/lib/banner.lib.php
  17. 13 4
      main/inc/lib/career.lib.php
  18. 7 4
      main/inc/lib/course.lib.php
  19. 1 0
      main/inc/lib/course_description.lib.php
  20. 3 2
      main/inc/lib/course_home.lib.php
  21. 25 13
      main/inc/lib/course_request.lib.php
  22. 9 7
      main/inc/lib/custom_pages.class.php
  23. 1 0
      main/inc/lib/dashboard.lib.php
  24. 1 0
      main/inc/lib/database.constants.inc.php
  25. 1 2
      main/inc/lib/database.lib.php
  26. 1 0
      main/inc/lib/database.mysqli.lib.php
  27. 47 13
      main/inc/lib/diagnoser.lib.php
  28. 0 1
      main/inc/lib/display.lib.php
  29. 39 33
      main/inc/lib/event_email_template.class.php
  30. 64 71
      main/inc/lib/events.lib.php
  31. 73 62
      main/inc/lib/events_email.class.php
  32. 10 7
      main/inc/lib/extra_field_value.lib.php
  33. 9 10
      main/inc/lib/fileDisplay.lib.php
  34. 52 57
      main/inc/lib/fileManage.lib.php
  35. 3 1
      main/inc/lib/fileUpload.lib.php
  36. 0 95
      main/inc/lib/file_store.class.php
  37. 2 1
      main/inc/lib/formvalidator/Element/DatePicker.php
  38. 2 1
      main/inc/lib/formvalidator/Element/DateTimePicker.php
  39. 55 56
      main/inc/lib/geometry.lib.php
  40. 37 31
      main/inc/lib/glossary.lib.php
  41. 18 4
      main/inc/lib/grade_model.lib.php
  42. 11 4
      main/inc/lib/gradebook.lib.php
  43. 76 69
      main/inc/lib/image.lib.php
  44. 1 1
      main/inc/lib/import.lib.php
  45. 46 63
      main/inc/lib/legal.lib.php
  46. 1 1
      main/inc/lib/link.lib.php
  47. 6 15
      main/inc/lib/login_redirection.class.php
  48. 64 29
      main/inc/lib/message.lib.php
  49. 0 1
      main/inc/lib/model.lib.php
  50. 6 4
      main/inc/lib/myspace.lib.php
  51. 41 52
      main/inc/lib/nanogong.lib.php
  52. 19 5
      main/inc/lib/notebook.lib.php
  53. 34 42
      main/inc/lib/online.inc.php
  54. 0 1
      main/inc/lib/pdf.lib.php
  55. 15 13
      main/inc/lib/plugin.class.php
  56. 1 0
      main/inc/lib/plugin.lib.php
  57. 3 1
      main/inc/lib/promotion.lib.php
  58. 5 1
      main/inc/lib/skill.lib.php
  59. 10 18
      main/inc/lib/social.lib.php
  60. 147 86
      main/inc/lib/specific_fields_manager.lib.php
  61. 26 13
      main/inc/lib/statistics.lib.php
  62. 255 256
      main/inc/lib/statsUtils.lib.inc.php
  63. 18 10
      main/inc/lib/sub_language.class.php
  64. 2 2
      main/inc/lib/surveymanager.lib.php
  65. 2 2
      main/inc/lib/system_announcements.lib.php
  66. 1 3
      main/inc/lib/table_sort.class.php
  67. 10 27
      main/inc/lib/template.lib.php
  68. 17 12
      main/inc/lib/thematic.lib.php
  69. 64 86
      main/inc/lib/tracking.lib.php
  70. 39 35
      main/inc/lib/urlmanager.lib.php
  71. 22 7
      main/inc/lib/usermanager.lib.php
  72. 48 19
      main/inc/lib/userportal.lib.php
  73. 1 1
      main/social/group_add.php
  74. 8 6
      main/social/group_topics.php
  75. 5 3
      main/social/group_view.php
  76. 1 1
      main/social/search.php
  77. 119 113
      main/template/default/auth/courses_categories.php
  78. 111 0
      main/template/default/layout/footer.js.tpl
  79. 1 155
      main/template/default/layout/footer.tpl
  80. 6 392
      main/template/default/layout/head.tpl
  81. 425 0
      main/template/default/layout/header.js.tpl
  82. 35 42
      tests/main/inc/lib/tracking.lib.test.php

+ 8 - 6
main/admin/course_edit.php

@@ -168,7 +168,6 @@ if (!empty($coursesInSession)) {
             $allTeachers
             $allTeachers
         );
         );
         $courseInfo[$groupName] = $sessionTeachers;
         $courseInfo[$groupName] = $sessionTeachers;
-
     }
     }
 }
 }
 
 
@@ -264,7 +263,7 @@ $(function() {
 });
 });
 </script>';
 </script>';
 
 
-$form->addButton('submit', get_lang('ModifyCourseInfo'), 'pencil', 'primary');
+$form->addButtonUpdate(get_lang('ModifyCourseInfo'));
 
 
 // Set some default values
 // Set some default values
 $courseInfo['disk_quota'] = round(DocumentManager::get_course_quota($courseInfo['code']) / 1024 / 1024, 1);
 $courseInfo['disk_quota'] = round(DocumentManager::get_course_quota($courseInfo['code']) / 1024 / 1024, 1);
@@ -360,17 +359,21 @@ if ($form->validate()) {
     // Updating teachers
     // Updating teachers
 
 
     if ($addTeacherToSessionCourses) {
     if ($addTeacherToSessionCourses) {
-
         // Updating session coaches
         // Updating session coaches
         $sessionCoaches = $course['session_coaches'];
         $sessionCoaches = $course['session_coaches'];
         if (!empty($sessionCoaches)) {
         if (!empty($sessionCoaches)) {
             foreach ($sessionCoaches as $sessionId => $teacherInfo) {
             foreach ($sessionCoaches as $sessionId => $teacherInfo) {
                 $coachesToSubscribe = $teacherInfo['coaches_by_session'];
                 $coachesToSubscribe = $teacherInfo['coaches_by_session'];
-                SessionManager::updateCoaches($sessionId, $courseId, $coachesToSubscribe, true);
+                SessionManager::updateCoaches(
+                    $sessionId,
+                    $courseId,
+                    $coachesToSubscribe,
+                    true
+                );
             }
             }
         }
         }
 
 
-        CourseManager::updateTeachers($courseId, $teachers, false, true, false);
+        CourseManager::updateTeachers($courseId, $teachers, true, true, false);
     } else {
     } else {
         // Normal behaviour
         // Normal behaviour
         CourseManager::updateTeachers($courseId, $teachers, true, false);
         CourseManager::updateTeachers($courseId, $teachers, true, false);
@@ -379,7 +382,6 @@ if ($form->validate()) {
         $sessionCoaches = $course['session_coaches'];
         $sessionCoaches = $course['session_coaches'];
         if (!empty($sessionCoaches)) {
         if (!empty($sessionCoaches)) {
             foreach ($sessionCoaches as $sessionId => $coachesToSubscribe) {
             foreach ($sessionCoaches as $sessionId => $coachesToSubscribe) {
-                //$coachesToSubscribe = isset($teacherInfo['coaches_by_session']) ? $teacherInfo['coaches_by_session'] : null;
                 if (!empty($coachesToSubscribe)) {
                 if (!empty($coachesToSubscribe)) {
                     SessionManager::updateCoaches(
                     SessionManager::updateCoaches(
                         $sessionId,
                         $sessionId,

+ 10 - 12
main/admin/course_list.php

@@ -221,6 +221,7 @@ function get_course_data_by_session($from, $number_of_items, $column, $direction
         $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]);
         $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]);
         $courses[] = $course_rem;
         $courses[] = $course_rem;
     }
     }
+
     return $courses;
     return $courses;
 }
 }
 
 
@@ -359,7 +360,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $form = new FormValidator('search_simple', 'get', '', '', array(), FormValidator::LAYOUT_INLINE);
     $form = new FormValidator('search_simple', 'get', '', '', array(), FormValidator::LAYOUT_INLINE);
     $form->addElement('text', 'keyword', null, array('id' => 'course-search-keyword'));
     $form->addElement('text', 'keyword', null, array('id' => 'course-search-keyword'));
     $form->addButtonSearch(get_lang('SearchCourse'));
     $form->addButtonSearch(get_lang('SearchCourse'));
-    $advanced .= '<a class="btn btn-default" href="'.  api_get_path(WEB_CODE_PATH).'admin/course_list.php?search=advanced"><i class="fa fa-search"></i> '.get_lang('AdvancedSearch').'</a>';
+    $advanced = '<a class="btn btn-default" href="'.  api_get_path(WEB_CODE_PATH).'admin/course_list.php?search=advanced"><i class="fa fa-search"></i> '.get_lang('AdvancedSearch').'</a>';
 
 
     // Create a filter by session
     // Create a filter by session
     $sessionFilter = new FormValidator('course_filter', 'get', '', '', array(), FormValidator::LAYOUT_INLINE);
     $sessionFilter = new FormValidator('course_filter', 'get', '', '', array(), FormValidator::LAYOUT_INLINE);
@@ -389,14 +390,14 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $actions .= $sessionFilter->return_form();
     $actions .= $sessionFilter->return_form();
     $actions .= '</div>';
     $actions .= '</div>';
     $actions .= '<div class="col-md-4">';
     $actions .= '<div class="col-md-4">';
-        
-        $actions .= $advanced;
-        $actions .= '<div class="pull-right">';
-        $actions .= '<a href="course_add.php">'.Display::return_icon('new_course.png', get_lang('AddCourse'),'',ICON_SIZE_MEDIUM).'</a> ';
-        if (api_get_setting('course_validation') == 'true') {
-            $actions .= '<a href="course_request_review.php">'.Display::return_icon('course_request_pending.png', get_lang('ReviewCourseRequests'),'',ICON_SIZE_MEDIUM).'</a>';
-        }
-        $actions .= '</div>';
+
+    $actions .= $advanced;
+    $actions .= '<div class="pull-right">';
+    $actions .= '<a href="course_add.php">'.Display::return_icon('new_course.png', get_lang('AddCourse'),'',ICON_SIZE_MEDIUM).'</a> ';
+    if (api_get_setting('course_validation') == 'true') {
+        $actions .= '<a href="course_request_review.php">'.Display::return_icon('course_request_pending.png', get_lang('ReviewCourseRequests'),'',ICON_SIZE_MEDIUM).'</a>';
+    }
+    $actions .= '</div>';
     $actions .= '</div>';
     $actions .= '</div>';
     $actions .= '</div>';
     $actions .= '</div>';
     $actions .= '
     $actions .= '
@@ -408,9 +409,6 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
         });
         });
     });
     });
     </script>';
     </script>';
-    
-   
-    
 
 
     if (isset($_GET['session_id']) && !empty($_GET['session_id'])) {
     if (isset($_GET['session_id']) && !empty($_GET['session_id'])) {
         // Create a sortable table with the course data filtered by session
         // Create a sortable table with the course data filtered by session

+ 2 - 1
main/admin/statistics/index.php

@@ -61,7 +61,8 @@ echo '</tr></table>';
 
 
 $course_categories = Statistics::getCourseCategories();
 $course_categories = Statistics::getCourseCategories();
 echo '<br/><br/>';//@todo: spaces between elements should be handled in the css, br should be removed if only there for presentation
 echo '<br/><br/>';//@todo: spaces between elements should be handled in the css, br should be removed if only there for presentation
-switch ($_REQUEST['report']) {
+$report = isset($_REQUEST['report']) ? $_REQUEST['report'] : '';
+switch ($report) {
     case 'courses':
     case 'courses':
         // total amount of courses
         // total amount of courses
         foreach ($course_categories as $code => $name) {
         foreach ($course_categories as $code => $name) {

+ 11 - 7
main/admin/system_announcements.php

@@ -6,8 +6,6 @@
  *	@package chamilo.admin.announcement
  *	@package chamilo.admin.announcement
  */
  */
 
 
-/* INIT SECTION */
-
 // Resetting the course id.
 // Resetting the course id.
 $cidReset = true;
 $cidReset = true;
 
 
@@ -25,7 +23,10 @@ $action_todo = false;
 api_protect_admin_script(true);
 api_protect_admin_script(true);
 
 
 // Setting breadcrumbs.
 // Setting breadcrumbs.
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array(
+    "url" => 'index.php',
+    "name" => get_lang('PlatformAdmin'),
+);
 
 
 $tool_name = null;
 $tool_name = null;
 
 
@@ -90,8 +91,8 @@ switch($action) {
         // Add an announcement.
         // Add an announcement.
         $values['action'] = 'add';
         $values['action'] = 'add';
         // Set default time window: NOW -> NEXT WEEK
         // Set default time window: NOW -> NEXT WEEK
-        $values['start'] = date('Y-m-d H:i:s',api_strtotime(api_get_local_time()));
-        $values['end']   = date('Y-m-d H:i:s',api_strtotime(api_get_local_time()) + (7 * 24 * 60 * 60));
+        $values['start'] = date('Y-m-d H:i:s', api_strtotime(api_get_local_time()));
+        $values['end']   = date('Y-m-d H:i:s', api_strtotime(api_get_local_time()) + (7 * 24 * 60 * 60));
 
 
         $values['range'] =
         $values['range'] =
             substr(api_get_local_time(time()), 0, 16).' / '.
             substr(api_get_local_time(time()), 0, 16).' / '.
@@ -230,7 +231,10 @@ if ($action_todo) {
                 );
                 );
 
 
                 if ($announcement_id !== false) {
                 if ($announcement_id !== false) {
-                    SystemAnnouncementManager::announcement_for_groups($announcement_id, array($values['group']));
+                    SystemAnnouncementManager::announcement_for_groups(
+                        $announcement_id,
+                        array($values['group'])
+                    );
                     Display :: display_confirmation_message(get_lang('AnnouncementAdded'));
                     Display :: display_confirmation_message(get_lang('AnnouncementAdded'));
                 } else {
                 } else {
                     $show_announcement_list = false;
                     $show_announcement_list = false;
@@ -309,5 +313,5 @@ if ($show_announcement_list) {
     $table->set_form_actions($form_actions);
     $table->set_form_actions($form_actions);
     $table->display();
     $table->display();
 }
 }
-/* FOOTER */
+
 Display :: display_footer();
 Display :: display_footer();

+ 24 - 6
main/document/upload.php

@@ -130,7 +130,10 @@ if (!empty($groupId)) {
 
 
     // Only courseadmin or group members allowed
     // Only courseadmin or group members allowed
     if ($is_allowed_to_edit || GroupManager::is_user_in_group(api_get_user_id(), $groupId)) {
     if ($is_allowed_to_edit || GroupManager::is_user_in_group(api_get_user_id(), $groupId)) {
-        $interbreadcrumb[] = array('url' => '../group/group_space.php?'.api_get_cidreq(), 'name' => get_lang('GroupSpace'));
+        $interbreadcrumb[] = array(
+            'url' => '../group/group_space.php?'.api_get_cidreq(),
+            'name' => get_lang('GroupSpace'),
+        );
     } else {
     } else {
         api_not_allowed(true);
         api_not_allowed(true);
     }
     }
@@ -170,9 +173,15 @@ if (isset($_REQUEST['certificate'])) {
 
 
 // Breadcrumbs
 // Breadcrumbs
 if ($is_certificate_mode) {
 if ($is_certificate_mode) {
-    $interbreadcrumb[] = array('url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
+    $interbreadcrumb[] = array(
+        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'name' => get_lang('Gradebook'),
+    );
 } else {
 } else {
-    $interbreadcrumb[] = array('url' => './document.php?id='.$document_id.'&'.api_get_cidreq(), 'name'=> get_lang('Documents'));
+    $interbreadcrumb[] = array(
+        'url' => './document.php?id='.$document_id.'&'.api_get_cidreq(),
+        'name' => get_lang('Documents'),
+    );
 }
 }
 
 
 // Interbreadcrumb for the current directory root path
 // Interbreadcrumb for the current directory root path
@@ -259,7 +268,13 @@ $form->addButtonAdvancedSettings('advanced_params');
 $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
 $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
 
 
 // Check box options
 // Check box options
-$form->addElement('checkbox', 'unzip', get_lang('Options'), get_lang('Uncompress'), 'onclick="javascript: check_unzip();" value="1"');
+$form->addElement(
+    'checkbox',
+    'unzip',
+    get_lang('Options'),
+    get_lang('Uncompress'),
+    'onclick="javascript: check_unzip();" value="1"'
+);
 
 
 if (api_get_setting('search_enabled') == 'true') {
 if (api_get_setting('search_enabled') == 'true') {
     //TODO: include language file
     //TODO: include language file
@@ -327,8 +342,11 @@ $nav_info = api_get_navigator();
 if ($nav_info ['name'] == 'Internet Explorer') {
 if ($nav_info ['name'] == 'Internet Explorer') {
     echo $simple_form;
     echo $simple_form;
 } else {
 } else {
-    $headers = array(get_lang('Send') , get_lang('Send').' ('.get_lang('Simple').')');
-    echo Display::tabs($headers, array($multiple_form, $simple_form),'tabs');
+    $headers = array(
+        get_lang('Upload'),
+        get_lang('Upload').' ('.get_lang('Simple').')',
+    );
+    echo Display::tabs($headers, array($multiple_form, $simple_form), 'tabs');
 }
 }
 
 
 Display::display_footer();
 Display::display_footer();

+ 18 - 5
main/exercice/exercise_result.php

@@ -97,8 +97,8 @@ $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
 if ($origin == 'learnpath') {
 if ($origin == 'learnpath') {
 ?>
 ?>
 	<form method="GET" action="exercise.php?<?php echo api_get_cidreq() ?>">
 	<form method="GET" action="exercise.php?<?php echo api_get_cidreq() ?>">
-	<input type="hidden" name="origin" 					value="<?php echo $origin; ?>" />
-    <input type="hidden" name="learnpath_id" 			value="<?php echo $learnpath_id; ?>" />
+	<input type="hidden" name="origin" value="<?php echo $origin; ?>" />
+    <input type="hidden" name="learnpath_id" value="<?php echo $learnpath_id; ?>" />
     <input type="hidden" name="learnpath_item_id" 		value="<?php echo $learnpath_item_id; ?>" />
     <input type="hidden" name="learnpath_item_id" 		value="<?php echo $learnpath_item_id; ?>" />
     <input type="hidden" name="learnpath_item_view_id"  value="<?php echo $learnpath_item_view_id; ?>" />
     <input type="hidden" name="learnpath_item_view_id"  value="<?php echo $learnpath_item_view_id; ?>" />
 <?php
 <?php
@@ -127,7 +127,12 @@ if ($objExercise->selectAttempts() > 0) {
         exit;
         exit;
     }
     }
 }
 }
-$total_score = $objExercise->get_stat_track_exercise_info_by_exe_id($objExercise->id)['exe_result'];
+
+$total_score = 0;
+if (!empty($exercise_stat_info)) {
+    $total_score = $exercise_stat_info['exe_result'];
+}
+
 $max_score = $objExercise->get_max_score();
 $max_score = $objExercise->get_max_score();
 
 
 Display :: display_normal_message(get_lang('Saved').'<br />',false);
 Display :: display_normal_message(get_lang('Saved').'<br />',false);
@@ -136,12 +141,20 @@ Display :: display_normal_message(get_lang('Saved').'<br />',false);
 ExerciseLib::display_question_list_by_attempt($objExercise, $exe_id, true);
 ExerciseLib::display_question_list_by_attempt($objExercise, $exe_id, true);
 
 
 //Unset session for clock time
 //Unset session for clock time
-ExerciseLib::exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);
+ExerciseLib::exercise_time_control_delete(
+    $objExercise->id,
+    $learnpath_id,
+    $learnpath_item_id
+);
 ExerciseLib::delete_chat_exercise_session($exe_id);
 ExerciseLib::delete_chat_exercise_session($exe_id);
 
 
 if ($origin != 'learnpath') {
 if ($origin != 'learnpath') {
     echo '<hr>';
     echo '<hr>';
-    echo Display::url(get_lang('ReturnToCourseHomepage'), api_get_course_url(), array('class' => 'btn btn-primary'));
+    echo Display::url(
+        get_lang('ReturnToCourseHomepage'),
+        api_get_course_url(),
+        array('class' => 'btn btn-primary')
+    );
 
 
     if (api_is_allowed_to_session_edit()) {
     if (api_is_allowed_to_session_edit()) {
         Session::erase('objExercise');
         Session::erase('objExercise');

+ 2 - 2
main/inc/lib/AnnouncementEmail.php

@@ -195,9 +195,9 @@ class AnnouncementEmail
      *
      *
      * @return array
      * @return array
      */
      */
-    public function sender($key = '')
+    public function sender($key = '',  $userId = '')
     {
     {
-        global $_user;
+        $_user = api_get_user_info($userId);
 
 
         return $key ? $_user[$key] : $_user;
         return $key ? $_user[$key] : $_user;
     }
     }

+ 82 - 41
main/inc/lib/AnnouncementManager.php

@@ -9,8 +9,12 @@
  */
  */
 class AnnouncementManager
 class AnnouncementManager
 {
 {
+    /**
+     * Constructor
+     */
     public function __construct()
     public function __construct()
     {
     {
+
     }
     }
 
 
     /**
     /**
@@ -71,8 +75,8 @@ class AnnouncementManager
 
 
     /**
     /**
      * Gets all announcements from a course
      * Gets all announcements from a course
-     * @param	string course db
-     * @param	int session id
+     * @param	array $course_info
+     * @param	int $session_id
      * @return	array html with the content and count of announcements or false otherwise
      * @return	array html with the content and count of announcements or false otherwise
      */
      */
     public static function get_all_annoucement_by_course($course_info, $session_id = 0)
     public static function get_all_annoucement_by_course($course_info, $session_id = 0)
@@ -85,11 +89,12 @@ class AnnouncementManager
 
 
         $sql = "SELECT DISTINCT announcement.id, announcement.title, announcement.content
         $sql = "SELECT DISTINCT announcement.id, announcement.title, announcement.content
 				FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
 				FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-				WHERE   announcement.id = toolitemproperties.ref AND
-				        toolitemproperties.tool='announcement' AND
-				        announcement.session_id  = '$session_id' AND
-				        announcement.c_id = $course_id AND
-				        toolitemproperties.c_id = $course_id
+				WHERE
+				    announcement.id = toolitemproperties.ref AND
+                    toolitemproperties.tool='announcement' AND
+                    announcement.session_id  = '$session_id' AND
+                    announcement.c_id = $course_id AND
+                    toolitemproperties.c_id = $course_id
 				ORDER BY display_order DESC";
 				ORDER BY display_order DESC";
         $rs = Database::query($sql);
         $rs = Database::query($sql);
         $num_rows = Database::num_rows($rs);
         $num_rows = Database::num_rows($rs);
@@ -98,8 +103,10 @@ class AnnouncementManager
             while ($row = Database::fetch_array($rs)) {
             while ($row = Database::fetch_array($rs)) {
                 $list[] = $row;
                 $list[] = $row;
             }
             }
+
             return $list;
             return $list;
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -113,11 +120,28 @@ class AnnouncementManager
     public static function change_visibility_announcement($_course, $id)
     public static function change_visibility_announcement($_course, $id)
     {
     {
         $session_id = api_get_session_id();
         $session_id = api_get_session_id();
-        $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $id, $session_id);
+        $item_visibility = api_get_item_visibility(
+            $_course,
+            TOOL_ANNOUNCEMENT,
+            $id,
+            $session_id
+        );
         if ($item_visibility == '1') {
         if ($item_visibility == '1') {
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'invisible', api_get_user_id());
+            api_item_property_update(
+                $_course,
+                TOOL_ANNOUNCEMENT,
+                $id,
+                'invisible',
+                api_get_user_id()
+            );
         } else {
         } else {
-            api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'visible', api_get_user_id());
+            api_item_property_update(
+                $_course,
+                TOOL_ANNOUNCEMENT,
+                $id,
+                'visible',
+                api_get_user_id()
+            );
         }
         }
 
 
         return true;
         return true;
@@ -142,7 +166,13 @@ class AnnouncementManager
         $announcements = self::get_all_annoucement_by_course($_course, api_get_session_id());
         $announcements = self::get_all_annoucement_by_course($_course, api_get_session_id());
         if (!empty($announcements)) {
         if (!empty($announcements)) {
             foreach ($announcements as $annon) {
             foreach ($announcements as $annon) {
-                api_item_property_update($_course, TOOL_ANNOUNCEMENT, $annon['id'], 'delete', api_get_user_id());
+                api_item_property_update(
+                    $_course,
+                    TOOL_ANNOUNCEMENT,
+                    $annon['id'],
+                    'delete',
+                    api_get_user_id()
+                );
             }
             }
         }
         }
     }
     }
@@ -295,14 +325,17 @@ class AnnouncementManager
     {
     {
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
-        $sql_max = "SELECT MAX(display_order) FROM $tbl_announcement WHERE c_id = $course_id ";
-        $res_max = Database::query($sql_max);
+        $sql = "SELECT MAX(display_order)
+                FROM $tbl_announcement
+                WHERE c_id = $course_id ";
+        $res_max = Database::query($sql);
 
 
         $order = 0;
         $order = 0;
         if (Database::num_rows($res_max)) {
         if (Database::num_rows($res_max)) {
             $row_max = Database::fetch_array($res_max);
             $row_max = Database::fetch_array($res_max);
-            $order   = intval($row_max[0])+1;
+            $order = intval($row_max[0])+1;
         }
         }
+
         return $order;
         return $order;
     }
     }
 
 
@@ -331,14 +364,8 @@ class AnnouncementManager
 
 
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
 
 
-        // filter data
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
-
         if (empty($end_date)) {
         if (empty($end_date)) {
             $end_date = api_get_utc_datetime();
             $end_date = api_get_utc_datetime();
-        } else {
-            $end_date = Database::escape_string($end_date);
         }
         }
 
 
         $order = self::get_last_announcement_order();
         $order = self::get_last_announcement_order();
@@ -447,16 +474,12 @@ class AnnouncementManager
 
 
         // Database definitions
         // Database definitions
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
         $order = self::get_last_announcement_order();
         $order = self::get_last_announcement_order();
 
 
         $now = api_get_utc_datetime();
         $now = api_get_utc_datetime();
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
         // store in the table announcement
         // store in the table announcement
-
         $params = [
         $params = [
             'c_id' => $course_id,
             'c_id' => $course_id,
             'content' => $newContent,
             'content' => $newContent,
@@ -549,16 +572,18 @@ class AnnouncementManager
         $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
         $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
         $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
 
 
-        $emailTitle = Database::escape_string($emailTitle);
-        $newContent = Database::escape_string($newContent);
         $id = intval($id);
         $id = intval($id);
 
 
-        // store the modifications in the table announcement
-        $sql = "UPDATE $tbl_announcement SET
-                    content = '$newContent',
-                    title = '$emailTitle'
-                WHERE c_id = $course_id AND id='$id'";
-        Database::query($sql);
+        $params = [
+            'title' => $emailTitle,
+            'content' => $newContent
+        ];
+
+        Database::update(
+            $tbl_announcement,
+            $params,
+            ['c_id = ? AND id = ?' => [$course_id, $id]]
+        );
 
 
         // save attachment file
         // save attachment file
         $row_attach = self::get_attachment($id);
         $row_attach = self::get_attachment($id);
@@ -684,7 +709,8 @@ class AnnouncementManager
         $insert_id = intval($insert_id);
         $insert_id = intval($insert_id);
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
         // store the modifications in the table tbl_annoucement
         // store the modifications in the table tbl_annoucement
-        $sql = "UPDATE $tbl_announcement SET email_sent='1' WHERE c_id = $course_id AND id = $insert_id";
+        $sql = "UPDATE $tbl_announcement SET email_sent='1'
+                WHERE c_id = $course_id AND id = $insert_id";
         Database::query($sql);
         Database::query($sql);
     }
     }
 
 
@@ -733,10 +759,13 @@ class AnnouncementManager
                 }
                 }
                 $result['content'] = $content;
                 $result['content'] = $content;
                 $result['count'] = $i;
                 $result['count'] = $i;
+
                 return $result;
                 return $result;
             }
             }
+
             return false;
             return false;
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -1008,9 +1037,17 @@ class AnnouncementManager
     {
     {
         $session_id = api_get_session_id();
         $session_id = api_get_session_id();
         if ($session_id != 0) {
         if ($session_id != 0) {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), $session_id, 1);
+            $new_group_list = CourseManager::get_group_list_of_course(
+                api_get_course_id(),
+                $session_id,
+                1
+            );
         } else {
         } else {
-            $new_group_list = CourseManager::get_group_list_of_course(api_get_course_id(), 0, 1);
+            $new_group_list = CourseManager::get_group_list_of_course(
+                api_get_course_id(),
+                0,
+                1
+            );
         }
         }
         return $new_group_list;
         return $new_group_list;
     }
     }
@@ -1225,7 +1262,8 @@ class AnnouncementManager
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
         if (is_array($file) && $file['error'] == 0) {
         if (is_array($file) && $file['error'] == 0) {
-            $courseDir = $_course['path'] . '/upload/announcements'; // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
+            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
+            $courseDir = $_course['path'] . '/upload/announcements';
             $sys_course_path = api_get_path(SYS_COURSE_PATH);
             $sys_course_path = api_get_path(SYS_COURSE_PATH);
             $updir = $sys_course_path . $courseDir;
             $updir = $sys_course_path . $courseDir;
 
 
@@ -1279,7 +1317,8 @@ class AnnouncementManager
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
         if (is_array($file) && $file['error'] == 0) {
         if (is_array($file) && $file['error'] == 0) {
-            $courseDir = $_course['path'] . '/upload/announcements'; // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
+            // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
+            $courseDir = $_course['path'] . '/upload/announcements';
             $sys_course_path = api_get_path(SYS_COURSE_PATH);
             $sys_course_path = api_get_path(SYS_COURSE_PATH);
             $updir = $sys_course_path . $courseDir;
             $updir = $sys_course_path . $courseDir;
 
 
@@ -1294,7 +1333,7 @@ class AnnouncementManager
             } else {
             } else {
                 $new_file_name = uniqid('');
                 $new_file_name = uniqid('');
                 $new_path = $updir . '/' . $new_file_name;
                 $new_path = $updir . '/' . $new_file_name;
-                $result = @move_uploaded_file($file['tmp_name'], $new_path);
+                @move_uploaded_file($file['tmp_name'], $new_path);
                 $safe_file_comment = Database::escape_string($file_comment);
                 $safe_file_comment = Database::escape_string($file_comment);
                 $safe_file_name = Database::escape_string($file_name);
                 $safe_file_name = Database::escape_string($file_name);
                 $safe_new_file_name = Database::escape_string($new_file_name);
                 $safe_new_file_name = Database::escape_string($new_file_name);
@@ -1323,7 +1362,9 @@ class AnnouncementManager
         $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
         $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
         $id = intval($id);
         $id = intval($id);
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
-        $sql = "DELETE FROM $tbl_announcement_attachment WHERE c_id = $course_id AND id = $id";
+        $sql = "DELETE FROM $tbl_announcement_attachment
+                WHERE c_id = $course_id AND id = $id";
+
         Database::query($sql);
         Database::query($sql);
     }
     }
 
 
@@ -1574,7 +1615,7 @@ class AnnouncementManager
         $ths .= Display::tag('th', get_lang('By') );
         $ths .= Display::tag('th', get_lang('By') );
         $ths .= Display::tag('th', get_lang('LastUpdateDate') );
         $ths .= Display::tag('th', get_lang('LastUpdateDate') );
         if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() &&
         if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() &&
-            api_is_element_in_the_session(TOOL_ANNOUNCEMENT,$myrow['id']))
+            api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']))
             OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
             OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
             $ths .= Display::tag('th', get_lang('Modify'));
             $ths .= Display::tag('th', get_lang('Modify'));
         }
         }
@@ -1811,7 +1852,7 @@ class AnnouncementManager
                                     $condition_session
                                     $condition_session
                                 GROUP BY ip.ref
                                 GROUP BY ip.ref
                                 ORDER BY display_order DESC
                                 ORDER BY display_order DESC
-                                LIMIT 0,$maximum";
+                                LIMIT 0, $maximum";
                     }
                     }
                 }
                 }
             }
             }

+ 0 - 1
main/inc/lib/CoursesAndSessionsCatalog.class.php

@@ -57,5 +57,4 @@ class CoursesAndSessionsCatalog
 
 
         return false;
         return false;
     }
     }
-
 }
 }

+ 1 - 0
main/inc/lib/GamificationUtils.php

@@ -1,5 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  * GamificationUtils class
  * GamificationUtils class
  * Functions to manage the gamification mode
  * Functions to manage the gamification mode

+ 8 - 5
main/inc/lib/TeacherTimeReport.php

@@ -9,7 +9,6 @@
  */
  */
 class TeacherTimeReport
 class TeacherTimeReport
 {
 {
-
     /**
     /**
      * The report data
      * The report data
      * @var array
      * @var array
@@ -18,9 +17,9 @@ class TeacherTimeReport
 
 
     /**
     /**
      * Callback for compare sessions names
      * Callback for compare sessions names
-     * @param array $dataA The datab A
+     * @param array $dataA The data A
      * @param array $dataB The data B
      * @param array $dataB The data B
-     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal 
+     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal
      */
      */
     public function compareSessions($dataA, $dataB)
     public function compareSessions($dataA, $dataB)
     {
     {
@@ -31,7 +30,7 @@ class TeacherTimeReport
      * Callback for compare courses names
      * Callback for compare courses names
      * @param array $dataA The datab A
      * @param array $dataA The datab A
      * @param array $dataB The data B
      * @param array $dataB The data B
-     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal 
+     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal
      */
      */
     public function compareCourses($dataA, $dataB)
     public function compareCourses($dataA, $dataB)
     {
     {
@@ -42,7 +41,7 @@ class TeacherTimeReport
      * Callback for compare coaches names
      * Callback for compare coaches names
      * @param array $dataA The datab A
      * @param array $dataA The datab A
      * @param array $dataB The data B
      * @param array $dataB The data B
-     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal 
+     * @return int returns -1 if dataA is less than dataB, 1 if dataA is greater than dataB, and 0 if they are equal
      */
      */
     public function compareCoaches($dataA, $dataB)
     public function compareCoaches($dataA, $dataB)
     {
     {
@@ -63,6 +62,10 @@ class TeacherTimeReport
         uasort($this->data, array($this, 'compareCoaches'));
         uasort($this->data, array($this, 'compareCoaches'));
     }
     }
 
 
+    /**
+     * @param bool|false $withFilter
+     * @return array
+     */
     public function prepareDataToExport($withFilter = false)
     public function prepareDataToExport($withFilter = false)
     {
     {
         $dataToExport = array();
         $dataToExport = array();

+ 5 - 1
main/inc/lib/VideoChat.php

@@ -1,8 +1,9 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  * VideoChat class
  * VideoChat class
- * 
+ *
  * This class provides methods for video chat management.
  * This class provides methods for video chat management.
  *
  *
  * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
  * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
@@ -43,6 +44,7 @@ class VideoChat
      * @param string $name The video chat name
      * @param string $name The video chat name
      * @param int $fromUser The sender user
      * @param int $fromUser The sender user
      * @param int $toUser The receiver user
      * @param int $toUser The receiver user
+     *
      * @return int The created video chat id. Otherwise return false
      * @return int The created video chat id. Otherwise return false
      */
      */
     public static function createRoom($name, $fromUser, $toUser)
     public static function createRoom($name, $fromUser, $toUser)
@@ -61,6 +63,7 @@ class VideoChat
     /**
     /**
      * Check if the video chat exists by its room name
      * Check if the video chat exists by its room name
      * @param string $name The video chat name
      * @param string $name The video chat name
+     *
      * @return boolean
      * @return boolean
      */
      */
     public static function nameExists($name)
     public static function nameExists($name)
@@ -84,6 +87,7 @@ class VideoChat
     /**
     /**
      * Get the video chat info by its room name
      * Get the video chat info by its room name
      * @param string $name The video chat name
      * @param string $name The video chat name
+     *
      * @return array The video chat info. Otherwise return false
      * @return array The video chat info. Otherwise return false
      */
      */
     public static function getChatRoomByName($name)
     public static function getChatRoomByName($name)

+ 13 - 14
main/inc/lib/agenda.lib.php

@@ -2459,8 +2459,8 @@ class Agenda
      */
      */
     public function displayActions($view, $filter = 0)
     public function displayActions($view, $filter = 0)
     {
     {
-        $courseInfo = api_get_course_info();     
-        
+        $courseInfo = api_get_course_info();
+
         $toolbar = '';
         $toolbar = '';
         $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_js.php?type={$this->type}'>".
         $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_js.php?type={$this->type}'>".
             Display::return_icon('calendar.png', get_lang('Calendar'), '', ICON_SIZE_MEDIUM)."</a>";
             Display::return_icon('calendar.png', get_lang('Calendar'), '', ICON_SIZE_MEDIUM)."</a>";
@@ -2469,11 +2469,12 @@ class Agenda
         if (!empty($courseInfo)) {
         if (!empty($courseInfo)) {
             $courseCondition = api_get_cidreq();
             $courseCondition = api_get_cidreq();
         }
         }
-        
+
         $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
         $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
             Display::return_icon('week.png', get_lang('AgendaList'), '', ICON_SIZE_MEDIUM)."</a>";
             Display::return_icon('week.png', get_lang('AgendaList'), '', ICON_SIZE_MEDIUM)."</a>";
-        
-       
+
+        $form = '';
+
         if (api_is_allowed_to_edit(false, true) ||
         if (api_is_allowed_to_edit(false, true) ||
             (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) ||
             (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) ||
             GroupManager::user_has_access(api_get_user_id(), api_get_group_id(), GroupManager::GROUP_TOOL_CALENDAR) &&
             GroupManager::user_has_access(api_get_user_id(), api_get_group_id(), GroupManager::GROUP_TOOL_CALENDAR) &&
@@ -2483,9 +2484,9 @@ class Agenda
                     Display::return_icon('new_event.png', get_lang('AgendaAdd'), '', ICON_SIZE_MEDIUM)."</a>";
                     Display::return_icon('new_event.png', get_lang('AgendaAdd'), '', ICON_SIZE_MEDIUM)."</a>";
             $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=importical&type=course'>".
             $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=importical&type=course'>".
                     Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), '', ICON_SIZE_MEDIUM)."</a>";
                     Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), '', ICON_SIZE_MEDIUM)."</a>";
-            
+
             if ($this->type == 'course') {
             if ($this->type == 'course') {
-                $form = null;
+
                 if (!isset($_GET['action'])) {
                 if (!isset($_GET['action'])) {
 
 
                     $form = new FormValidator(
                     $form = new FormValidator(
@@ -2503,10 +2504,10 @@ class Agenda
                     $selectedValues = $this->parseAgendaFilter($filter);
                     $selectedValues = $this->parseAgendaFilter($filter);
                     $this->showToForm($form, $selectedValues, $attributes);
                     $this->showToForm($form, $selectedValues, $attributes);
                     $form = $form->returnForm();
                     $form = $form->returnForm();
-                }   
+                }
             }
             }
         }
         }
-         
+
         if (api_is_platform_admin() ||
         if (api_is_platform_admin() ||
             api_is_teacher() ||
             api_is_teacher() ||
             api_is_student_boss() ||
             api_is_student_boss() ||
@@ -2544,7 +2545,7 @@ class Agenda
                 }
                 }
             }
             }
         }
         }
-        
+
         $actions = '<div class="row">';
         $actions = '<div class="row">';
         $actions .= '<div class="col-md-9">';
         $actions .= '<div class="col-md-9">';
         if ($view == 'calendar') {
         if ($view == 'calendar') {
@@ -2552,7 +2553,7 @@ class Agenda
         }
         }
         $actions .= '</div>';
         $actions .= '</div>';
         $actions .= '<div class="col-md-3 right">';
         $actions .= '<div class="col-md-3 right">';
-        $actions .= $toolbar; 
+        $actions .= $toolbar;
         $actions .= '</div>';
         $actions .= '</div>';
         $actions .= '</div>';
         $actions .= '</div>';
 
 
@@ -2573,7 +2574,7 @@ class Agenda
         $form->addElement('header', get_lang('ICalFileImport'));
         $form->addElement('header', get_lang('ICalFileImport'));
         $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
         $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
         $form->addRule('ical_import', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('ical_import', get_lang('ThisFieldIsRequired'), 'required');
-        $form->addElement('button', 'ical_submit', get_lang('Import'));
+        $form->addButtonImport(get_lang('Import'), 'ical_submit');
 
 
         return $form;
         return $form;
     }
     }
@@ -3370,6 +3371,4 @@ class Agenda
     {
     {
         $this->isAllowedToEdit = $isAllowedToEdit;
         $this->isAllowedToEdit = $isAllowedToEdit;
     }
     }
-
-
 }
 }

+ 6 - 2
main/inc/lib/api.lib.php

@@ -530,6 +530,10 @@ define('TEACHER_HTML_FULLPAGE', 5);
 define('TIMELINE_STATUS_ACTIVE', '1');
 define('TIMELINE_STATUS_ACTIVE', '1');
 define('TIMELINE_STATUS_INACTIVE', '2');
 define('TIMELINE_STATUS_INACTIVE', '2');
 
 
+// Event email template class
+define ('EVENT_EMAIL_TEMPLATE_ACTIVE',  1);
+define ('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
+
 /**
 /**
  * Inclusion of internationalization libraries
  * Inclusion of internationalization libraries
  */
  */
@@ -6089,8 +6093,8 @@ function api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id = null,
         $my_user_id = api_get_user_id();
         $my_user_id = api_get_user_id();
     }
     }
 
 
-    $iam_a_global_admin     = api_is_global_platform_admin($my_user_id);
-    $user_is_global_admin   = api_is_global_platform_admin($admin_id_to_check);
+    $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
+    $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
 
 
     if ($iam_a_global_admin) {
     if ($iam_a_global_admin) {
         // Global admin can edit everything
         // Global admin can edit everything

+ 78 - 73
main/inc/lib/app_view.php

@@ -8,87 +8,92 @@
  */
  */
 
 
 class ViewException extends Exception {}
 class ViewException extends Exception {}
-class View {
-	
-	private $data;
-	private $template;
-	private $layout;
+class View
+{
+    private $data;
+    private $template;
+    private $layout;
     private $tool_path;
     private $tool_path;
-   
-   	/**
-   	 * Constructor, init tool path for rendering
-   	 * @param string  tool name (optional)
-   	 */
-	public function __construct($toolname = '', $template_path=null) {
-		if (!empty($toolname)) {
+
+    /**
+     * Constructor, init tool path for rendering
+     * @param string  tool name (optional)
+     */
+    public function __construct($toolname = '', $template_path=null)
+    {
+        if (!empty($toolname)) {
             if (isset($template_path)) {
             if (isset($template_path)) {
                 $path = $template_path.$toolname.'/';
                 $path = $template_path.$toolname.'/';
             } else {
             } else {
                 $path = api_get_path(SYS_CODE_PATH).$toolname.'/';
                 $path = api_get_path(SYS_CODE_PATH).$toolname.'/';
             }
             }
-			if (is_dir($path)) {
-				$this->tool_path = $path;
-			} else {
-				throw new ViewException('View::__construct() $path directory does not exist ' . $path);
-			}
-		}
-	}
-   
+            if (is_dir($path)) {
+                $this->tool_path = $path;
+            } else {
+                throw new ViewException('View::__construct() $path directory does not exist ' . $path);
+            }
+        }
+    }
+
     /**
     /**
-   	 * Set data sent from a controller 
-   	 * @param array data
-   	 */
-	public function set_data($data) {
-		if (!is_array($data)) {
-			throw new ViewException('View::set_data() $data must to be an array, you have sent a' . gettype( $data ));
-		}
-		$this->data = $data;
-	}
-   
+     * Set data sent from a controller
+     * @param array data
+     */
+    public function set_data($data)
+    {
+        if (!is_array($data)) {
+            throw new ViewException('View::set_data() $data must to be an array, you have sent a' . gettype( $data ));
+        }
+        $this->data = $data;
+    }
+
+    /**
+     * Set layout view sent from a controller
+     * @param string layout view
+     */
+    public function set_layout( $layout )
+    {
+        $this->layout = $layout;
+    }
+
+    /**
+     * Set template view sent from a controller
+     * @param string template view
+     */
+    public function set_template($template)
+    {
+        $this->template = $template;
+    }
+
     /**
     /**
-   	 * Set layout view sent from a controller 
-   	 * @param string layout view
-   	 */
-	public function set_layout( $layout ) {		
-		$this->layout = $layout;
-	}
-   
-   	/**
-   	 * Set template view sent from a controller 
-   	 * @param string template view
-   	 */
-	public function set_template($template) {		
-		$this->template = $template;
-	}
+     * Render data to the template and layout views
+     */
+    public function render()
+    {
+        $content = $this->render_template();
+        $target = $this->tool_path.$this->layout.'.php';
+        if (file_exists($target)) {
+            require_once $target;
+        } else {
+            throw new ViewException('View::render() invalid file path '.$target);
+        }
+    }
 
 
-	/**
-   	 * Render data to the template and layout views  
-   	 */
-	public function render() {
-		$content = $this->render_template();
-		$target = $this->tool_path.$this->layout.'.php';
-		if (file_exists($target)) {           
-			require_once $target;
-		} else {
-			throw new ViewException('View::render() invalid file path '.$target);
-		}
-	}
-    
     /**
     /**
-   	 * It's used into render method for rendering data in the template and layout views
-     * @return  String  Rendered template (as HTML, most of the time)   
-   	 */   
-	private function render_template() {		
-		$target = $this->tool_path.$this->template.'.php';
-		if (file_exists($target)) {           
-			ob_start();
-			@extract($this->data, EXTR_OVERWRITE); //pass the $this->data array into local scope
-			require_once $target;
-			$content = ob_get_clean();
-			return $content;
-		} else {
-			throw new ViewException('View::render_template() invalid file path '.$target);
-		}
-	}
+     * It's used into render method for rendering data in the template and layout views
+     * @return  String  Rendered template (as HTML, most of the time)
+     */
+    private function render_template()
+    {
+        $target = $this->tool_path.$this->template.'.php';
+        if (file_exists($target)) {
+            ob_start();
+            @extract($this->data, EXTR_OVERWRITE); //pass the $this->data array into local scope
+            require_once $target;
+            $content = ob_get_clean();
+            return $content;
+        } else {
+            throw new ViewException('View::render_template() invalid file path '.$target);
+        }
+    }
 }
 }
-?>

+ 29 - 21
main/inc/lib/banner.lib.php

@@ -15,8 +15,9 @@
  * @return array containing all the possible tabs
  * @return array containing all the possible tabs
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
  */
-function get_tabs() {
-    global $_course;
+function get_tabs($courseId = null)
+{
+    $_course = api_get_course_info($courseId);
 
 
     $navigation = array();
     $navigation = array();
 
 
@@ -27,7 +28,7 @@ function get_tabs() {
 
 
     // My Courses
     // My Courses
 
 
-    if(api_is_allowed_to_create_course()) {
+    if (api_is_allowed_to_create_course()) {
         // Link to my courses for teachers
         // Link to my courses for teachers
         $navigation['mycourses']['url'] = api_get_path(WEB_PATH).'user_portal.php?nosession=true';
         $navigation['mycourses']['url'] = api_get_path(WEB_PATH).'user_portal.php?nosession=true';
     } else {
     } else {
@@ -48,17 +49,17 @@ function get_tabs() {
 
 
 	// Gradebook
 	// Gradebook
 	if (api_get_setting('gradebook_enable') == 'true') {
 	if (api_get_setting('gradebook_enable') == 'true') {
-            $navigation['mygradebook']['url'] = api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php'.(!empty($_course['path']) ? '?coursePath='.$_course['path'].'&amp;courseCode='.$_course['official_code'] : '' );
-            $navigation['mygradebook']['title'] = get_lang('MyGradebook');
-            $navigation['mygradebook']['key'] = 'gradebook';
+        $navigation['mygradebook']['url'] = api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php'.(!empty($_course['path']) ? '?coursePath='.$_course['path'].'&amp;courseCode='.$_course['official_code'] : '' );
+        $navigation['mygradebook']['title'] = get_lang('MyGradebook');
+        $navigation['mygradebook']['key'] = 'gradebook';
 	}
 	}
 
 
 	// Reporting
 	// Reporting
 	if (api_is_allowed_to_create_course() || api_is_drh() || api_is_session_admin()) {
 	if (api_is_allowed_to_create_course() || api_is_drh() || api_is_session_admin()) {
-            // Link to my space
-            $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH).'mySpace/'.(api_is_drh()?'session.php':'');
-            $navigation['session_my_space']['title'] = get_lang('MySpace');
-            $navigation['session_my_space']['key'] = 'my-space';
+        // Link to my space
+        $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH).'mySpace/'.(api_is_drh()?'session.php':'');
+        $navigation['session_my_space']['title'] = get_lang('MySpace');
+        $navigation['session_my_space']['key'] = 'my-space';
     } else if (api_is_student_boss()) {
     } else if (api_is_student_boss()) {
         $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH) . 'mySpace/student.php';
         $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH) . 'mySpace/student.php';
         $navigation['session_my_space']['title'] = get_lang('MySpace');
         $navigation['session_my_space']['title'] = get_lang('MySpace');
@@ -74,22 +75,22 @@ function get_tabs() {
                 $navigation['session_my_progress']['url'] .= 'auth/my_progress.php';
                 $navigation['session_my_progress']['url'] .= 'auth/my_progress.php';
         }
         }
 
 
-            $navigation['session_my_progress']['title'] = get_lang('MyProgress');
-            $navigation['session_my_progress']['key'] = 'my-progress';
+        $navigation['session_my_progress']['title'] = get_lang('MyProgress');
+        $navigation['session_my_progress']['key'] = 'my-progress';
     }
     }
 
 
 	// Social
 	// Social
 	if (api_get_setting('allow_social_tool')=='true') {
 	if (api_get_setting('allow_social_tool')=='true') {
-            $navigation['social']['url'] = api_get_path(WEB_CODE_PATH).'social/home.php';
-            $navigation['social']['title'] = get_lang('SocialNetwork');
-            $navigation['social']['key'] = 'social-network';
+        $navigation['social']['url'] = api_get_path(WEB_CODE_PATH).'social/home.php';
+        $navigation['social']['title'] = get_lang('SocialNetwork');
+        $navigation['social']['key'] = 'social-network';
 	}
 	}
 
 
 	// Dashboard
 	// Dashboard
 	if (api_is_platform_admin() || api_is_drh() || api_is_session_admin()) {
 	if (api_is_platform_admin() || api_is_drh() || api_is_session_admin()) {
-            $navigation['dashboard']['url'] = api_get_path(WEB_CODE_PATH).'dashboard/index.php';
-            $navigation['dashboard']['title'] = get_lang('Dashboard');
-            $navigation['dashboard']['key'] = 'dashboard';
+        $navigation['dashboard']['url'] = api_get_path(WEB_CODE_PATH).'dashboard/index.php';
+        $navigation['dashboard']['title'] = get_lang('Dashboard');
+        $navigation['dashboard']['key'] = 'dashboard';
 	}
 	}
 
 
 	// Reports
 	// Reports
@@ -121,6 +122,7 @@ function get_tabs() {
         $navigation['platform_admin']['title'] = get_lang('PlatformAdmin');
         $navigation['platform_admin']['title'] = get_lang('PlatformAdmin');
         $navigation['platform_admin']['key'] = 'admin';
         $navigation['platform_admin']['key'] = 'admin';
 	}
 	}
+
 	return $navigation;
 	return $navigation;
 }
 }
 
 
@@ -129,7 +131,8 @@ function get_tabs() {
  *
  *
  * @return array
  * @return array
  */
  */
-function getCustomTabs() {
+function getCustomTabs()
+{
     $tableSettingsCurrent = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
     $tableSettingsCurrent = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
     $sql = "SELECT * FROM $tableSettingsCurrent
     $sql = "SELECT * FROM $tableSettingsCurrent
         WHERE variable = 'show_tabs' AND
         WHERE variable = 'show_tabs' AND
@@ -144,7 +147,8 @@ function getCustomTabs() {
     return $customTabs;
     return $customTabs;
 }
 }
 
 
-function return_logo($theme) {
+function return_logo($theme)
+{
     $_course = api_get_course_info();
     $_course = api_get_course_info();
     $html = '';
     $html = '';
     $logo = api_get_path(SYS_CSS_PATH).'themes/'.$theme.'/images/header-logo.png';
     $logo = api_get_path(SYS_CSS_PATH).'themes/'.$theme.'/images/header-logo.png';
@@ -369,7 +373,11 @@ function return_navigation_array()
         }
         }
     }
     }
 
 
-    return array('menu_navigation' => $menu_navigation, 'navigation' => $navigation, 'possible_tabs' => $possible_tabs);
+    return array(
+        'menu_navigation' => $menu_navigation,
+        'navigation' => $navigation,
+        'possible_tabs' => $possible_tabs,
+    );
 }
 }
 
 
 function return_menu()
 function return_menu()

+ 13 - 4
main/inc/lib/career.lib.php

@@ -30,7 +30,12 @@ class Career extends Model
      */
      */
     public function get_count()
     public function get_count()
     {
     {
-        $row = Database::select('count(*) as count', $this->table, array(),'first');
+        $row = Database::select(
+            'count(*) as count',
+            $this->table,
+            array(),
+            'first'
+        );
         return $row['count'];
         return $row['count'];
     }
     }
 
 
@@ -40,7 +45,11 @@ class Career extends Model
      */
      */
     public function get_all($where_conditions = array())
     public function get_all($where_conditions = array())
     {
     {
-        return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
+        return Database::select(
+            '*',
+            $this->table,
+            array('where' => $where_conditions, 'order' => 'name ASC')
+        );
     }
     }
 
 
     /**
     /**
@@ -85,8 +94,8 @@ class Career extends Model
     /**
     /**
      * Returns a Form validator Obj
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @todo the form should be auto generated
-     * @param   string  url
-     * @param   string  action add, edit
+     * @param   string  $url
+     * @param   string  $action add, edit
      * @return  obj     form validator obj
      * @return  obj     form validator obj
      */
      */
     public function return_form($url, $action)
     public function return_form($url, $action)

+ 7 - 4
main/inc/lib/course.lib.php

@@ -2468,7 +2468,8 @@ class CourseManager
      * Get list of courses for a given user
      * Get list of courses for a given user
      * @param int $user_id
      * @param int $user_id
      * @param boolean $include_sessions Whether to include courses from session or not
      * @param boolean $include_sessions Whether to include courses from session or not
-     * @param boolean $adminGetsAllCourses If the user is platform admin, whether he gets all the courses or just his. Note: This does *not* include all sessions
+     * @param boolean $adminGetsAllCourses If the user is platform admin,
+     * whether he gets all the courses or just his. Note: This does *not* include all sessions
      * @return array    List of codes and db name
      * @return array    List of codes and db name
      * @author isaac flores paz
      * @author isaac flores paz
      */
      */
@@ -2534,7 +2535,8 @@ class CourseManager
 
 
         if ($include_sessions === true) {
         if ($include_sessions === true) {
             $sql = "SELECT DISTINCT(c.code), c.id as real_id
             $sql = "SELECT DISTINCT(c.code), c.id as real_id
-                    FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " s, " . Database::get_main_table(TABLE_MAIN_COURSE) . " c
+                    FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " s,
+                    " . Database::get_main_table(TABLE_MAIN_COURSE) . " c
                     WHERE user_id = $user_id AND s.c_id = c.id";
                     WHERE user_id = $user_id AND s.c_id = c.id";
             $r = Database::query($sql);
             $r = Database::query($sql);
             while ($row = Database::fetch_array($r, 'ASSOC')) {
             while ($row = Database::fetch_array($r, 'ASSOC')) {
@@ -4510,7 +4512,7 @@ class CourseManager
                 WHERE
                 WHERE
                     u.access_url_id = " . api_get_current_access_url_id() . " AND
                     u.access_url_id = " . api_get_current_access_url_id() . " AND
                     login_course_date <= '$now' AND
                     login_course_date <= '$now' AND
-                    login_course_date > DATE_SUB(now(), INTERVAL $days DAY) AND
+                    login_course_date > DATE_SUB('$now', INTERVAL $days DAY) AND
                     visibility <> '" . COURSE_VISIBILITY_CLOSED . "' AND visibility <> '" . COURSE_VISIBILITY_HIDDEN . "'
                     visibility <> '" . COURSE_VISIBILITY_CLOSED . "' AND visibility <> '" . COURSE_VISIBILITY_HIDDEN . "'
                 GROUP BY a.c_id
                 GROUP BY a.c_id
                 ORDER BY course_count DESC
                 ORDER BY course_count DESC
@@ -4829,7 +4831,7 @@ class CourseManager
             }
             }
 
 
             $sql = 'DELETE FROM ' . $course_user_table . '
             $sql = 'DELETE FROM ' . $course_user_table . '
-                    WHERE c_id ="' . $courseId . '" AND status="1"' . $cond;
+                    WHERE c_id ="' . $courseId . '" AND status="1" AND relation_type = 0 ' . $cond;
             Database::query($sql);
             Database::query($sql);
         }
         }
 
 
@@ -4850,6 +4852,7 @@ class CourseManager
                             status = '1',
                             status = '1',
                             is_tutor = '0',
                             is_tutor = '0',
                             sort = '0',
                             sort = '0',
+                            relation_type = '0',
                             user_course_cat='0'";
                             user_course_cat='0'";
                 }
                 }
                 Database::query($sql);
                 Database::query($sql);

+ 1 - 0
main/inc/lib/course_description.lib.php

@@ -1,5 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  * This file contains a class used like library provides functions for
  * This file contains a class used like library provides functions for
  * course description tool. It's also used like model to
  * course description tool. It's also used like model to

+ 3 - 2
main/inc/lib/course_home.lib.php

@@ -12,9 +12,10 @@ class CourseHome
     /**
     /**
      * Gets the html content to show in the 3 column view
      * Gets the html content to show in the 3 column view
      */
      */
-    public static function show_tool_3column($cat)
+    public static function show_tool_3column($cat, $userId = null)
     {
     {
-        global $_user;
+        $_user = api_get_user_info($userId);
+
         $TBL_ACCUEIL = Database :: get_course_table(TABLE_TOOL_LIST);
         $TBL_ACCUEIL = Database :: get_course_table(TABLE_TOOL_LIST);
         $TABLE_TOOLS = Database :: get_main_table(TABLE_MAIN_COURSE_MODULE);
         $TABLE_TOOLS = Database :: get_main_table(TABLE_MAIN_COURSE_MODULE);
 
 

+ 25 - 13
main/inc/lib/course_request.lib.php

@@ -31,7 +31,11 @@ class CourseRequestManager
         }
         }
         $table_course_request = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
         $table_course_request = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
         $wanted_course_code = Database::escape_string($wanted_course_code);
         $wanted_course_code = Database::escape_string($wanted_course_code);
-        $sql = sprintf('SELECT COUNT(id) AS number FROM %s WHERE visual_code = "%s"', $table_course_request, $wanted_course_code);
+        $sql = sprintf(
+            'SELECT COUNT(id) AS number FROM %s WHERE visual_code = "%s"',
+            $table_course_request,
+            $wanted_course_code
+        );
         $result = Database::fetch_array(Database::query($sql));
         $result = Database::fetch_array(Database::query($sql));
         return $result['number'] > 0;
         return $result['number'] > 0;
     }
     }
@@ -442,13 +446,13 @@ class CourseRequestManager
         // Create the requested course
         // Create the requested course
         $params = array();
         $params = array();
 
 
-        $params['title']                = $course_request_info['title'];
-        $params['course_category']        = $course_request_info['category_code'];
-        $params['course_language']      = $course_request_info['course_language'];
-        $params['exemplary_content']    = intval($course_request_info['exemplary_content']) > 0;
-        $params['wanted_code']          = $course_request_info['code'];
-        $params['user_id']              = $course_request_info['user_id'];
-        $params['tutor_name']           = api_get_person_name($user_info['firstname'], $user_info['lastname']);
+        $params['title'] = $course_request_info['title'];
+        $params['course_category'] = $course_request_info['category_code'];
+        $params['course_language'] = $course_request_info['course_language'];
+        $params['exemplary_content'] = intval($course_request_info['exemplary_content']) > 0;
+        $params['wanted_code'] = $course_request_info['code'];
+        $params['user_id'] = $course_request_info['user_id'];
+        $params['tutor_name'] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
 
 
         $course_info = CourseManager::create_course($params);
         $course_info = CourseManager::create_course($params);
         if (!empty($course_info)) {
         if (!empty($course_info)) {
@@ -532,7 +536,9 @@ class CourseRequestManager
 
 
         $code = $course_request_info['code'];
         $code = $course_request_info['code'];
 
 
-        $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." SET status = ".COURSE_REQUEST_REJECTED." WHERE id = ".$id;
+        $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)."
+                SET status = ".COURSE_REQUEST_REJECTED."
+                WHERE id = ".$id;
         if (Database::query($sql) === false) {
         if (Database::query($sql) === false) {
             return false;
             return false;
         }
         }
@@ -625,13 +631,18 @@ class CourseRequestManager
         $email_body .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language).",\n\n";
         $email_body .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language).",\n\n";
         $email_body .= sprintf(get_lang('CourseRequestAskInfoEmailText', null, $email_language), $code)."\n";
         $email_body .= sprintf(get_lang('CourseRequestAskInfoEmailText', null, $email_language), $code)."\n";
         $email_body .= "\n".get_lang('Formula', null, $email_language)."\n";
         $email_body .= "\n".get_lang('Formula', null, $email_language)."\n";
-        $email_body .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language)."\n";
+        $email_body .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n";
         $email_body .= get_lang('Manager', null, $email_language).' '.api_get_setting('siteName')."\n";
         $email_body .= get_lang('Manager', null, $email_language).' '.api_get_setting('siteName')."\n";
         $email_body .= get_lang('Phone', null, $email_language).': '.api_get_setting('administratorTelephone')."\n";
         $email_body .= get_lang('Phone', null, $email_language).': '.api_get_setting('administratorTelephone')."\n";
-        $email_body .= get_lang('Email', null, $email_language).': '.api_get_setting('emailAdministrator', null, $email_language)."\n";
+        $email_body .= get_lang('Email', null, $email_language).': '.api_get_setting('emailAdministrator')."\n";
         $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
         $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
 
 
-        $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+        $sender_name = api_get_person_name(
+            api_get_setting('administratorName'),
+            api_get_setting('administratorSurname'),
+            null,
+            PERSON_NAME_EMAIL_ADDRESS
+        );
         $sender_email = api_get_setting('emailAdministrator');
         $sender_email = api_get_setting('emailAdministrator');
         $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
         $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
         $recipient_email = $user_info['mail'];
         $recipient_email = $user_info['mail'];
@@ -661,7 +672,8 @@ class CourseRequestManager
         }
         }
 
 
         // Marking the fact that additional information about the request has been asked.
         // Marking the fact that additional information about the request has been asked.
-        $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." SET info = 1 WHERE id = ".$id;
+        $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)."
+                SET info = 1 WHERE id = ".$id;
         $result = Database::query($sql) !== false;
         $result = Database::query($sql) !== false;
 
 
         return $result;
         return $result;

+ 9 - 7
main/inc/lib/custom_pages.class.php

@@ -1,8 +1,9 @@
 <?php
 <?php
+/* For licensing terms, see /license.txt */
 
 
 /**
 /**
  *  Used to implement the loading of custom pages
  *  Used to implement the loading of custom pages
- * 
+ *
  * @license see /license.txt
  * @license see /license.txt
  * @author 2011, Jean-Karim Bockstael <jeankarim@cblue.be>
  * @author 2011, Jean-Karim Bockstael <jeankarim@cblue.be>
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
@@ -27,7 +28,7 @@ class CustomPages
 
 
     /**
     /**
      * Returns the path to a custom page.
      * Returns the path to a custom page.
-     * 
+     *
      * @param string $name
      * @param string $name
      * @return string
      * @return string
      */
      */
@@ -38,7 +39,7 @@ class CustomPages
 
 
     /**
     /**
      * If enabled display a custom page and exist. Otherwise log error and returns.
      * If enabled display a custom page and exist. Otherwise log error and returns.
-     * 
+     *
      * @param string $page_name
      * @param string $page_name
      * @param array $content used to path data to the custom page
      * @param array $content used to path data to the custom page
      */
      */
@@ -58,10 +59,10 @@ class CustomPages
     }
     }
 
 
     /**
     /**
-     * Does not look like this function is being used is being used 
-     * 
+     * Does not look like this function is being used is being used
+     *
      * @param type $url_id
      * @param type $url_id
-     * @return string 
+     * @return string
      */
      */
     public static function getURLImages($url_id = null)
     public static function getURLImages($url_id = null)
     {
     {
@@ -76,7 +77,8 @@ class CustomPages
                 $images[] = api_get_path(WEB_PATH) . 'custompages/url-images/' . $url_id . '_url_image_' . $img_id . '.png';
                 $images[] = api_get_path(WEB_PATH) . 'custompages/url-images/' . $url_id . '_url_image_' . $img_id . '.png';
             }
             }
         }
         }
+
         return $images;
         return $images;
     }
     }
 
 
-}
+}

+ 1 - 0
main/inc/lib/dashboard.lib.php

@@ -1,5 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  * This file contains a class used like library, provides functions for dashboard.
  * This file contains a class used like library, provides functions for dashboard.
  * @author Christian Fasanando <christian1827@gmail.com>
  * @author Christian Fasanando <christian1827@gmail.com>

+ 1 - 0
main/inc/lib/database.constants.inc.php

@@ -1,5 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  *	This is the database constants definition for Chamilo
  *	This is the database constants definition for Chamilo
  *  This file is called by database.lib.php
  *  This file is called by database.lib.php

+ 1 - 2
main/inc/lib/database.lib.php

@@ -323,8 +323,6 @@ class Database
     {
     {
         $connection = self::getManager()->getConnection();
         $connection = self::getManager()->getConnection();
 
 
-        $result = false;
-
         if (api_get_setting('server_type') == 'test') {
         if (api_get_setting('server_type') == 'test') {
             $result = $connection->executeQuery($query);
             $result = $connection->executeQuery($query);
         } else {
         } else {
@@ -332,6 +330,7 @@ class Database
                 $result = $connection->executeQuery($query);
                 $result = $connection->executeQuery($query);
             } catch (Exception $e) {
             } catch (Exception $e) {
                 api_not_allowed(false, get_lang('GeneralError'));
                 api_not_allowed(false, get_lang('GeneralError'));
+                //error_log($e->getMessage());
                 exit;
                 exit;
             }
             }
         }
         }

+ 1 - 0
main/inc/lib/database.mysqli.lib.php

@@ -1,3 +1,4 @@
 <?php
 <?php
 
 
 // This file is needed to avoid the double Database class definition in 1.9.x
 // This file is needed to avoid the double Database class definition in 1.9.x
+// Don't remove.

+ 47 - 13
main/inc/lib/diagnoser.lib.php

@@ -1,5 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
  * Class Diagnoser
  * Class Diagnoser
  * Class that is responsible for generating diagnostic information about the system
  * Class that is responsible for generating diagnostic information about the system
@@ -189,7 +190,7 @@ class Diagnoser
         $setting = ini_get('upload_max_filesize');
         $setting = ini_get('upload_max_filesize');
         $req_setting = '>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M';
         $req_setting = '>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M';
         $status = self :: STATUS_ERROR;
         $status = self :: STATUS_ERROR;
-        if ((float)$setting >= REQUIRED_UPLOAD_MAX_FILESIZE)
+        if ((float)$setting >= REQUIRED_MIN_UPLOAD_MAX_FILESIZE)
             $status = self :: STATUS_OK;
             $status = self :: STATUS_OK;
         $array[] = $this->build_setting($status, '[INI]', 'upload_max_filesize', 'http://www.php.net/manual/en/ini.core.php#ini.upload_max_filesize', $setting, $req_setting, null, get_lang('UploadMaxFilesizeInfo'));
         $array[] = $this->build_setting($status, '[INI]', 'upload_max_filesize', 'http://www.php.net/manual/en/ini.core.php#ini.upload_max_filesize', $setting, $req_setting, null, get_lang('UploadMaxFilesizeInfo'));
 
 
@@ -208,21 +209,54 @@ class Diagnoser
         $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
         $status = $setting == $req_setting ? self :: STATUS_OK : self :: STATUS_WARNING;
         $array[] = $this->build_setting($status, '[INI]', 'browscap', 'http://www.php.net/manual/en/misc.configuration.php#ini.browscap', $setting, $req_setting, 'on_off', get_lang('BrowscapInfo'));
         $array[] = $this->build_setting($status, '[INI]', 'browscap', 'http://www.php.net/manual/en/misc.configuration.php#ini.browscap', $setting, $req_setting, 'on_off', get_lang('BrowscapInfo'));
 
 
-        //Extensions
-        $extensions = array('gd' 		=> array('link'=>'http://www.php.net/gd', 		'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'mysql' 	=> array('link'=>'http://www.php.net/mysql', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'pcre' 		=> array('link'=>'http://www.php.net/pcre', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'session' 	=> array('link'=>'http://www.php.net/session', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'standard' 	=> array('link'=>'http://www.php.net/spl', 		'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'zlib' 		=> array('link'=>'http://www.php.net/zlib', 	'expected' => 1, 'comment' => get_lang('ExtensionMustBeLoaded')),
-        					'xsl' 		=> array('link'=>'http://be2.php.net/xsl', 		'expected' => 2, 'comment' => get_lang('ExtensionShouldBeLoaded')),
-        					'curl' 		=> array('link'=>'http://www.php.net/curl', 	'expected' => 2, 'comment' => get_lang('ExtensionShouldBeLoaded')),
+        // Extensions
+        $extensions = array(
+            'gd' => array(
+                'link' => 'http://www.php.net/gd',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'mysql' => array(
+                'link' => 'http://www.php.net/mysql',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'pcre' => array(
+                'link' => 'http://www.php.net/pcre',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'session' => array(
+                'link' => 'http://www.php.net/session',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'standard' => array(
+                'link' => 'http://www.php.net/spl',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'zlib' => array(
+                'link' => 'http://www.php.net/zlib',
+                'expected' => 1,
+                'comment' => get_lang('ExtensionMustBeLoaded'),
+            ),
+            'xsl' => array(
+                'link' => 'http://be2.php.net/xsl',
+                'expected' => 2,
+                'comment' => get_lang('ExtensionShouldBeLoaded'),
+            ),
+            'curl' => array(
+                'link' => 'http://www.php.net/curl',
+                'expected' => 2,
+                'comment' => get_lang('ExtensionShouldBeLoaded'),
+            ),
         );
         );
 
 
         foreach ($extensions as $extension => $data) {
         foreach ($extensions as $extension => $data) {
-        	$url  	  		= $data['link'];
-        	$expected_value = $data['expected'];
-        	$comment 		= $data['comment'];
+            $url = $data['link'];
+            $expected_value = $data['expected'];
+            $comment = $data['comment'];
 
 
             $loaded = extension_loaded($extension);
             $loaded = extension_loaded($extension);
             $status = $loaded ? self :: STATUS_OK : self :: STATUS_ERROR;
             $status = $loaded ? self :: STATUS_OK : self :: STATUS_ERROR;

+ 0 - 1
main/inc/lib/display.lib.php

@@ -398,7 +398,6 @@ class Display
         $column_order = array(),
         $column_order = array(),
         $form_actions = array()
         $form_actions = array()
     ) {
     ) {
-        global $origin;
         $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
         $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
         $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
         $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
 
 

+ 39 - 33
main/inc/lib/event_email_template.class.php

@@ -5,33 +5,37 @@
 *	Include/require it in your code to use its features.
 *	Include/require it in your code to use its features.
 *	@package chamilo.library
 *	@package chamilo.library
 */
 */
-/**
- * Code
- */
-define ('EVENT_EMAIL_TEMPLATE_ACTIVE',  1);
-define ('EVENT_EMAIL_TEMPLATE_INACTIVE',0);
 
 
 /**
 /**
- * @package chamilo.library
+ * Class EventEmailTemplate
  */
  */
-class EventEmailTemplate extends Model {
-
-    var $table;
-    var $columns = array('id', 'message','subject','event_type_name','activated');
+class EventEmailTemplate extends Model
+{
+    public $table;
+    public $columns = array('id', 'message','subject','event_type_name','activated');
 
 
-	public function __construct() {
+    /**
+     * Constructor
+     */
+	public function __construct()
+    {
         $this->table =  Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE);
         $this->table =  Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE);
 	}
 	}
 
 
-    public function get_all($where_conditions = array()) {
-        return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
+    public function get_all($where_conditions = array())
+    {
+        return Database::select(
+            '*',
+            $this->table,
+            array('where' => $where_conditions, 'order' => 'name ASC')
+        );
     }
     }
 
 
-
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
-	public function display() {
+	public function display()
+    {
 		// action links
 		// action links
 		$content = Display::actions(array(
 		$content = Display::actions(array(
                 array(
                 array(
@@ -44,8 +48,12 @@ class EventEmailTemplate extends Model {
         return $content;
         return $content;
 	}
 	}
 
 
-    public function get_status_list() {
-        return array(EVENT_EMAIL_TEMPLATE_ACTIVE => get_lang('Enabled'), EVENT_EMAIL_TEMPLATE_INACTIVE=> get_lang('Disabled'));
+    public function get_status_list()
+    {
+        return array(
+            EVENT_EMAIL_TEMPLATE_ACTIVE => get_lang('Enabled'),
+            EVENT_EMAIL_TEMPLATE_INACTIVE => get_lang('Disabled'),
+        );
     }
     }
 
 
     /**
     /**
@@ -69,7 +77,17 @@ class EventEmailTemplate extends Model {
         $form->addElement('hidden', 'id', $id);
         $form->addElement('hidden', 'id', $id);
 
 
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
-        $form->addHtmlEditor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+        $form->addHtmlEditor(
+            'description',
+            get_lang('Description'),
+            false,
+            false,
+            array(
+                'ToolbarSet' => 'careers',
+                'Width' => '100%',
+                'Height' => '250',
+            )
+        );
 	    $status_list = $this->get_status_list();
 	    $status_list = $this->get_status_list();
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
         if ($action == 'edit') {
@@ -99,22 +117,10 @@ class EventEmailTemplate extends Model {
 		return $form;
 		return $form;
     }
     }
 
 
-      public function get_count() {
+    public function get_count()
+    {
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         $row = Database::select('count(*) as count', $this->table, array(),'first');
-        return $row['count'];
-    }
 
 
-    /*
-    public function save($params) {
-	    $id = parent::save($params);
-	    if (!empty($id)) {
-	    	event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
-   		}
-   		return $id;
+        return $row['count'];
     }
     }
-
-    public function delete($id) {
-	    parent::delete($id);
-	    event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
-    } */
 }
 }

+ 64 - 71
main/inc/lib/events.lib.php

@@ -151,7 +151,8 @@ class Event
             return false;
             return false;
         }
         }
         $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
         $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
-        $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
+        //for "what's new" notification
+        $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 
 
         $_course = api_get_course_info();
         $_course = api_get_course_info();
         $courseId = api_get_course_int_id();
         $courseId = api_get_course_int_id();
@@ -180,7 +181,7 @@ class Event
                          )
                          )
                     VALUES
                     VALUES
                         (".$user_id.",".// Don't add ' ' around value, it's already done.
                         (".$user_id.",".// Don't add ' ' around value, it's already done.
-                "'".$courseId."' ,
+                        "'".$courseId."' ,
                         '".$tool."',
                         '".$tool."',
                         '".$reallyNow."',
                         '".$reallyNow."',
                         '".$id_session."')";
                         '".$id_session."')";
@@ -849,8 +850,10 @@ class Event
     {
     {
         $exe_id = intval($exe_id);
         $exe_id = intval($exe_id);
         $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-        $sql_track_attempt = 'SELECT max(tms) as last_attempt_date FROM '.$track_attempts.' WHERE exe_id='.$exe_id;
-        $rs_last_attempt = Database::query($sql_track_attempt);
+        $sql = 'SELECT max(tms) as last_attempt_date
+                FROM '.$track_attempts.'
+                WHERE exe_id='.$exe_id;
+        $rs_last_attempt = Database::query($sql);
         $row_last_attempt = Database::fetch_array($rs_last_attempt);
         $row_last_attempt = Database::fetch_array($rs_last_attempt);
         $last_attempt_date = $row_last_attempt['last_attempt_date']; //Get the date of last attempt
         $last_attempt_date = $row_last_attempt['last_attempt_date']; //Get the date of last attempt
 
 
@@ -896,7 +899,9 @@ class Event
         $lp_item_id = intval($lp_item_id);
         $lp_item_id = intval($lp_item_id);
         $lp_item_view_id = intval($lp_item_view_id);
         $lp_item_view_id = intval($lp_item_view_id);
 
 
-        $sql = "SELECT count(*) as count FROM $stat_table WHERE
+        $sql = "SELECT count(*) as count
+                FROM $stat_table
+                WHERE
                     exe_exo_id 				= $exerciseId AND
                     exe_exo_id 				= $exerciseId AND
                     exe_user_id 			= $user_id AND
                     exe_user_id 			= $user_id AND
                     status 			   	   != 'incomplete' AND
                     status 			   	   != 'incomplete' AND
@@ -931,7 +936,9 @@ class Event
         $lp_item_id = intval($lp_item_id);
         $lp_item_id = intval($lp_item_id);
         //$lp_item_view_id = intval($lp_item_view_id);
         //$lp_item_view_id = intval($lp_item_view_id);
 
 
-        $sql = "SELECT count(*) as count FROM $stat_table WHERE
+        $sql = "SELECT count(*) as count
+                FROM $stat_table
+                WHERE
                     exe_exo_id 			= $exerciseId AND
                     exe_exo_id 			= $exerciseId AND
                     exe_user_id 		= $user_id AND
                     exe_user_id 		= $user_id AND
                     status 				!= 'incomplete' AND
                     status 				!= 'incomplete' AND
@@ -995,7 +1002,8 @@ class Event
             $view = Database::fetch_array($result, 'ASSOC');
             $view = Database::fetch_array($result, 'ASSOC');
             $lp_view_id = $view['id'];
             $lp_view_id = $view['id'];
 
 
-            $sql = "DELETE FROM $lp_item_view_table WHERE c_id = $course_id AND lp_view_id = $lp_view_id ";
+            $sql = "DELETE FROM $lp_item_view_table
+                    WHERE c_id = $course_id AND lp_view_id = $lp_view_id ";
             Database::query($sql);
             Database::query($sql);
 
 
             $sql = "DELETE FROM $lpInteraction
             $sql = "DELETE FROM $lpInteraction
@@ -1096,8 +1104,13 @@ class Event
      * @return  array   with the results
      * @return  array   with the results
      *
      *
      */
      */
-    public static function get_all_exercise_results($exercise_id, $courseId, $session_id = 0, $load_question_list = true, $user_id = null)
-    {
+    public static function get_all_exercise_results(
+        $exercise_id,
+        $courseId,
+        $session_id = 0,
+        $load_question_list = true,
+        $user_id = null
+    ) {
         $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
         $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
         $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
         $courseId = intval($courseId);
         $courseId = intval($courseId);
@@ -1124,7 +1137,8 @@ class Event
         while ($row = Database::fetch_array($res, 'ASSOC')) {
         while ($row = Database::fetch_array($res, 'ASSOC')) {
             $list[$row['exe_id']] = $row;
             $list[$row['exe_id']] = $row;
             if ($load_question_list) {
             if ($load_question_list) {
-                $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT WHERE exe_id = {$row['exe_id']}";
+                $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT
+                        WHERE exe_id = {$row['exe_id']}";
                 $res_question = Database::query($sql);
                 $res_question = Database::query($sql);
                 while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
                 while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
                     $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
                     $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
@@ -1194,12 +1208,13 @@ class Event
         $user_id = intval($user_id);
         $user_id = intval($user_id);
 
 
         $sql = "SELECT * FROM $table_track_exercises
         $sql = "SELECT * FROM $table_track_exercises
-                WHERE status = '' AND
-                        exe_user_id = $user_id AND
-                        c_id = '$courseId' AND
-                        session_id = $session_id AND
-                        orig_lp_id = 0 AND
-                        orig_lp_item_id = 0
+                WHERE
+                    status = '' AND
+                    exe_user_id = $user_id AND
+                    c_id = '$courseId' AND
+                    session_id = $session_id AND
+                    orig_lp_id = 0 AND
+                    orig_lp_item_id = 0
                 ORDER by exe_id";
                 ORDER by exe_id";
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
@@ -1233,7 +1248,8 @@ class Event
 
 
         $status = Database::escape_string($status);
         $status = Database::escape_string($status);
 
 
-        $sql = "SELECT * FROM $table_track_exercises WHERE status = '".$status."' AND exe_id = $exe_id";
+        $sql = "SELECT * FROM $table_track_exercises
+                WHERE status = '".$status."' AND exe_id = $exe_id";
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
         $list = array();
         $list = array();
@@ -1241,14 +1257,16 @@ class Event
             $row = Database::fetch_array($res, 'ASSOC');
             $row = Database::fetch_array($res, 'ASSOC');
 
 
             //Checking if this attempt was revised by a teacher
             //Checking if this attempt was revised by a teacher
-            $sql_revised = 'SELECT exe_id FROM '.$table_track_attempt_recording.' WHERE author != "" AND exe_id = '.$exe_id.' LIMIT 1';
+            $sql_revised = 'SELECT exe_id FROM '.$table_track_attempt_recording.'
+                            WHERE author != "" AND exe_id = '.$exe_id.' LIMIT 1';
             $res_revised = Database::query($sql_revised);
             $res_revised = Database::query($sql_revised);
             $row['attempt_revised'] = 0;
             $row['attempt_revised'] = 0;
             if (Database::num_rows($res_revised) > 0) {
             if (Database::num_rows($res_revised) > 0) {
                 $row['attempt_revised'] = 1;
                 $row['attempt_revised'] = 1;
             }
             }
             $list[$exe_id] = $row;
             $list[$exe_id] = $row;
-            $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = $exe_id ORDER BY tms ASC";
+            $sql = "SELECT * FROM $table_track_attempt
+                    WHERE exe_id = $exe_id ORDER BY tms ASC";
             $res_question = Database::query($sql);
             $res_question = Database::query($sql);
             while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
             while ($row_q = Database::fetch_array($res_question, 'ASSOC')) {
                 $list[$exe_id]['question_list'][$row_q['question_id']] = $row_q;
                 $list[$exe_id]['question_list'][$row_q['question_id']] = $row_q;
@@ -1372,12 +1390,13 @@ class Event
         $session_id = intval($session_id);
         $session_id = intval($session_id);
 
 
         $sql = "SELECT * FROM $table_track_exercises
         $sql = "SELECT * FROM $table_track_exercises
-                WHERE   status = '' AND
-                        c_id = $courseId AND
-                        exe_exo_id = '$exercise_id' AND
-                        session_id = $session_id AND
-                        orig_lp_id = 0 AND
-                        orig_lp_item_id = 0
+                WHERE
+                    status = '' AND
+                    c_id = $courseId AND
+                    exe_exo_id = '$exercise_id' AND
+                    session_id = $session_id AND
+                    orig_lp_id = 0 AND
+                    orig_lp_item_id = 0
                 ORDER BY exe_id";
                 ORDER BY exe_id";
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
@@ -1426,14 +1445,15 @@ class Event
         $user_id = intval($user_id);
         $user_id = intval($user_id);
 
 
         $sql = "SELECT * FROM $table_track_exercises
         $sql = "SELECT * FROM $table_track_exercises
-                WHERE   status = ''  AND
-                        c_id = '$courseId' AND
-                        exe_exo_id = '$exercise_id' AND
-                        session_id = $session_id  AND
-                        exe_user_id = $user_id AND
-                        orig_lp_id =0 AND
-                        orig_lp_item_id = 0
-                        ORDER BY exe_id";
+                WHERE
+                    status = ''  AND
+                    c_id = '$courseId' AND
+                    exe_exo_id = '$exercise_id' AND
+                    session_id = $session_id  AND
+                    exe_user_id = $user_id AND
+                    orig_lp_id =0 AND
+                    orig_lp_item_id = 0
+                ORDER BY exe_id";
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
         $list = array();
         $list = array();
@@ -1486,7 +1506,8 @@ class Event
                     orig_lp_id = 0 AND
                     orig_lp_id = 0 AND
                     marks IS NULL AND
                     marks IS NULL AND
                     status = '' AND
                     status = '' AND
-                    orig_lp_item_id = 0 ORDER BY e.exe_id";
+                    orig_lp_item_id = 0
+                ORDER BY e.exe_id";
         $res = Database::query($sql);
         $res = Database::query($sql);
         $row = Database::fetch_array($res, 'ASSOC');
         $row = Database::fetch_array($res, 'ASSOC');
 
 
@@ -1509,11 +1530,12 @@ class Event
 
 
         $sql = "SELECT DISTINCT exe_exo_id, exe_user_id
         $sql = "SELECT DISTINCT exe_exo_id, exe_user_id
                 FROM $table_track_exercises
                 FROM $table_track_exercises
-                WHERE   status = '' AND
-                        c_id = '$courseId' AND
-                        session_id = $session_id AND
-                        orig_lp_id =0 AND
-                        orig_lp_item_id = 0
+                WHERE
+                    status = '' AND
+                    c_id = '$courseId' AND
+                    session_id = $session_id AND
+                    orig_lp_id =0 AND
+                    orig_lp_item_id = 0
                 ORDER BY exe_id";
                 ORDER BY exe_id";
         $res = Database::query($sql);
         $res = Database::query($sql);
         $count = 0;
         $count = 0;
@@ -1592,6 +1614,7 @@ class Event
      *
      *
      * @param int $id
      * @param int $id
      * @param int $question_id
      * @param int $question_id
+     *
      * @return string the comment
      * @return string the comment
      */
      */
     public static function get_comments($exe_id, $question_id)
     public static function get_comments($exe_id, $question_id)
@@ -1607,6 +1630,7 @@ class Event
 
 
     /**
     /**
      * @param int $exe_id
      * @param int $exe_id
+     *
      * @return array
      * @return array
      */
      */
     public static function getAllExerciseEventByExeId($exe_id)
     public static function getAllExerciseEventByExeId($exe_id)
@@ -1652,7 +1676,7 @@ class Event
                     session_id = $session_id AND
                     session_id = $session_id AND
                     question_id = $question_id ";
                     question_id = $question_id ";
         Database::query($sql);
         Database::query($sql);
-        $courseInfo = api_get_course_info_by_id($courseId);
+
         Event::addEvent(
         Event::addEvent(
             LOG_QUESTION_RESULT_DELETE,
             LOG_QUESTION_RESULT_DELETE,
             LOG_EXERCISE_ATTEMPT_QUESTION_ID,
             LOG_EXERCISE_ATTEMPT_QUESTION_ID,
@@ -1700,37 +1724,6 @@ class Event
         );
         );
     }
     }
 
 
-    /**
-     * @param $exe_id
-     * @param $objExercise
-     * @return array
-     */
-    public static function getAnsweredQuestionsFromAttempt($exe_id, $objExercise)
-    {
-        $attempt_list = self::getAllExerciseEventByExeId($exe_id);
-        $exercise_result = array();
-        if (!empty($attempt_list)) {
-            foreach ($attempt_list as $question_id => $options) {
-                foreach ($options as $item) {
-                    $question_obj = Question::read($item['question_id']);
-                    switch ($question_obj->type) {
-                        case FILL_IN_BLANKS:
-                            $item['answer'] = $objExercise->fill_in_blank_answer_to_string($item['answer']);
-                            break;
-                        case HOT_SPOT:
-                            break;
-                    }
-
-                    if ($item['answer'] != '0' && !empty($item['answer'])) {
-                        $exercise_result[] = $question_id;
-                        break;
-                    }
-                }
-            }
-        }
-        return $exercise_result;
-    }
-
     /**
     /**
      * User logs in for the first time to a course
      * User logs in for the first time to a course
      * @param int $courseId
      * @param int $courseId

+ 73 - 62
main/inc/lib/events_email.class.php

@@ -1,13 +1,11 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
+
 /**
 /**
- * Manages the email sending action when a event requires it.
- * @package chamilo.libraries.events
- */
-/**
- * EventsMail class: manages the e-mail sending action when a event requires it
+ * Class EventsMail
+ * manages the e-mail sending action when a event requires it
  */
  */
-class EventsMail 
+class EventsMail
 {
 {
 
 
     /**
     /**
@@ -15,27 +13,33 @@ class EventsMail
      *
      *
      * @param string $event_name the name of the event that was triggered
      * @param string $event_name the name of the event that was triggered
      * @param array $event_data what to put in the mail
      * @param array $event_data what to put in the mail
-     * 
+     *
      * Possible key :
      * Possible key :
      * - $event_data["about_user"] (= $user_id)
      * - $event_data["about_user"] (= $user_id)
      * - $event_data["prior_lang"]
      * - $event_data["prior_lang"]
-     * 
+     *
      * Warning :
      * Warning :
      * - $event_data["send_to"] MUST BE an array
      * - $event_data["send_to"] MUST BE an array
      */
      */
-    public static function send_mail($event_name, $event_data) 
+    public static function send_mail($event_name, $event_data)
     {
     {
         /**
         /**
          * Global explanation :
          * Global explanation :
          * 1. we get information about the user that fired the event (in $event_data["about_user"])
          * 1. we get information about the user that fired the event (in $event_data["about_user"])
          * 2. we send mail to people that are in the $event_data["send_to"]
          * 2. we send mail to people that are in the $event_data["send_to"]
-         * 2b. if a language was specified, we use that one to send the mail, else we get the user's language, if there isn't any, we get the english one
-         * 3. we do the same with the people associated to the event through the admin panel 
+         * 2b. if a language was specified, we use that one to send the mail,
+         * else we get the user's language, if there isn't any, we get the english one
+         * 3. we do the same with the people associated to the event through the admin panel
          */
          */
         global $event_config;
         global $event_config;
 
 
         // common variable for every mail sent
         // common variable for every mail sent
-        $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+        $sender_name = api_get_person_name(
+            api_get_setting('administratorName'),
+            api_get_setting('administratorSurname'),
+            null,
+            PERSON_NAME_EMAIL_ADDRESS
+        );
         $email_admin = api_get_setting('emailAdministrator');
         $email_admin = api_get_setting('emailAdministrator');
         // basic  keys
         // basic  keys
         $event_data["sitename"] = api_get_setting('siteName');
         $event_data["sitename"] = api_get_setting('siteName');
@@ -44,10 +48,10 @@ class EventsMail
         $event_data["administrator_phone"] = api_get_setting('administratorTelephone');
         $event_data["administrator_phone"] = api_get_setting('administratorTelephone');
         $event_data["administrator_email"] = api_get_setting('emailAdministrator');
         $event_data["administrator_email"] = api_get_setting('emailAdministrator');
         $event_data["portal"] = api_get_path(WEB_PATH);
         $event_data["portal"] = api_get_path(WEB_PATH);
-        
+
         // Fill the array's cells with info regarding the user that fired the event
         // Fill the array's cells with info regarding the user that fired the event
         // (for the keys in the template)
         // (for the keys in the template)
-        if ( isset($event_data["about_user"]) ) 
+        if ( isset($event_data["about_user"]) )
         {
         {
             $about_user = api_get_user_info($event_data["about_user"]);
             $about_user = api_get_user_info($event_data["about_user"]);
             $event_data["firstname"] = $about_user["firstname"];
             $event_data["firstname"] = $about_user["firstname"];
@@ -59,51 +63,51 @@ class EventsMail
         }
         }
 
 
         // First, we send the mail to people we put in the $event_data["send_to"]
         // First, we send the mail to people we put in the $event_data["send_to"]
-        if ($event_data["send_to"] != null) // the users we precised need to receive the mail 
+        if ($event_data["send_to"] != null) // the users we precised need to receive the mail
         {
         {
-            foreach ($event_data["send_to"] as $id) // for every member put in the array 
+            foreach ($event_data["send_to"] as $id) // for every member put in the array
             {
             {
                 // get user's info (to know where to send)
                 // get user's info (to know where to send)
                 $user_info = api_get_user_info($id);
                 $user_info = api_get_user_info($id);
-                
+
                 // get the language the email will be in
                 // get the language the email will be in
                 if ($event_data["prior_lang"] != null) // if $lang is not null, we use that lang
                 if ($event_data["prior_lang"] != null) // if $lang is not null, we use that lang
-                { 
+                {
                     $language = $event_data["prior_lang"];
                     $language = $event_data["prior_lang"];
                 }
                 }
                 else  // else we use the user's language
                 else  // else we use the user's language
                 {
                 {
-                    $sql = 'SELECT language FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' u 
+                    $sql = 'SELECT language FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' u
                     WHERE u.user_id = "' . $id . '"
                     WHERE u.user_id = "' . $id . '"
                     ';
                     ';
                     $language = Database::store_result(Database::query($sql), 'ASSOC');
                     $language = Database::store_result(Database::query($sql), 'ASSOC');
                     $language = $language[0]["language"];
                     $language = $language[0]["language"];
                 }
                 }
-                
+
                 // we get the message in the correct language (or in english if doesn't exist)
                 // we get the message in the correct language (or in english if doesn't exist)
                 $result = self::getMessage($event_name, $language);
                 $result = self::getMessage($event_name, $language);
                 $message = "";
                 $message = "";
                 $subject = "";
                 $subject = "";
                 self::getCorrectMessage($message, $subject, $language, $result);
                 self::getCorrectMessage($message, $subject, $language, $result);
-                
+
                 // replace the keycodes used in the message
                 // replace the keycodes used in the message
                 self::formatMessage($message, $subject, $event_config, $event_name, $event_data);
                 self::formatMessage($message, $subject, $event_config, $event_name, $event_data);
-                
-                // sending email                    
+
+                // sending email
                 $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname']);
                 $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname']);
 
 
                 // checks if there's a file we need to join to the mail
                 // checks if there's a file we need to join to the mail
                 if (isset($values["certificate_pdf_file"])) {
                 if (isset($values["certificate_pdf_file"])) {
-                    $message = str_replace("\n", "<br />", $message);                  
+                    $message = str_replace("\n", "<br />", $message);
                     api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin, null, array($values['certificate_pdf_file']));
                     api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin, null, array($values['certificate_pdf_file']));
                 } else {
                 } else {
                     api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin);
                     api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin);
                 }
                 }
-                
+
                 // If the mail only need to be send once (we know that thanks to the events.conf), we log it in the table
                 // If the mail only need to be send once (we know that thanks to the events.conf), we log it in the table
                 if ($event_config[$event_name]["sending_mail_once"])
                 if ($event_config[$event_name]["sending_mail_once"])
                 {
                 {
-                    $sql = 'INSERT INTO ' . Database::get_main_table(TABLE_EVENT_SENT) . ' 
+                    $sql = 'INSERT INTO ' . Database::get_main_table(TABLE_EVENT_SENT) . '
                         (user_from, user_to, event_type_name)
                         (user_from, user_to, event_type_name)
                         VALUES ('.$event_data["user_id"].', '.$id.' ,"'.Database::escape_string($event_name).'");
                         VALUES ('.$event_data["user_id"].', '.$id.' ,"'.Database::escape_string($event_name).'");
                         ';
                         ';
@@ -111,48 +115,48 @@ class EventsMail
                 }
                 }
             }
             }
         }
         }
-        
+
         // Second, we send to people linked to the event
         // Second, we send to people linked to the event
         // So, we get everyone
         // So, we get everyone
-        $sql = 'SELECT u.user_id, u.language, u.email, u.firstname, u.lastname FROM ' . Database::get_main_table(TABLE_EVENT_TYPE_REL_USER) . ' ue 
+        $sql = 'SELECT u.user_id, u.language, u.email, u.firstname, u.lastname FROM ' . Database::get_main_table(TABLE_EVENT_TYPE_REL_USER) . ' ue
                 INNER JOIN '.Database::get_main_table(TABLE_MAIN_USER).' u ON u.user_id = ue.user_id
                 INNER JOIN '.Database::get_main_table(TABLE_MAIN_USER).' u ON u.user_id = ue.user_id
                 WHERE event_type_name = "' . $event_name . '"';
                 WHERE event_type_name = "' . $event_name . '"';
         $result = Database::store_result(Database::query($sql), 'ASSOC');
         $result = Database::store_result(Database::query($sql), 'ASSOC');
-        
+
         foreach ($result as $key => $value) // for each of the linked users
         foreach ($result as $key => $value) // for each of the linked users
         {
         {
             // we get the language
             // we get the language
-            if ($event_data["prior_lang"] != null) // if $lang is not null, we use that lang 
-            { 
+            if ($event_data["prior_lang"] != null) // if $lang is not null, we use that lang
+            {
                 $language = $event_data["prior_lang"];
                 $language = $event_data["prior_lang"];
             }
             }
             else // else we get the user's lang
             else // else we get the user's lang
-            { 
-                $sql = 'SELECT language FROM '.Database::get_main_table(TABLE_MAIN_USER).' 
+            {
+                $sql = 'SELECT language FROM '.Database::get_main_table(TABLE_MAIN_USER).'
                     where user_id = '.$value["user_id"].' ';
                     where user_id = '.$value["user_id"].' ';
                 $result = Database::store_result(Database::query($sql), 'ASSOC');
                 $result = Database::store_result(Database::query($sql), 'ASSOC');
 
 
                 $language = $result[0]["language"];
                 $language = $result[0]["language"];
             }
             }
-            
+
             // we get the message in the correct language (or in english if doesn't exist)
             // we get the message in the correct language (or in english if doesn't exist)
             $result = self::getMessage($event_name, $language);
             $result = self::getMessage($event_name, $language);
             $message = "";
             $message = "";
             $subject = "";
             $subject = "";
             self::getCorrectMessage($message, $subject, $language, $result);
             self::getCorrectMessage($message, $subject, $language, $result);
-               
+
             // replace the keycodes used in the message
             // replace the keycodes used in the message
             self::formatMessage($message, $subject, $event_config, $event_name, $event_data);
             self::formatMessage($message, $subject, $event_config, $event_name, $event_data);
-            
+
             // we send the mail
             // we send the mail
             $recipient_name = api_get_person_name($value['firstname'], $value['lastname']);
             $recipient_name = api_get_person_name($value['firstname'], $value['lastname']);
 
 
             api_mail_html($recipient_name, $value["email"], $subject, $message, $sender_name, $email_admin);
             api_mail_html($recipient_name, $value["email"], $subject, $message, $sender_name, $email_admin);
-            
+
             // If the mail only need to be send once (we know that thanks to the events.conf, we log it in the table
             // If the mail only need to be send once (we know that thanks to the events.conf, we log it in the table
             if ($event_config[$event_name]["sending_mail_once"])
             if ($event_config[$event_name]["sending_mail_once"])
             {
             {
-                $sql = 'INSERT INTO ' . Database::get_main_table(TABLE_EVENT_SENT) . ' 
+                $sql = 'INSERT INTO ' . Database::get_main_table(TABLE_EVENT_SENT) . '
                     (user_from, user_to, event_type_name)
                     (user_from, user_to, event_type_name)
                     VALUES ('.$event_data["user_id"].', '.$value["user_id"].' , "'.Database::escape_string($event_name).'");
                     VALUES ('.$event_data["user_id"].', '.$value["user_id"].' , "'.Database::escape_string($event_name).'");
                     ';
                     ';
@@ -162,84 +166,91 @@ class EventsMail
     }
     }
 
 
     /**
     /**
-     * Checks if a message in a language exists, if the event is activated 
+     * Checks if a message in a language exists, if the event is activated
      * and if "manage event" is checked in admin panel.
      * and if "manage event" is checked in admin panel.
-     * If yes to three, we can use this class, else we still use api_mail. 
+     * If yes to three, we can use this class, else we still use api_mail.
      *
      *
      * @param string $event_name
      * @param string $event_name
-     * @return boolean 
+     * @return boolean
      */
      */
-    public static function check_if_using_class($event_name) {
+    public static function check_if_using_class($event_name)
+    {
         if (api_get_setting('activate_email_template') === 'false') {
         if (api_get_setting('activate_email_template') === 'false') {
             return false;
             return false;
         }
         }
         $current_language = api_get_interface_language();
         $current_language = api_get_interface_language();
 
 
-        $sql = 'SELECT COUNT(*) as total FROM ' . Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE) . ' em 
-        INNER JOIN ' . Database::get_main_table(TABLE_MAIN_LANGUAGE) . ' l on em.language_id = l.id
-        WHERE em.event_type_name = "' . $event_name . '" and l.dokeos_folder = "'.$current_language.'" and em.activated = 1';
+        $sql = 'SELECT COUNT(*) as total
+                FROM ' . Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE) . ' em
+                INNER JOIN ' . Database::get_main_table(TABLE_MAIN_LANGUAGE) . ' l
+                ON em.language_id = l.id
+                WHERE
+                    em.event_type_name = "' . $event_name . '" and
+                    l.dokeos_folder = "'.$current_language.'" and
+                    em.activated = 1';
 
 
-        $exists = Database::store_result(Database::query($sql), 'ASSOC');                
+        $exists = Database::store_result(Database::query($sql), 'ASSOC');
         if ($exists[0]["total"])  {
         if ($exists[0]["total"])  {
-            return true;            
+            return true;
         } else {
         } else {
             return false;
             return false;
         }
         }
     }
     }
-    
+
     /**
     /**
      * Get the record containing the good message and subject
      * Get the record containing the good message and subject
      *
      *
      * @param string $event_name
      * @param string $event_name
      * @param string $language
      * @param string $language
-     * @return array 
+     * @return array
      */
      */
     private static function getMessage($event_name, $language)
     private static function getMessage($event_name, $language)
     {
     {
-        $sql = 'SELECT message, subject, l.dokeos_folder FROM ' . Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE) . ' em 
-                    INNER JOIN ' . Database::get_main_table(TABLE_MAIN_LANGUAGE) . ' l on em.language_id = l.id
-                    WHERE em.event_type_name = "' . $event_name . '" and (l.dokeos_folder = "' . $language . '" OR l.dokeos_folder = "english") and em.message <> ""
-                    ';
+        $sql = 'SELECT message, subject, l.dokeos_folder FROM ' . Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE) . ' em
+                INNER JOIN ' . Database::get_main_table(TABLE_MAIN_LANGUAGE) . ' l
+                ON em.language_id = l.id
+                WHERE em.event_type_name = "' . $event_name . '" and (l.dokeos_folder = "' . $language . '" OR l.dokeos_folder = "english") and em.message <> ""
+                ';
         return Database::store_result(Database::query($sql), 'ASSOC');
         return Database::store_result(Database::query($sql), 'ASSOC');
     }
     }
-    
+
     /**
     /**
      * Get the correct message, meaning in the specified language or in english if previous one doesn't exist
      * Get the correct message, meaning in the specified language or in english if previous one doesn't exist
      *
      *
      * @param string $message
      * @param string $message
      * @param string $subject
      * @param string $subject
      * @param string $language
      * @param string $language
-     * @param array $result 
+     * @param array $result
      */
      */
     private static function getCorrectMessage(&$message, &$subject, $language, $result)
     private static function getCorrectMessage(&$message, &$subject, $language, $result)
     {
     {
-        foreach ($result as $msg) 
+        foreach ($result as $msg)
         {
         {
-            if ($msg["dokeos_folder"] == $language) 
+            if ($msg["dokeos_folder"] == $language)
             {
             {
                 $message = $msg["message"];
                 $message = $msg["message"];
                 $subject = $msg["subject"];
                 $subject = $msg["subject"];
                 break;
                 break;
-            } 
-            else if ($msg["dokeos_folder"] == "english") 
+            }
+            else if ($msg["dokeos_folder"] == "english")
             {
             {
                 $message = $msg["message"];
                 $message = $msg["message"];
                 $subject = $msg["subject"];
                 $subject = $msg["subject"];
             }
             }
         }
         }
     }
     }
-    
+
     /**
     /**
      * Replaces the ((key)) by the good values
      * Replaces the ((key)) by the good values
      *
      *
      * @param string $message
      * @param string $message
      * @param string $subject
      * @param string $subject
      * @param array $event_config
      * @param array $event_config
-     * @param string $event_name 
+     * @param string $event_name
      */
      */
     private static function formatMessage(&$message, &$subject, $event_config, $event_name, &$event_data)
     private static function formatMessage(&$message, &$subject, $event_config, $event_name, &$event_data)
     {
     {
-        foreach ($event_config[$event_name]["available_keyvars"] as $key => $word) 
+        foreach ($event_config[$event_name]["available_keyvars"] as $key => $word)
         {
         {
             $message = str_replace('((' . $key . '))', $event_data[$word], $message);
             $message = str_replace('((' . $key . '))', $event_data[$word], $message);
             $subject = str_replace('((' . $key . '))', $event_data[$word], $subject);
             $subject = str_replace('((' . $key . '))', $event_data[$word], $subject);

+ 10 - 7
main/inc/lib/extra_field_value.lib.php

@@ -58,10 +58,6 @@ class ExtraFieldValue extends Model
      */
      */
     public function get_count()
     public function get_count()
     {
     {
-        /*$row = Database::select('count(*) as count', $this->table, array(), 'first');
-
-        return $row['count'];*/
-
         $query = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraFieldValues')->createQueryBuilder('e');
         $query = Database::getManager()->getRepository('ChamiloCoreBundle:ExtraFieldValues')->createQueryBuilder('e');
         $query->select('count(e.id)');
         $query->select('count(e.id)');
         $query->where('e.extraFieldType = :type');
         $query->where('e.extraFieldType = :type');
@@ -626,6 +622,7 @@ class ExtraFieldValue extends Model
                     }
                     }
                 }
                 }
             }
             }
+
             return $result;
             return $result;
         } else {
         } else {
             return false;
             return false;
@@ -672,6 +669,7 @@ class ExtraFieldValue extends Model
         $result = Database::query($sql);
         $result = Database::query($sql);
         if ($result !== false && Database::num_rows($result)) {
         if ($result !== false && Database::num_rows($result)) {
             $result = Database::fetch_array($result, 'ASSOC');
             $result = Database::fetch_array($result, 'ASSOC');
+
             return $result;
             return $result;
         } else {
         } else {
             return false;
             return false;
@@ -679,7 +677,8 @@ class ExtraFieldValue extends Model
     }
     }
 
 
     /**
     /**
-     * @param $fieldId
+     * @param int $fieldId
+     *
      * @return array|bool
      * @return array|bool
      */
      */
     public function getValuesByFieldId($fieldId)
     public function getValuesByFieldId($fieldId)
@@ -699,6 +698,7 @@ class ExtraFieldValue extends Model
         if (Database::num_rows($result)) {
         if (Database::num_rows($result)) {
             return Database::store_result($result, 'ASSOC');
             return Database::store_result($result, 'ASSOC');
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -726,6 +726,7 @@ class ExtraFieldValue extends Model
         if (Database::num_rows($result)) {
         if (Database::num_rows($result)) {
             return Database::store_result($result, 'ASSOC');
             return Database::store_result($result, 'ASSOC');
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -752,6 +753,7 @@ class ExtraFieldValue extends Model
         if (Database::num_rows($result)) {
         if (Database::num_rows($result)) {
             return Database::store_result($result, 'ASSOC');
             return Database::store_result($result, 'ASSOC');
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -759,6 +761,7 @@ class ExtraFieldValue extends Model
      * @param int $itemId
      * @param int $itemId
      * @param int $fieldId
      * @param int $fieldId
      * @param string $fieldValue
      * @param string $fieldValue
+     *
      * @return array|bool
      * @return array|bool
      */
      */
     public function getAllValuesByItemAndFieldAndValue($itemId, $fieldId, $fieldValue)
     public function getAllValuesByItemAndFieldAndValue($itemId, $fieldId, $fieldValue)
@@ -788,6 +791,7 @@ class ExtraFieldValue extends Model
     /**
     /**
      * Deletes all the values related to a specific field ID
      * Deletes all the values related to a specific field ID
      * @param int $field_id
      * @param int $field_id
+     *
      * @return void
      * @return void
      * @assert ('a') == null
      * @assert ('a') == null
      */
      */
@@ -854,7 +858,7 @@ class ExtraFieldValue extends Model
         $itemId = intval($itemId);
         $itemId = intval($itemId);
         $fieldId = intval($fieldId);
         $fieldId = intval($fieldId);
         $fieldValue = Database::escape_string($fieldValue);
         $fieldValue = Database::escape_string($fieldValue);
-        $extraFieldType = $this->getExtraField()->getExtraFieldType();
+        //$extraFieldType = $this->getExtraField()->getExtraFieldType();
 
 
         $sql = "DELETE FROM {$this->table}
         $sql = "DELETE FROM {$this->table}
                 WHERE
                 WHERE
@@ -936,5 +940,4 @@ class ExtraFieldValue extends Model
 
 
         return $valueList;
         return $valueList;
     }
     }
-
 }
 }

+ 9 - 10
main/inc/lib/fileDisplay.lib.php

@@ -81,6 +81,7 @@ function choose_image($file_name)
             }
             }
         }
         }
     }
     }
+
     return 'defaut.gif';
     return 'defaut.gif';
 }
 }
 
 
@@ -106,7 +107,6 @@ function format_date($date)
 function format_url($file_path)
 function format_url($file_path)
 {
 {
     $path_component = explode('/', $file_path);
     $path_component = explode('/', $file_path);
-
     $path_component = array_map('rawurlencode', $path_component);
     $path_component = array_map('rawurlencode', $path_component);
 
 
     return implode('/', $path_component);
     return implode('/', $path_component);
@@ -121,7 +121,6 @@ function format_url($file_path)
  */
  */
 function recent_modified_file_time($dir_name, $do_recursive = true)
 function recent_modified_file_time($dir_name, $do_recursive = true)
 {
 {
-
     $dir = dir($dir_name);
     $dir = dir($dir_name);
     $last_modified = 0;
     $last_modified = 0;
     $return = 0;
     $return = 0;
@@ -144,6 +143,7 @@ function recent_modified_file_time($dir_name, $do_recursive = true)
         //prevents returning 0 (for empty directories)
         //prevents returning 0 (for empty directories)
         $return = ($last_modified == 0) ? filemtime($dir_name) : $last_modified;
         $return = ($last_modified == 0) ? filemtime($dir_name) : $last_modified;
     }
     }
+
     return $return;
     return $return;
 }
 }
 
 
@@ -156,18 +156,17 @@ function recent_modified_file_time($dir_name, $do_recursive = true)
 function folder_size($dir_name)
 function folder_size($dir_name)
 {
 {
     $size = 0;
     $size = 0;
-
-    if ($dir_handle = opendir($dir_name))
-    {
-        while (($entry = readdir($dir_handle)) !== false)
-        {
-            if($entry == '.' || $entry == '..')
+    if ($dir_handle = opendir($dir_name)) {
+        while (($entry = readdir($dir_handle)) !== false) {
+            if ($entry == '.' || $entry == '..') {
                 continue;
                 continue;
+            }
 
 
-            if(is_dir($dir_name.'/'.$entry))
+            if (is_dir($dir_name.'/'.$entry)) {
                 $size += folder_size($dir_name.'/'.$entry);
                 $size += folder_size($dir_name.'/'.$entry);
-            else
+            } else {
                 $size += filesize($dir_name.'/'.$entry);
                 $size += filesize($dir_name.'/'.$entry);
+            }
         }
         }
 
 
         closedir($dir_handle);
         closedir($dir_handle);

+ 52 - 57
main/inc/lib/fileManage.lib.php

@@ -55,21 +55,21 @@ function update_db_info($action, $old_path, $new_path = '')
  *           boolean FALSE otherwise.
  *           boolean FALSE otherwise.
  */
  */
 function check_name_exist($file_path) {
 function check_name_exist($file_path) {
-	clearstatcache();
-	$save_dir = getcwd();
-	if (!is_dir(dirname($file_path))) {
-		return false;
-	}
-	chdir(dirname($file_path));
-	$file_name = basename($file_path);
-
-	if (file_exists($file_name)) {
-		chdir($save_dir);
-		return true;
-	} else {
-		chdir($save_dir);
-		return false;
-	}
+    clearstatcache();
+    $save_dir = getcwd();
+    if (!is_dir(dirname($file_path))) {
+        return false;
+    }
+    chdir(dirname($file_path));
+    $file_name = basename($file_path);
+
+    if (file_exists($file_name)) {
+        chdir($save_dir);
+        return true;
+    } else {
+        chdir($save_dir);
+        return false;
+    }
 }
 }
 
 
 /**
 /**
@@ -82,17 +82,17 @@ function check_name_exist($file_path) {
  */
  */
 function my_delete($file)
 function my_delete($file)
 {
 {
-	if (check_name_exist($file)) {
-		if (is_file($file)) { // FILE CASE
-			unlink($file);
-			return true;
-		} elseif (is_dir($file)) { // DIRECTORY CASE
-			removeDir($file);
-			return true;
-		}
-	} else {
-		return false; // no file or directory to delete
-	}
+    if (check_name_exist($file)) {
+        if (is_file($file)) { // FILE CASE
+            unlink($file);
+            return true;
+        } elseif (is_dir($file)) { // DIRECTORY CASE
+            removeDir($file);
+            return true;
+        }
+    } else {
+        return false; // no file or directory to delete
+    }
 }
 }
 
 
 /**
 /**
@@ -107,31 +107,31 @@ function my_delete($file)
  */
  */
 function removeDir($dir)
 function removeDir($dir)
 {
 {
-	if (!@$opendir = opendir($dir)) {
-		return false;
-	}
+    if (!@$opendir = opendir($dir)) {
+        return false;
+    }
 
 
-	while ($readdir = readdir($opendir)) {
-		if ($readdir != '..' && $readdir != '.') {
-			if (is_file($dir.'/'.$readdir)) {
-				if (!@unlink($dir.'/'.$readdir)) {
-					return false;
-				}
-			} elseif (is_dir($dir.'/'.$readdir)) {
-				if (!removeDir($dir.'/'.$readdir)) {
-					return false;
-				}
-			}
-		}
-	}
+    while ($readdir = readdir($opendir)) {
+        if ($readdir != '..' && $readdir != '.') {
+            if (is_file($dir.'/'.$readdir)) {
+                if (!@unlink($dir.'/'.$readdir)) {
+                    return false;
+                }
+            } elseif (is_dir($dir.'/'.$readdir)) {
+                if (!removeDir($dir.'/'.$readdir)) {
+                    return false;
+                }
+            }
+        }
+    }
 
 
-	closedir($opendir);
+    closedir($opendir);
 
 
-	if (!@rmdir($dir)) {
-		return false;
-	}
+    if (!@rmdir($dir)) {
+        return false;
+    }
 
 
-	return true;
+    return true;
 }
 }
 
 
 /**
 /**
@@ -154,6 +154,7 @@ function folder_is_empty($in_folder)
             $folder_is_empty = 1;
             $folder_is_empty = 1;
         }
         }
     }
     }
+
     return $folder_is_empty;
     return $folder_is_empty;
 }
 }
 
 
@@ -173,7 +174,6 @@ function my_rename($file_path, $new_file_name) {
 	$save_dir = getcwd();
 	$save_dir = getcwd();
 	$path = dirname($file_path);
 	$path = dirname($file_path);
 	$old_file_name = basename($file_path);
 	$old_file_name = basename($file_path);
-
 	$new_file_name = api_replace_dangerous_char($new_file_name);
 	$new_file_name = api_replace_dangerous_char($new_file_name);
 
 
 	// If no extension, take the old one
 	// If no extension, take the old one
@@ -363,7 +363,8 @@ class FileManager
 			chdir($path);
 			chdir($path);
 			$handle = opendir($path);
 			$handle = opendir($path);
 			while ($element = readdir($handle)) {
 			while ($element = readdir($handle)) {
-				if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
+				if ($element == '.' || $element == '..') continue;
+                // Skip the current and parent directories
 				if (is_dir($element)) {
 				if (is_dir($element)) {
 					$dir_array[] = $path.'/'.$element;
 					$dir_array[] = $path.'/'.$element;
 				}
 				}
@@ -447,7 +448,8 @@ class FileManager
 	 * @author	Roan Embrechts
 	 * @author	Roan Embrechts
 	 * @version 1.2
 	 * @version 1.2
 	 */
 	 */
-	function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v') {
+	function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v')
+    {
 		if (!$default_visibility) $default_visibility = 'v';
 		if (!$default_visibility) $default_visibility = 'v';
 
 
 		// Make sure path is not wrongly formed
 		// Make sure path is not wrongly formed
@@ -477,15 +479,8 @@ class FileManager
 		}
 		}
 		Database::query($query);
 		Database::query($query);
 	}
 	}
-
-
-
 } //end class FileManager
 } //end class FileManager
 
 
-
-
-
-
 /*	DEPRECATED FUNCTIONS */
 /*	DEPRECATED FUNCTIONS */
 
 
 /**
 /**

+ 3 - 1
main/inc/lib/fileUpload.lib.php

@@ -141,6 +141,7 @@ function process_uploaded_file($uploaded_file, $show_output = true)
             if ($show_output) {
             if ($show_output) {
                 Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
                 Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
             }
             }
+
             return false;
             return false;
         }
         }
     }
     }
@@ -155,6 +156,7 @@ function process_uploaded_file($uploaded_file, $show_output = true)
             if ($show_output) {
             if ($show_output) {
                 Display::display_error_message(get_lang('UplNotEnoughSpace'));
                 Display::display_error_message(get_lang('UplNotEnoughSpace'));
             }
             }
+
             return false;
             return false;
         }
         }
     }
     }
@@ -709,6 +711,7 @@ function enough_size($file_size, $dir, $max_dir_space)
             return false;
             return false;
         }
         }
     }
     }
+
     return true;
     return true;
 }
 }
 
 
@@ -751,7 +754,6 @@ function dir_total_space($dir_path)
     return $sumSize;
     return $sumSize;
 }
 }
 
 
-
 /**
 /**
  * Tries to add an extension to files without extension
  * Tries to add an extension to files without extension
  * Some applications on Macintosh computers don't add an extension to the files.
  * Some applications on Macintosh computers don't add an extension to the files.

+ 0 - 95
main/inc/lib/file_store.class.php

@@ -1,95 +0,0 @@
-<?php
-
-/**
- *
- * @copyright (c) 2012 University of Geneva
- * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
- * @author Laurent Opprecht <laurent@opprecht.info>
- */
-class FileStore
-{
-
-    /**
-     *
-     * @param int $c_id
-     * @param string $sub_path 
-
-     * @return FileStore 
-     */
-    static function course($c_id, $sub_path = '') 
-    { 
-        
-        $sys_path = api_get_path(SYS_COURSE_PATH);
-        $course = api_get_course_info_by_id($c_id);
-        $course_path = $course['path'];
-        $path = $sys_path . $course_path . $sub_path;
-        if (!is_dir($path)) {
-            $mode = api_get_permissions_for_new_directories();
-            $success = mkdir($path, $mode, true);
-            if (!$success) {
-                return false;
-            }
-        }
-        return new self($path);
-    }
-
-    protected $root = '';
-
-    public function __construct($root)
-    {
-        $root = ltrim($root, '/');
-        $root .= '/';
-        $this->root = $root;
-    }
-
-    public function root()
-    {
-        return $this->root;
-    }
-
-    function accept($filename)
-    {
-        return (bool) filter_extension($filename);
-    }
-
-    function add($path)
-    {
-        $root = $this->root();
-        $id = $this->new_id();
-
-        $new_path = "$root/$id";
-        $success = @move_uploaded_file($path, $new_path);
-        return $success ? $id : false;
-    }
-    
-    function remove($path){
-        
-        $root = $this->root();
-        $full_path = "$root/$path";
-        if(is_file($full_path)){
-            $result = unlink($full_path);
-            return $result;
-        }
-        return  false;
-    }
-
-    function get($id)
-    {
-        $root = $this->root();
-        $result = "$root/$id";
-        return $result;
-    }
-
-    function new_id()
-    {
-        $root = $this->root();
-        $id = uniqid('');
-        $path = "$root/$id";
-        while (file_exists($path)) {
-            $id = uniqid('');
-            $path = "$root/$id";
-        }
-        return $id;
-    }
-
-}

+ 2 - 1
main/inc/lib/formvalidator/Element/DatePicker.php

@@ -38,12 +38,13 @@ class DatePicker extends HTML_QuickForm_text
 
 
         $id = $this->getAttribute('id');
         $id = $this->getAttribute('id');
         $value = $this->getValue();
         $value = $this->getValue();
+        $label = $this->getLabel();
 
 
         if (!empty($value)) {
         if (!empty($value)) {
             $value = api_format_date($value, DATE_TIME_FORMAT_LONG_24H);
             $value = api_format_date($value, DATE_TIME_FORMAT_LONG_24H);
         }
         }
 
 
-        if (empty($this->getLabel())) {
+        if (empty($label)) {
             return $this->getElementJS() . '
             return $this->getElementJS() . '
                 <div class="input-group">
                 <div class="input-group">
                     <span class="input-group-addon">
                     <span class="input-group-addon">

+ 2 - 1
main/inc/lib/formvalidator/Element/DateTimePicker.php

@@ -32,12 +32,13 @@ class DateTimePicker extends HTML_QuickForm_text
 
 
         $id = $this->getAttribute('id');
         $id = $this->getAttribute('id');
         $value = $this->getValue();
         $value = $this->getValue();
+        $label = $this->getLabel();
 
 
         if (!empty($value)) {
         if (!empty($value)) {
             $value = api_format_date($value, DATE_TIME_FORMAT_LONG_24H);
             $value = api_format_date($value, DATE_TIME_FORMAT_LONG_24H);
         }
         }
 
 
-        if (empty($this->getLabel())) {
+        if (empty($label)) {
             return $this->getElementJS() . '
             return $this->getElementJS() . '
                 <div class="input-group">
                 <div class="input-group">
                     <span class="input-group-addon">
                     <span class="input-group-addon">

+ 55 - 56
main/inc/lib/geometry.lib.php

@@ -4,9 +4,7 @@
  * @author Arnaud Ligot (CBlue SPRL) <arnaud@cblue.be>
  * @author Arnaud Ligot (CBlue SPRL) <arnaud@cblue.be>
  * @package chamilo.include.geometry
  * @package chamilo.include.geometry
  */
  */
-/**
- * Code
- */
+
 DEFINE('DEBUG', false);
 DEFINE('DEBUG', false);
 /**
 /**
  * poly_init -    build the array which will store the image of the polygone
  * poly_init -    build the array which will store the image of the polygone
@@ -15,7 +13,7 @@ DEFINE('DEBUG', false);
  * @returns an array such as: for all i in [0..max[x][ : for all j in [0..max[y][ : array[i][j] = FALSE
  * @returns an array such as: for all i in [0..max[x][ : for all j in [0..max[y][ : array[i][j] = FALSE
  */
  */
 function poly_init($max) {
 function poly_init($max) {
-    return array_fill(0, $max["x"]-1, 
+    return array_fill(0, $max["x"]-1,
             array_fill(0, $max["y"]-1, FALSE));
             array_fill(0, $max["y"]-1, FALSE));
 }
 }
 
 
@@ -24,7 +22,7 @@ function poly_init($max) {
  * poly_compile - return an array which holds the image of the polygone
  * poly_compile - return an array which holds the image of the polygone
  *            FALSE = blank pixel
  *            FALSE = blank pixel
  *            TRUE = black pixel
  *            TRUE = black pixel
- * 
+ *
  * @param poly        points from the polygone
  * @param poly        points from the polygone
  *            example:
  *            example:
  *                poly[0]['x'] = ...
  *                poly[0]['x'] = ...
@@ -47,15 +45,15 @@ function poly_compile($poly, $max, $test = false) {
     $res = poly_init($max);
     $res = poly_init($max);
 
 
     // looking for EDGES
     // looking for EDGES
-        // may be optimized by a dynamic choice 
+        // may be optimized by a dynamic choice
         // between Y and X based on max[y]<max[x]
         // between Y and X based on max[y]<max[x]
-    
+
     /*
     /*
      * bords    cointains the edges of the polygone
      * bords    cointains the edges of the polygone
-     *        it is an array of array, 
+     *        it is an array of array,
      *            there are an array for each collon of the image
      *            there are an array for each collon of the image
      *
      *
-     *        for all j in [O..max[y][ : for all i in bords[$j] : 
+     *        for all j in [O..max[y][ : for all i in bords[$j] :
      *            (i,j) is a point inside an edge of the polygone
      *            (i,j) is a point inside an edge of the polygone
      */
      */
 	$bord_lenght = $max['x'];
 	$bord_lenght = $max['x'];
@@ -67,47 +65,47 @@ function poly_compile($poly, $max, $test = false) {
     $bords = array_fill(0, $bord_lenght, array()); // building this array
     $bords = array_fill(0, $bord_lenght, array()); // building this array
 
 
     /* adding the first point of the polygone */
     /* adding the first point of the polygone */
-    if (is_array($bords[$poly[0]['y']])) //avoid warning 
+    if (is_array($bords[$poly[0]['y']])) //avoid warning
     	array_push($bords[$poly[0]['y']], $poly[0]['x']);
     	array_push($bords[$poly[0]['y']], $poly[0]['x']);
-    
+
     $i = 1; // we re-use $i and $old_pente bellow the loop
     $i = 1; // we re-use $i and $old_pente bellow the loop
     $old_pente=0;
     $old_pente=0;
-    for (    ;    // for each points of the polygon but the first 
+    for (    ;    // for each points of the polygon but the first
         $i<sizeof($poly) && (!empty($poly[$i]['x']) && !empty($poly[$i]['y'])); $i++) {
         $i<sizeof($poly) && (!empty($poly[$i]['x']) && !empty($poly[$i]['y'])); $i++) {
-        
+
         /* special cases */
         /* special cases */
         if ($poly[$i-1]['y'] == $poly[$i]['y']) {
         if ($poly[$i-1]['y'] == $poly[$i]['y']) {
-            if ($poly[$i-1]['x'] == $poly[$i]['x']) 
+            if ($poly[$i-1]['x'] == $poly[$i]['x'])
                 continue; // twice the same point
                 continue; // twice the same point
             else {    //  infinite elevation of the edge
             else {    //  infinite elevation of the edge
             	if (is_array($bords[$poly[$i]['y']]))
             	if (is_array($bords[$poly[$i]['y']]))
-                	array_push($bords[$poly[$i]['y']],$poly[$i]['x']);                
+                	array_push($bords[$poly[$i]['y']],$poly[$i]['x']);
                 $old_pente=0;
                 $old_pente=0;
                 continue;
                 continue;
             }
             }
         }
         }
-    	
+
 		//echo 'point:'.$poly[$i]['y']; bug here
 		//echo 'point:'.$poly[$i]['y']; bug here
         // adding the point as a part of an edge
         // adding the point as a part of an edge
         if (is_array($bords[$poly[$i]['y']])) //avoid warning
         if (is_array($bords[$poly[$i]['y']])) //avoid warning
         array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
         array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
         if (DEBUG) echo '('.$poly[$i]['x'].';'.$poly[$i]['y'].')   ';
         if (DEBUG) echo '('.$poly[$i]['x'].';'.$poly[$i]['y'].')   ';
-        
+
         /* computing the elevation of the edge going */
         /* computing the elevation of the edge going */
-        //        from $poly[$i-1] to $poly[$i] 
+        //        from $poly[$i-1] to $poly[$i]
         $pente = ($poly[$i-1]['x']-$poly[$i]['x'])/
         $pente = ($poly[$i-1]['x']-$poly[$i]['x'])/
                  ($poly[$i-1]['y']-$poly[$i]['y']);
                  ($poly[$i-1]['y']-$poly[$i]['y']);
 
 
-        // if the sign of the elevation change from the one of the 
+        // if the sign of the elevation change from the one of the
         // previous edge, the point must be added a second time inside
         // previous edge, the point must be added a second time inside
         // $bords
         // $bords
         if ($i>1)
         if ($i>1)
-            if (($old_pente<0 && $pente>0) 
+            if (($old_pente<0 && $pente>0)
                     || ($old_pente>0 && $pente<0)) {
                     || ($old_pente>0 && $pente<0)) {
-				if (is_array($bords[$poly[$i]['y']])) //avoid warning  
+				if (is_array($bords[$poly[$i]['y']])) //avoid warning
                 	array_push($bords[$poly[$i]['y']],$poly[$i]['x']);
                 	array_push($bords[$poly[$i]['y']],$poly[$i]['x']);
-                
-                if (DEBUG) 
+
+                if (DEBUG)
                     echo '*('.$poly[$i]['x'].
                     echo '*('.$poly[$i]['x'].
                         ';'.$poly[$i]['y'].')   ';
                         ';'.$poly[$i]['y'].')   ';
         	}
         	}
@@ -123,16 +121,16 @@ function poly_compile($poly, $max, $test = false) {
 
 
         // we iterate w/ $dy in ]$poly[$i-1]['y'],$poly[$i-1]['y'][
         // we iterate w/ $dy in ]$poly[$i-1]['y'],$poly[$i-1]['y'][
         //    w/ $dy_inc as increment
         //    w/ $dy_inc as increment
-        for ($dy = $poly[$i-1]['y']+$dy_inc; 
-            $dy != $poly[$i]['y']; 
+        for ($dy = $poly[$i-1]['y']+$dy_inc;
+            $dy != $poly[$i]['y'];
             $dy += $dy_inc) {
             $dy += $dy_inc) {
             $x += $pente*$dy_inc;
             $x += $pente*$dy_inc;
             array_push($bords[$dy], $x);
             array_push($bords[$dy], $x);
 //            if (DEBUG) echo '/('.$x.';'.$dy.')   ';
 //            if (DEBUG) echo '/('.$x.';'.$dy.')   ';
         }
         }
-        $old_pente = $pente; 
+        $old_pente = $pente;
     }
     }
-    
+
     // closing the polygone (the edge between $poly[$i-1] and $poly[0])
     // closing the polygone (the edge between $poly[$i-1] and $poly[0])
     if ($poly[$i-1]['y']!=$poly[0]['y']) {// droite--> rien à faire
     if ($poly[$i-1]['y']!=$poly[0]['y']) {// droite--> rien à faire
 
 
@@ -140,11 +138,11 @@ function poly_compile($poly, $max, $test = false) {
         $rest = $poly[0]['y']-$poly[1]['y'];
         $rest = $poly[0]['y']-$poly[1]['y'];
         if ($rest!=0)
         if ($rest!=0)
         	$pente1 = ($poly[0]['x']-$poly[1]['x'])/($rest);
         	$pente1 = ($poly[0]['x']-$poly[1]['x'])/($rest);
-        else 
+        else
 			$pente1 = 0;
 			$pente1 = 0;
-			
+
         // elevation between $poly[$i-1]['x'] and $poly[0]['x'])
         // elevation between $poly[$i-1]['x'] and $poly[0]['x'])
-        $pente = ($poly[$i-1]['x']-$poly[0]['x'])/ 
+        $pente = ($poly[$i-1]['x']-$poly[0]['x'])/
             ($poly[$i-1]['y']-$poly[0]['y']);
             ($poly[$i-1]['y']-$poly[0]['y']);
 
 
 //        if (DEBUG) echo 'start('.$poly[$i-1]['x'].','.$poly[$i-1]['y'].
 //        if (DEBUG) echo 'start('.$poly[$i-1]['x'].','.$poly[$i-1]['y'].
@@ -152,8 +150,8 @@ function poly_compile($poly, $max, $test = false) {
 //                ')-pente'.$pente;
 //                ')-pente'.$pente;
 
 
         // doubling the first point if needed (see above)
         // doubling the first point if needed (see above)
-        if (($pente1<0 && $pente>0) || ($pente1>0 && $pente<0)) {  
-        	if (is_array($bords[$poly[$i]['y']]))      	
+        if (($pente1<0 && $pente>0) || ($pente1>0 && $pente<0)) {
+        	if (is_array($bords[$poly[$i]['y']]))
             	array_push($bords[$poly[$i]['y']],  round($poly[$i]['x']));
             	array_push($bords[$poly[$i]['y']],  round($poly[$i]['x']));
             //if (DEBUG) echo '('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].')   ';
             //if (DEBUG) echo '('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].')   ';
         }
         }
@@ -164,14 +162,14 @@ function poly_compile($poly, $max, $test = false) {
             //if (DEBUG) echo '*('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].')   ';
             //if (DEBUG) echo '*('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].')   ';
         }
         }
 
 
-        
+
         $dy_inc = ($poly[0]['y']-$poly[$i-1]['y']) > 0 ? 1 : -1;
         $dy_inc = ($poly[0]['y']-$poly[$i-1]['y']) > 0 ? 1 : -1;
         $x = $poly[$i-1]['x'];
         $x = $poly[$i-1]['x'];
 //        if (DEBUG) echo "init: ".$poly[$i-1]['y']."  dy_inc: ".$dy_inc.
 //        if (DEBUG) echo "init: ".$poly[$i-1]['y']."  dy_inc: ".$dy_inc.
 //            "   end: ".$poly[0]['y'];
 //            "   end: ".$poly[0]['y'];
 
 
-        for ($dy = $poly[$i-1]['y']+$dy_inc; 
-            $dy != $poly[0]['y']; 
+        for ($dy = $poly[$i-1]['y']+$dy_inc;
+            $dy != $poly[0]['y'];
             $dy += $dy_inc)
             $dy += $dy_inc)
         {
         {
             $x += $pente*$dy_inc;
             $x += $pente*$dy_inc;
@@ -179,33 +177,34 @@ function poly_compile($poly, $max, $test = false) {
 //            if (DEBUG) echo '/('.$x.';'.$dy.')   ';
 //            if (DEBUG) echo '/('.$x.';'.$dy.')   ';
         }
         }
     }
     }
-    
+
     /* filling the polygon */
     /* filling the polygon */
-    /* basic idea: we sort a column of edges. 
+    /* basic idea: we sort a column of edges.
         For each pair of point, we color the points in between */
         For each pair of point, we color the points in between */
     $n = count($bords);
     $n = count($bords);
     for ($i = 0; $i<$n; $i++) {  // Y
     for ($i = 0; $i<$n; $i++) {  // Y
         //error_log(__FILE__.' - Border Num '.$i,0);
         //error_log(__FILE__.' - Border Num '.$i,0);
         if (is_array($bords[$i])) {
         if (is_array($bords[$i])) {
        		sort($bords[$i]);
        		sort($bords[$i]);
-        } 
-         	
+        }
+
         for ($j = 0; $j<sizeof($bords[$i]);$j+=2) // bords
         for ($j = 0; $j<sizeof($bords[$i]);$j+=2) // bords
-            for ($k = round($bords[$i][$j]); $k<=$bords[$i][$j+1];$k++) { 
+            for ($k = round($bords[$i][$j]); $k<=$bords[$i][$j+1];$k++) {
                 $res[$k][$i] = true; //filling the array with trues
                 $res[$k][$i] = true; //filling the array with trues
                 if ($test == 1)  {
                 if ($test == 1)  {
                 	/*how to draw the polygon in a human way:
                 	/*how to draw the polygon in a human way:
                 	In ubuntu : sudo apt-get install gnuplot
                 	In ubuntu : sudo apt-get install gnuplot
                 	Create an empty file with all points with the result of this echos (No commas, no point, no headers)
                 	Create an empty file with all points with the result of this echos (No commas, no point, no headers)
-                	In gnuplot: 
+                	In gnuplot:
                 	For 1 polygon:  plot "/home/jmontoya/test"
                 	For 1 polygon:  plot "/home/jmontoya/test"
                 	For 2 polygons:  plot "/home/jmontoya/test", "/home/jmontoya/test2"
                 	For 2 polygons:  plot "/home/jmontoya/test", "/home/jmontoya/test2"
                 	A new window will appear with the plot
                 	A new window will appear with the plot
                 	*/
                 	*/
-                	echo $k.'  '.$i; echo '<br />';                	
+                	echo $k.'  '.$i; echo '<br />';
                 }
                 }
             }
             }
     }
     }
+
     return $res;
     return $res;
 }
 }
 
 
@@ -215,7 +214,7 @@ function poly_compile($poly, $max, $test = false) {
  * @param array       the polygone as output by poly_compile()
  * @param array       the polygone as output by poly_compile()
  * @param array       see above (poly_init)
  * @param array       see above (poly_init)
  * @param string      Format ('raw' text or 'html')
  * @param string      Format ('raw' text or 'html')
- * 
+ *
  * @return string     html code of the representation of the polygone image
  * @return string     html code of the representation of the polygone image
  */
  */
 function poly_dump(&$poly, $max, $format='raw') {
 function poly_dump(&$poly, $max, $format='raw') {
@@ -240,25 +239,25 @@ function poly_dump(&$poly, $max, $format='raw') {
  * @param poly1        first polygone as returned by poly_compile
  * @param poly1        first polygone as returned by poly_compile
  * @param poly2        second ....
  * @param poly2        second ....
  * @param max        resolution as specified for poly_init
  * @param max        resolution as specified for poly_init
- * 
+ *
  * @returns (see below, UTSL)
  * @returns (see below, UTSL)
  */
  */
 function poly_result(&$poly1, &$poly2, $max) {
 function poly_result(&$poly1, &$poly2, $max) {
     $onlyIn1 = 0;
     $onlyIn1 = 0;
     $surfaceOf1 = 0;
     $surfaceOf1 = 0;
-    $surfaceOf2 = 0;    
+    $surfaceOf2 = 0;
 
 
-    for ($i=0; $i<$max['x']; $i++) 
+    for ($i=0; $i<$max['x']; $i++)
         for($j=0; $j<$max['y']; $j++) {
         for($j=0; $j<$max['y']; $j++) {
             if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == TRUE)) {
             if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == TRUE)) {
                 $surfaceOf1++;
                 $surfaceOf1++;
-                if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == FALSE)) 
+                if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == FALSE))
                     $onlyIn1++;
                     $onlyIn1++;
             }
             }
-            if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == TRUE)) 
+            if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == TRUE))
                 $surfaceOf2++;
                 $surfaceOf2++;
         }
         }
-    
+
     return array (
     return array (
         "s1" => $surfaceOf1,
         "s1" => $surfaceOf1,
         "s2" => $surfaceOf2,
         "s2" => $surfaceOf2,
@@ -273,14 +272,14 @@ function poly_result(&$poly1, &$poly2, $max) {
  * @param poly1        first polygone as returned by poly_compile
  * @param poly1        first polygone as returned by poly_compile
  * @param poly2        second ....
  * @param poly2        second ....
  * @param max        resolution as specified for poly_init
  * @param max        resolution as specified for poly_init
- * 
+ *
  * @returns (see below, UTSL)
  * @returns (see below, UTSL)
  */
  */
 function poly_touch(&$poly1, &$poly2, $max) {
 function poly_touch(&$poly1, &$poly2, $max) {
 
 
     for ($i=0; $i<$max['x']; $i++) {
     for ($i=0; $i<$max['x']; $i++) {
         for($j=0; $j<$max['y']; $j++) {
         for($j=0; $j<$max['y']; $j++) {
-            if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == true) 
+            if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == true)
                 && isset($poly2[$i][$j]) && ($poly2[$i][$j] == true)) {
                 && isset($poly2[$i][$j]) && ($poly2[$i][$j] == true)) {
                     return true;
                     return true;
             }
             }
@@ -290,7 +289,7 @@ function poly_touch(&$poly1, &$poly2, $max) {
 }
 }
 
 
 /**
 /**
- * Convert a list of points in x1;y1|x2;y2|x3;y3 or x1;y1/x2;y2 format to 
+ * Convert a list of points in x1;y1|x2;y2|x3;y3 or x1;y1/x2;y2 format to
  * the format in which the functions in this library are expecting their data
  * the format in which the functions in this library are expecting their data
  * @param   string  List of points in x1;y1|... format (or /)
  * @param   string  List of points in x1;y1|... format (or /)
  * @param   string  The points separator for the list (| or /)
  * @param   string  The points separator for the list (| or /)
@@ -302,7 +301,7 @@ function convert_coordinates($coords,$sep='|') {
     $pairs = explode($sep,$coords);
     $pairs = explode($sep,$coords);
     foreach ($pairs as $idx => $pcoord) {
     foreach ($pairs as $idx => $pcoord) {
         list($x,$y) = explode(';',$pcoord);
         list($x,$y) = explode(';',$pcoord);
-        $points[] = array('x'=>$x,'y'=>$y); 
+        $points[] = array('x'=>$x,'y'=>$y);
     }
     }
 	return $points;
 	return $points;
 }
 }
@@ -311,13 +310,13 @@ function convert_coordinates($coords,$sep='|') {
  * Returns the maximum coordinates in x,y (from 0,0) that the geometrical form
  * Returns the maximum coordinates in x,y (from 0,0) that the geometrical form
  * can reach
  * can reach
  * @param   array   Coordinates of one polygon
  * @param   array   Coordinates of one polygon
- * @return  array   ('x'=>val,'y'=>val)   
+ * @return  array   ('x'=>val,'y'=>val)
  */
  */
 function poly_get_max(&$coords1, &$coords2) {
 function poly_get_max(&$coords1, &$coords2) {
     $mx = 0;
     $mx = 0;
     $my = 0;
     $my = 0;
     foreach ($coords1 as $coord) {
     foreach ($coords1 as $coord) {
-    	if ($coord['x'] > $mx) { 
+    	if ($coord['x'] > $mx) {
             $mx = $coord['x'];
             $mx = $coord['x'];
     	}
     	}
         if ($coord['y'] > $my) {
         if ($coord['y'] > $my) {
@@ -325,7 +324,7 @@ function poly_get_max(&$coords1, &$coords2) {
         }
         }
     }
     }
     foreach ($coords2 as $coord) {
     foreach ($coords2 as $coord) {
-        if ($coord['x'] > $mx) { 
+        if ($coord['x'] > $mx) {
             $mx = $coord['x'];
             $mx = $coord['x'];
         }
         }
         if ($coord['y'] > $my) {
         if ($coord['y'] > $my) {

+ 37 - 31
main/inc/lib/glossary.lib.php

@@ -48,6 +48,7 @@ class GlossaryManager
         $rs=Database::query($sql);
         $rs=Database::query($sql);
         if (Database::num_rows($rs) > 0) {
         if (Database::num_rows($rs) > 0) {
             $row = Database::fetch_array($rs);
             $row = Database::fetch_array($rs);
+
             return $row['description'];
             return $row['description'];
         } else {
         } else {
             return '';
             return '';
@@ -158,7 +159,6 @@ class GlossaryManager
     {
     {
         // Database table definition
         // Database table definition
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
-
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
         // check if the glossary term already exists
         // check if the glossary term already exists
@@ -206,7 +206,8 @@ class GlossaryManager
         // Database table definition
         // Database table definition
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
-        $get_max = "SELECT MAX(display_order) FROM $t_glossary WHERE c_id = $course_id ";
+        $get_max = "SELECT MAX(display_order) FROM $t_glossary
+                    WHERE c_id = $course_id ";
         $res_max = Database::query($get_max);
         $res_max = Database::query($get_max);
         if (Database::num_rows($res_max)==0) {
         if (Database::num_rows($res_max)==0) {
             return 0;
             return 0;
@@ -235,7 +236,10 @@ class GlossaryManager
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
-        $sql = "SELECT name FROM $t_glossary WHERE c_id = $course_id AND name = '".Database::escape_string($term)."'";
+        $sql = "SELECT name FROM $t_glossary
+                WHERE
+                    c_id = $course_id AND
+                    name = '".Database::escape_string($term)."'";
         if ($not_id<>'') {
         if ($not_id<>'') {
             $sql .= " AND glossary_id <> '".Database::escape_string($not_id)."'";
             $sql .= " AND glossary_id <> '".Database::escape_string($not_id)."'";
         }
         }
@@ -261,21 +265,25 @@ class GlossaryManager
         // Database table definition
         // Database table definition
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_item_propery = Database :: get_course_table(TABLE_ITEM_PROPERTY);
         $t_item_propery = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-        if (empty($glossary_id)) { return false; }
-        $sql = "SELECT 	g.glossary_id 		as glossary_id,
-						g.name 				as glossary_title,
-						g.description 		as glossary_comment,
-						g.display_order		as glossary_display_order,
-						ip.insert_date      as insert_date,
-                        ip.lastedit_date    as update_date,
-						g.session_id
-				   FROM $t_glossary g, $t_item_propery ip
-                   WHERE 	g.glossary_id 	= ip.ref AND
-                   			tool 			= '".TOOL_GLOSSARY."' AND
-							g.glossary_id 	= '".intval($glossary_id)."' AND
-							g.c_id			= ".api_get_course_int_id()." AND
-							ip.c_id			= ".api_get_course_int_id()."
-					";
+        if (empty($glossary_id)) {
+            return false;
+        }
+        $sql = "SELECT
+                    g.glossary_id 		as glossary_id,
+                    g.name 				as glossary_title,
+                    g.description 		as glossary_comment,
+                    g.display_order		as glossary_display_order,
+                    ip.insert_date      as insert_date,
+                    ip.lastedit_date    as update_date,
+                    g.session_id
+                FROM $t_glossary g, $t_item_propery ip
+                WHERE
+                    g.glossary_id 	= ip.ref AND
+                    tool 			= '".TOOL_GLOSSARY."' AND
+                    g.glossary_id 	= '".intval($glossary_id)."' AND
+                    g.c_id			= ".api_get_course_int_id()." AND
+                    ip.c_id			= ".api_get_course_int_id()."
+                ";
         $result = Database::query($sql);
         $result = Database::query($sql);
         if ($result === false || Database::num_rows($result) != 1) {
         if ($result === false || Database::num_rows($result) != 1) {
             return false;
             return false;
@@ -354,7 +362,7 @@ class GlossaryManager
                 Display::return_icon('view_text.png',get_lang('TableView'),'',ICON_SIZE_MEDIUM).'</a>';
                 Display::return_icon('view_text.png',get_lang('TableView'),'',ICON_SIZE_MEDIUM).'</a>';
         }
         }
         echo '</div>';
         echo '</div>';
-        if (!$_SESSION['glossary_view'] OR $_SESSION['glossary_view'] == 'table') {
+        if (!$_SESSION['glossary_view'] || $_SESSION['glossary_view'] == 'table') {
             $table = new SortableTable(
             $table = new SortableTable(
                 'glossary',
                 'glossary',
                 array('GlossaryManager', 'get_number_glossary_terms'),
                 array('GlossaryManager', 'get_number_glossary_terms'),
@@ -410,9 +418,12 @@ class GlossaryManager
 
 
         $session_id = intval($session_id);
         $session_id = intval($session_id);
         $sql_filter = api_get_session_condition($session_id, true, true);
         $sql_filter = api_get_session_condition($session_id, true, true);
-        $sql = "SELECT count(glossary_id) as total FROM $t_glossary WHERE c_id = $course_id $sql_filter";
+        $sql = "SELECT count(glossary_id) as total
+                FROM $t_glossary WHERE c_id = $course_id $sql_filter";
         $res = Database::query($sql);
         $res = Database::query($sql);
-        if ($res === false) { return 0; }
+        if ($res === false) {
+            return 0;
+        }
         $obj = Database::fetch_object($res);
         $obj = Database::fetch_object($res);
         return $obj->total;
         return $obj->total;
     }
     }
@@ -432,7 +443,7 @@ class GlossaryManager
      */
      */
     public static  function get_glossary_data($from, $number_of_items, $column, $direction)
     public static  function get_glossary_data($from, $number_of_items, $column, $direction)
     {
     {
-        global $_user;
+        $_user = api_get_user_info();
         // Database table definition
         // Database table definition
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
         $t_item_propery = Database :: get_course_table(TABLE_ITEM_PROPERTY);
         $t_item_propery = Database :: get_course_table(TABLE_ITEM_PROPERTY);
@@ -481,13 +492,6 @@ class GlossaryManager
             }
             }
 
 
             if (api_is_allowed_to_edit(null,true)) {
             if (api_is_allowed_to_edit(null,true)) {
-                // Date treatment for timezones
-                /*if (!empty($data[2])  && $data[2] != '0000-00-00 00:00:00:') {
-                    $array[2] = api_get_local_time($data[2], null, date_default_timezone_get());
-                }
-                if (!empty($data[3])  && $data[3] != '0000-00-00 00:00:00:') {
-                    $array[3] = api_get_local_time($data[3], null, date_default_timezone_get());
-                }*/
                 $array[2] = $data[2];
                 $array[2] = $data[2];
             }
             }
             $return[] = $array;
             $return[] = $array;
@@ -605,8 +609,10 @@ class GlossaryManager
                 $found = true;
                 $found = true;
             }
             }
         }
         }
-        $sql1 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($next_display_order)."' WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($current_id)."'";
-        $sql2 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($current_display_order)."' WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($next_id)."'";
+        $sql1 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($next_display_order)."'
+                WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($current_id)."'";
+        $sql2 = "UPDATE $t_glossary SET display_order = '".Database::escape_string($current_display_order)."'
+                WHERE c_id = $course_id  AND glossary_id = '".Database::escape_string($next_id)."'";
         Database::query($sql1);
         Database::query($sql1);
         Database::query($sql2);
         Database::query($sql2);
         if ($message)
         if ($message)

+ 18 - 4
main/inc/lib/grade_model.lib.php

@@ -24,7 +24,11 @@ class GradeModel extends Model
      */
      */
     public function get_all($where_conditions = array())
     public function get_all($where_conditions = array())
     {
     {
-        return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
+        return Database::select(
+            '*',
+            $this->table,
+            array('where' => $where_conditions, 'order' => 'name ASC')
+        );
     }
     }
 
 
     /**
     /**
@@ -32,7 +36,13 @@ class GradeModel extends Model
      */
      */
     public function get_count()
     public function get_count()
     {
     {
-        $row = Database::select('count(*) as count', $this->table, array(),'first');
+        $row = Database::select(
+            'count(*) as count',
+            $this->table,
+            array(),
+            'first'
+        );
+
         return $row['count'];
         return $row['count'];
     }
     }
 
 
@@ -86,9 +96,9 @@ class GradeModel extends Model
 
 
         $form->addElement('label', get_lang('Components'));
         $form->addElement('label', get_lang('Components'));
 
 
-        //Get components
+        // Get components
         $nr_items = 2;
         $nr_items = 2;
-        $max      = 10;
+        $max = 10;
 
 
         // Setting the defaults
         // Setting the defaults
 
 
@@ -203,10 +213,14 @@ class GradeModel extends Model
                 }
                 }
             }
             }
         }
         }
+
         //event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
         //event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
    		return $id;
    		return $id;
     }
     }
 
 
+    /**
+     * @param array $params
+     */
     public function update($params)
     public function update($params)
     {
     {
         parent::update($params);
         parent::update($params);

+ 11 - 4
main/inc/lib/gradebook.lib.php

@@ -42,7 +42,9 @@ class Gradebook extends Model
     {
     {
         $name = 'gradebook';
         $name = 'gradebook';
         $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
         $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-        $sql = "SELECT * from $table WHERE variable='course_hide_tools' AND subkey='$name' LIMIT 1";
+        $sql = "SELECT * from $table
+                WHERE variable='course_hide_tools' AND subkey='$name'
+                LIMIT 1";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $setting = Database::store_result($result);
         $setting = Database::store_result($result);
         $setting = isset($setting[0]) ? $setting[0] : null;
         $setting = isset($setting[0]) ? $setting[0] : null;
@@ -55,7 +57,9 @@ class Gradebook extends Model
 
 
         $c_id = $c_id ? intval($c_id) : api_get_course_int_id();
         $c_id = $c_id ? intval($c_id) : api_get_course_int_id();
         $table  = Database::get_course_table(TABLE_TOOL_LIST);
         $table  = Database::get_course_table(TABLE_TOOL_LIST);
-        $sql = "SELECT * from $table WHERE c_id = $c_id and name='$name' LIMIT 1";
+        $sql = "SELECT * from $table
+                WHERE c_id = $c_id and name='$name'
+                LIMIT 1";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $item = Database::store_result($result, 'ASSOC');
         $item = Database::store_result($result, 'ASSOC');
         $item = isset($item[0]) ? $item[0] : null;
         $item = isset($item[0]) ? $item[0] : null;
@@ -68,6 +72,7 @@ class Gradebook extends Model
 
 
     /**
     /**
      * @param array $options
      * @param array $options
+     *
      * @return array
      * @return array
      */
      */
     public function get_all($options = array())
     public function get_all($options = array())
@@ -77,13 +82,13 @@ class Gradebook extends Model
             if (empty($gradebook['name'])) {
             if (empty($gradebook['name'])) {
                 $gradebook['name'] = $gradebook['course_code'];
                 $gradebook['name'] = $gradebook['course_code'];
             }
             }
-            //$gradebook['name'] = $gradebook['course_code'] .' > '.$gradebook['name'];
         }
         }
         return $gradebooks;
         return $gradebooks;
     }
     }
 
 
     /**
     /**
      * @param array $params
      * @param array $params
+     *
      * @return bool
      * @return bool
      */
      */
     public function update($params)
     public function update($params)
@@ -107,7 +112,9 @@ class Gradebook extends Model
             $skill_list = array_map('intval', $skill_list);
             $skill_list = array_map('intval', $skill_list);
             $skill_list = array_filter($skill_list);
             $skill_list = array_filter($skill_list);
             $skill_gradebook = new SkillRelGradebook();
             $skill_gradebook = new SkillRelGradebook();
-            $skill_gradebooks_source = $skill_gradebook->get_all(array('where'=>array('gradebook_id = ?' =>$gradebook_id)));
+            $skill_gradebooks_source = $skill_gradebook->get_all(
+                array('where' => array('gradebook_id = ?' => $gradebook_id))
+            );
             $clean_gradebook = array();
             $clean_gradebook = array();
 
 
             if (!empty($skill_gradebooks_source)) {
             if (!empty($skill_gradebooks_source)) {

+ 76 - 69
main/inc/lib/image.lib.php

@@ -13,67 +13,69 @@ define('IMAGE_PROCESSOR', 'gd'); // imagick or gd strings
  */
  */
 class Image
 class Image
 {
 {
-	public $image_wrapper = null;
-
-	function __construct($path)
-	{
-		$path = preg_match(VALID_WEB_PATH, $path) ? (api_is_internal_path(
-			$path
-		) ? api_get_path(TO_SYS, $path) : $path) : $path;
-		if (IMAGE_PROCESSOR == 'gd') {
-			$this->image_wrapper = new GDWrapper($path);
-		} else {
-			if (class_exists('Imagick')) {
-				$this->image_wrapper = new ImagickWrapper($path);
-			} else {
-				Display::display_warning_message('Class Imagick not found');
-				exit;
-			}
-		}
-	}
+    public $image_wrapper = null;
 
 
-	public function resize(
-		$thumbw,
-		$thumbh,
-		$border = 0,
-		$specific_size = false
-	) {
-		$this->image_wrapper->resize($thumbw, $thumbh, $border, $specific_size);
-	}
+    function __construct($path)
+    {
+        $path = preg_match(VALID_WEB_PATH, $path) ? (api_is_internal_path(
+            $path
+        ) ? api_get_path(TO_SYS, $path) : $path) : $path;
+        if (IMAGE_PROCESSOR == 'gd') {
+            $this->image_wrapper = new GDWrapper($path);
+        } else {
+            if (class_exists('Imagick')) {
+                $this->image_wrapper = new ImagickWrapper($path);
+            } else {
+                Display::display_warning_message('Class Imagick not found');
+                exit;
+            }
+        }
+    }
 
 
-	public function send_image(
-		$file = '',
-		$compress = -1,
-		$convert_file_to = null
-	) {
-		return $this->image_wrapper->send_image(
-			$file,
-			$compress,
-			$convert_file_to
-		);
-	}
+    public function resize(
+        $thumbw,
+        $thumbh,
+        $border = 0,
+        $specific_size = false
+    ) {
+        $this->image_wrapper->resize($thumbw, $thumbh, $border, $specific_size);
+    }
 
 
-	public function get_image_size()
-	{
-		return $this->image_wrapper->get_image_size();
-	}
+    public function send_image(
+        $file = '',
+        $compress = -1,
+        $convert_file_to = null
+    ) {
+        return $this->image_wrapper->send_image(
+            $file,
+            $compress,
+            $convert_file_to
+        );
+    }
 
 
-	public function get_image_info()
-	{
-		return $this->image_wrapper->get_image_info();
-	}
+    public function get_image_size()
+    {
+        return $this->image_wrapper->get_image_size();
+    }
 
 
-	public function convert2bw()
-	{
-		$this->image_wrapper->convert2bw();
-	}
+    public function get_image_info()
+    {
+        return $this->image_wrapper->get_image_info();
+    }
+
+    public function convert2bw()
+    {
+        $this->image_wrapper->convert2bw();
+    }
 }
 }
 
 
 /**
 /**
  * Image wrapper class
  * Image wrapper class
+ *
  * @package chamilo.include.image
  * @package chamilo.include.image
  */
  */
-abstract class ImageWrapper {
+abstract class ImageWrapper
+{
     var $debug = true;
     var $debug = true;
     var $path;
     var $path;
     var $width;
     var $width;
@@ -82,7 +84,8 @@ abstract class ImageWrapper {
     var $allowed_extensions = array('jpeg', 'jpg', 'png', 'gif');
     var $allowed_extensions = array('jpeg', 'jpg', 'png', 'gif');
     var $image_validated = false;
     var $image_validated = false;
 
 
-    public function __construct($path) {
+    public function __construct($path)
+    {
         if (empty($path)) {
         if (empty($path)) {
             return false;
             return false;
         }
         }
@@ -95,11 +98,14 @@ abstract class ImageWrapper {
     abstract function get_image_size();
     abstract function get_image_size();
     abstract function resize($thumbw, $thumbh, $border, $specific_size = false);
     abstract function resize($thumbw, $thumbh, $border, $specific_size = false);
     abstract function send_image($file = '', $compress = -1, $convert_file_to = null);
     abstract function send_image($file = '', $compress = -1, $convert_file_to = null);
-    public function get_image_info() {
-        return array('width' => $this->width,
-        			'height' => $this->height,
-        			'type'   => $this->type
-                        );
+
+    public function get_image_info()
+    {
+        return array(
+            'width' => $this->width,
+            'height' => $this->height,
+            'type' => $this->type,
+        );
     }
     }
 }
 }
 
 
@@ -110,7 +116,8 @@ abstract class ImageWrapper {
  *
  *
  * @package chamilo.include.image
  * @package chamilo.include.image
  */
  */
-class ImagickWrapper extends ImageWrapper {
+class ImagickWrapper extends ImageWrapper
+{
     var $image;
     var $image;
     var $filter = Imagick::FILTER_LANCZOS;
     var $filter = Imagick::FILTER_LANCZOS;
 
 
@@ -118,21 +125,20 @@ class ImagickWrapper extends ImageWrapper {
           parent::__construct($path);
           parent::__construct($path);
     }
     }
     public function set_image_wrapper() {
     public function set_image_wrapper() {
-    	if ($this->debug) error_log('Image::set_image_wrapper loaded');
+        if ($this->debug) error_log('Image::set_image_wrapper loaded');
         try {
         try {
-        	if (file_exists($this->path)) {
-	            $this->image     = new Imagick($this->path);
-
-	            if ($this->image) {
-	                $this->fill_image_info(); //Fills height, width and type
-	            }
-        	} else {
-        		if ($this->debug) error_log('Image::image does not exist');
-        	}
+            if (file_exists($this->path)) {
+                $this->image     = new Imagick($this->path);
+
+                if ($this->image) {
+                    $this->fill_image_info(); //Fills height, width and type
+                }
+            } else {
+                if ($this->debug) error_log('Image::image does not exist');
+            }
         } catch(ImagickException $e) {
         } catch(ImagickException $e) {
             if ($this->debug) error_log($e->getMessage());
             if ($this->debug) error_log($e->getMessage());
         }
         }
-
     }
     }
 
 
     public function fill_image_info() {
     public function fill_image_info() {
@@ -215,7 +221,8 @@ class ImagickWrapper extends ImageWrapper {
  * php-gd wrapper
  * php-gd wrapper
  * @package chamilo.include.image
  * @package chamilo.include.image
  */
  */
-class GDWrapper extends ImageWrapper {
+class GDWrapper extends ImageWrapper
+{
     var $bg;
     var $bg;
 
 
     function __construct($path) {
     function __construct($path) {

+ 1 - 1
main/inc/lib/import.lib.php

@@ -63,7 +63,7 @@ class Import
 		if ($csvReader) {
 		if ($csvReader) {
 			$workflow = new Workflow($csvReader);
 			$workflow = new Workflow($csvReader);
 			$writer = new ArrayWriter($resultArray);
 			$writer = new ArrayWriter($resultArray);
-			$result = $workflow->addWriter($writer)->process();
+			$workflow->addWriter($writer)->process();
 		}
 		}
 
 
 		return $resultArray;
 		return $resultArray;

+ 46 - 63
main/inc/lib/legal.lib.php

@@ -8,7 +8,10 @@
  */
  */
 class LegalManager
 class LegalManager
 {
 {
-	private function __construct ()
+    /**
+     * Constructor
+     */
+	public function __construct()
     {
     {
 
 
 	}
 	}
@@ -101,7 +104,8 @@ class LegalManager
 		$language= Database::escape_string($language);
 		$language= Database::escape_string($language);
 		$sql = "SELECT * FROM $legal_conditions_table
 		$sql = "SELECT * FROM $legal_conditions_table
                 WHERE language_id = '".$language."'
                 WHERE language_id = '".$language."'
-                ORDER BY version DESC LIMIT 1 ";
+                ORDER BY version DESC
+                LIMIT 1 ";
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 
 
 		return Database::fetch_array($result);
 		return Database::fetch_array($result);
@@ -114,21 +118,22 @@ class LegalManager
 	 */
 	 */
 	public static function get_last_version($language)
 	public static function get_last_version($language)
     {
     {
-		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
-		$language= Database::escape_string($language);
-		$sql = "SELECT version FROM $legal_conditions_table
-		        WHERE language_id = '".$language."'
-		        ORDER BY version DESC LIMIT 1 ";
-		$result = Database::query($sql);
-		if (Database::num_rows($result)>0){
-			$version = Database::fetch_array($result);
-			$version = explode(':',$version[0]);
-
-			return $version[0];
-		} else {
+        $legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
+        $language = intval($language);
+        $sql = "SELECT version FROM $legal_conditions_table
+                WHERE language_id = '".$language."'
+                ORDER BY version DESC
+                LIMIT 1 ";
+        $result = Database::query($sql);
+        if (Database::num_rows($result)>0){
+            $version = Database::fetch_array($result);
+            $version = explode(':',$version[0]);
+
+            return $version[0];
+        } else {
 
 
-			return false;
-		}
+            return false;
+        }
 	}
 	}
 
 
 	/**
 	/**
@@ -139,55 +144,30 @@ class LegalManager
 	 */
 	 */
 	public static function show_last_condition($term_preview)
 	public static function show_last_condition($term_preview)
     {
     {
-		$preview = '';
-		switch ($term_preview['type']) {
-			/*// scroll box
-			case 0:
-				$preview ='<fieldset>
-					 <legend>'.get_lang('TermsAndConditions').'</legend>';
-				$preview .= '<div class="form-item">
-				<label>'.get_lang('TermsAndConditions').': </label>
-				<div class="resizable-textarea">
-				<span>
-				<textarea id="" class="form-textarea resizable textarea-processed" readonly="readonly" name="" rows="10" cols="60">';
-				$preview .= $term_preview['content'];
-				$preview .= '</textarea>
-				<div class="grippie" style="margin-right: -2px;"/>
-				</span>
-				</div>
-				</div>
-				<div id="edit-legal-accept-wrapper" class="form-item">
-				<label class="option" for="edit-legal-accept">
-				<input id="edit-legal-accept" class="form-checkbox" type="checkbox" value="1" name="legal_accept"/>
-						<strong>'.get_lang('Accept').'</strong>
-						'.get_lang('TermsAndConditions').'
-						</label>
-				</div>
-				</fieldset>';
-                break;*/
-            // HTML
-			case 0:
+        $preview = '';
+        switch ($term_preview['type']) {
+            case 0:
                 if (!empty($term_preview['content'])) {
                 if (!empty($term_preview['content'])) {
                     $preview = '<div class="legal-terms">'.$term_preview['content'].'</div><br />';
                     $preview = '<div class="legal-terms">'.$term_preview['content'].'</div><br />';
                 }
                 }
-				$preview .= get_lang('ByClickingRegisterYouAgreeTermsAndConditions');
+                $preview .= get_lang('ByClickingRegisterYouAgreeTermsAndConditions');
                 break;
                 break;
-			// Page link
-			case 1:
-				$preview ='<fieldset>
-							 <legend>'.get_lang('TermsAndConditions').'</legend>';
-				$preview .= '<div id="legal-accept-wrapper" class="form-item">
-				<label class="option" for="legal-accept">
-				<input id="legal-accept" type="checkbox" value="1" name="legal_accept"/>
-				'.get_lang('IHaveReadAndAgree').'
-				<a href="#">'.get_lang('TermsAndConditions').'</a>
-				</label>
-				</div>
-				</fieldset>';
+                // Page link
+            case 1:
+                $preview ='<fieldset>
+                             <legend>'.get_lang('TermsAndConditions').'</legend>';
+                $preview .= '<div id="legal-accept-wrapper" class="form-item">
+                <label class="option" for="legal-accept">
+                <input id="legal-accept" type="checkbox" value="1" name="legal_accept"/>
+                '.get_lang('IHaveReadAndAgree').'
+                <a href="#">'.get_lang('TermsAndConditions').'</a>
+                </label>
+                </div>
+                </fieldset>';
                 break;
                 break;
-			default:
+            default:
                 break;
                 break;
-		}
+        }
 		return 	$preview;
 		return 	$preview;
 	}
 	}
 
 
@@ -237,7 +217,9 @@ class LegalManager
 	public static function count()
 	public static function count()
     {
     {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
-		$sql = "SELECT count(*) as count_result FROM $legal_conditions_table ORDER BY legal_id DESC ";
+		$sql = "SELECT count(*) as count_result
+		        FROM $legal_conditions_table
+		        ORDER BY legal_id DESC ";
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		$url = Database::fetch_array($result,'ASSOC');
 		$url = Database::fetch_array($result,'ASSOC');
 		$result = $url['count_result'];
 		$result = $url['count_result'];
@@ -251,12 +233,13 @@ class LegalManager
 	 * @param int The language id
 	 * @param int The language id
 	 * @return int The current type of terms and conditions
 	 * @return int The current type of terms and conditions
 	 */
 	 */
-	public static function get_type_of_terms_and_conditions($legal_id,$language_id)
+	public static function get_type_of_terms_and_conditions($legal_id, $language_id)
     {
     {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$legal_id = intval($legal_id);
 		$legal_id = intval($legal_id);
-		$language_id = Database::escape_string($language_id);
-		$sql = 'SELECT type FROM '.$legal_conditions_table.' WHERE legal_id="'.$legal_id.'" AND language_id="'.$language_id.'"';
+		$language_id = intval($language_id);
+		$sql = 'SELECT type FROM '.$legal_conditions_table.'
+		        WHERE legal_id="'.$legal_id.'" AND language_id="'.$language_id.'"';
 		$rs = Database::query($sql);
 		$rs = Database::query($sql);
 
 
 		return Database::result($rs,0,'type');
 		return Database::result($rs,0,'type');

+ 1 - 1
main/inc/lib/link.lib.php

@@ -1313,7 +1313,7 @@ class Link extends Model
             $ipu = 'LinkAdded';
             $ipu = 'LinkAdded';
             $rv = 2; // 2 = new
             $rv = 2; // 2 = new
         }
         }
-        global $_course, $nameTools, $_user;
+        global $_course, $_user;
         api_item_property_update(
         api_item_property_update(
             $_course,
             $_course,
             TOOL_LINK,
             TOOL_LINK,

+ 6 - 15
main/inc/lib/login_redirection.class.php

@@ -1,27 +1,18 @@
 <?php
 <?php
+/* For licensing terms, see /license.txt */
 
 
 /**
 /**
  * When a user login, the function LoginRedirection::redirect is called.
  * When a user login, the function LoginRedirection::redirect is called.
  * When this function is called all user info has already been registered in $_user session variable
  * When this function is called all user info has already been registered in $_user session variable
  * */
  * */
-Class LoginRedirection {
-
+class LoginRedirection
+{
     //checks user status and redirect him through custom page if setting is enabled
     //checks user status and redirect him through custom page if setting is enabled
-    public static function redirect() {
-
+    public static function redirect()
+    {
         global $param;
         global $param;
         $param = isset($param) ? $param : '';
         $param = isset($param) ? $param : '';
         $redirect_url = '';
         $redirect_url = '';
-        /*
-          //If session request url is setted, we go there
-          if (!empty($_SESSION['request_uri'])) {
-          $req = $_SESSION['request_uri'];
-          unset($_SESSION['request_uri']);
-          header('location: '.$req);
-          exit();
-          }
-         */
-
         if (api_is_student() && !api_get_setting('student_page_after_login') == '') {
         if (api_is_student() && !api_get_setting('student_page_after_login') == '') {
             $redirect_url = html_entity_decode(api_get_setting('student_page_after_login'));
             $redirect_url = html_entity_decode(api_get_setting('student_page_after_login'));
             if ($redirect_url[0] == "/") {
             if ($redirect_url[0] == "/") {
@@ -60,4 +51,4 @@ Class LoginRedirection {
         exit();
         exit();
     }
     }
 
 
-}
+}

+ 64 - 29
main/inc/lib/message.lib.php

@@ -60,14 +60,15 @@ class MessageManager
 
 
     /**
     /**
      * Get the new messages for the current user from the database.
      * Get the new messages for the current user from the database.
+     * @return int
      */
      */
     public static function get_new_messages()
     public static function get_new_messages()
     {
     {
-        $table_message = Database::get_main_table(TABLE_MESSAGE);
+        $table = Database::get_main_table(TABLE_MESSAGE);
         if (!api_get_user_id()) {
         if (!api_get_user_id()) {
             return false;
             return false;
         }
         }
-        $sql = "SELECT * FROM $table_message
+        $sql = "SELECT * FROM $table
                 WHERE user_receiver_id=".api_get_user_id()." AND msg_status=".MESSAGE_STATUS_UNREAD;
                 WHERE user_receiver_id=".api_get_user_id()." AND msg_status=".MESSAGE_STATUS_UNREAD;
         $result = Database::query($sql);
         $result = Database::query($sql);
         $i = Database::num_rows($result);
         $i = Database::num_rows($result);
@@ -527,9 +528,9 @@ class MessageManager
             // delete attachment file
             // delete attachment file
             self::delete_message_attachment_file($id, $user_sender_id);
             self::delete_message_attachment_file($id, $user_sender_id);
             // delete message
             // delete message
-            $query = "UPDATE $table_message SET msg_status=3
+            $sql = "UPDATE $table_message SET msg_status=3
                     WHERE user_sender_id='$user_sender_id' AND id='$id'";
                     WHERE user_sender_id='$user_sender_id' AND id='$id'";
-            $result = Database::query($query);
+            $result = Database::query($sql);
 
 
             return $result;
             return $result;
         }
         }
@@ -626,9 +627,16 @@ class MessageManager
 
 
             if (!empty($group_id)) {
             if (!empty($group_id)) {
                 $userGroup = new UserGroup();
                 $userGroup = new UserGroup();
-                $path_user_info = $userGroup->get_group_picture_path_by_id($group_id, 'system', true);
+                $path_user_info = $userGroup->get_group_picture_path_by_id(
+                    $group_id,
+                    'system',
+                    true
+                );
             } else {
             } else {
-                $path_user_info['dir'] = UserManager::getUserPathById($message_uid, 'system');
+                $path_user_info['dir'] = UserManager::getUserPathById(
+                    $message_uid,
+                    'system'
+                );
             }
             }
 
 
             $path_message_attach = $path_user_info['dir'].'message_attachments/';
             $path_message_attach = $path_user_info['dir'].'message_attachments/';
@@ -643,8 +651,8 @@ class MessageManager
 
 
     /**
     /**
      * update messages by user id and message id
      * update messages by user id and message id
-     * @param  int		user id
-     * @param  int		message id
+     * @param  int		$user_id
+     * @param  int		$message_id
      * @return resource
      * @return resource
      */
      */
     public static function update_message($user_id, $message_id)
     public static function update_message($user_id, $message_id)
@@ -681,8 +689,8 @@ class MessageManager
 
 
     /**
     /**
      * get messages by user id and message id
      * get messages by user id and message id
-     * @param  int		user id
-     * @param  int		message id
+     * @param  int		$user_id
+     * @param  int		$message_id
      * @return array
      * @return array
      */
      */
     public static function get_message_by_user($user_id, $message_id)
     public static function get_message_by_user($user_id, $message_id)
@@ -752,6 +760,7 @@ class MessageManager
                 }
                 }
             }
             }
         }
         }
+
         return $data;
         return $data;
     }
     }
 
 
@@ -902,6 +911,7 @@ class MessageManager
                 WHERE msg_status=".MESSAGE_STATUS_OUTBOX." AND user_sender_id=".api_get_user_id();
                 WHERE msg_status=".MESSAGE_STATUS_OUTBOX." AND user_sender_id=".api_get_user_id();
         $sql_result = Database::query($sql);
         $sql_result = Database::query($sql);
         $result = Database::fetch_array($sql_result);
         $result = Database::fetch_array($sql_result);
+
         return $result['number_messages'];
         return $result['number_messages'];
     }
     }
 
 
@@ -1221,6 +1231,7 @@ class MessageManager
                 false
                 false
             );
             );
         }
         }
+
         return $html_messages;
         return $html_messages;
     }
     }
 
 
@@ -1248,8 +1259,6 @@ class MessageManager
         $query_vars = array('id' => $group_id, 'topic_id' => $topic_id, 'topics_page_nr' => 0);
         $query_vars = array('id' => $group_id, 'topic_id' => $topic_id, 'topics_page_nr' => 0);
 
 
         // Main message
         // Main message
-
-        $user_link = '';
         $links = '';
         $links = '';
         $main_content = '';
         $main_content = '';
 
 
@@ -1269,7 +1278,10 @@ class MessageManager
 
 
         $topic_page_nr = isset($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : null;
         $topic_page_nr = isset($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : null;
         $links.= '<div id="message-reply-link">';
         $links.= '<div id="message-reply-link">';
-        if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $main_message['user_sender_id'] == $current_user_id) {
+        if (($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
+            $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
+            $main_message['user_sender_id'] == $current_user_id
+        ) {
             $urlEdit = api_get_path(WEB_CODE_PATH);
             $urlEdit = api_get_path(WEB_CODE_PATH);
             $urlEdit .= 'social/message_for_group_form.inc.php?';
             $urlEdit .= 'social/message_for_group_form.inc.php?';
             $urlEdit .= http_build_query([
             $urlEdit .= http_build_query([
@@ -1320,13 +1332,12 @@ class MessageManager
                 'data-title' => get_lang('Reply')
                 'data-title' => get_lang('Reply')
             ]
             ]
         );
         );
-        
-        $links.= '&nbsp;&nbsp; &topics_page_nr='.$topic_page_nr.'&items_page_nr='.$items_page_nr.'&topic_id='.$main_message['id'].'" class="ajax btn" title="'.get_lang('Reply').'">';
-        $links.= Display :: return_icon('talk.png', get_lang('Reply')).'</a>';
+
         $links.= '</div>';
         $links.= '</div>';
 
 
         $userPicture = $user_sender_info['avatar'];
         $userPicture = $user_sender_info['avatar'];
-        $main_content.= '<div class="message-group-author"><img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
+        $main_content.= '<div class="message-group-author">
+                         <img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
         $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$main_message['user_sender_id'].'">'.$name.'&nbsp;</a>';
         $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$main_message['user_sender_id'].'">'.$name.'&nbsp;</a>';
 
 
         $date = '';
         $date = '';
@@ -1353,8 +1364,6 @@ class MessageManager
                     continue;
                     continue;
                 }
                 }
                 $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr']) ? intval($_GET['items_'.$topic['id'].'_page_nr']) : null;
                 $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr']) ? intval($_GET['items_'.$topic['id'].'_page_nr']) : null;
-
-                $user_link = '';
                 $links = '';
                 $links = '';
                 $html_items = '';
                 $html_items = '';
                 $user_sender_info = api_get_user_info($topic['user_sender_id']);
                 $user_sender_info = api_get_user_info($topic['user_sender_id']);
@@ -1406,9 +1415,22 @@ class MessageManager
             $options = array('hide_navigation' => false, 'per_page' => $items_per_page);
             $options = array('hide_navigation' => false, 'per_page' => $items_per_page);
             $visibility = array(true, true, true, false);
             $visibility = array(true, true, true, false);
 
 
-            $style_class = array('item' => array('class' => 'group_social_item'), 'main' => array('class' => 'group_social_grid'));
+            $style_class = array(
+                'item' => array('class' => 'group_social_item'),
+                'main' => array('class' => 'group_social_grid'),
+            );
             if (!empty($array_html_items)) {
             if (!empty($array_html_items)) {
-                $html .= Display::return_sortable_grid('items_'.$topic['id'], array(), $array_html_items, $options, $query_vars, null, $visibility, false, $style_class);
+                $html .= Display::return_sortable_grid(
+                    'items_'.$topic['id'],
+                    array(),
+                    $array_html_items,
+                    $options,
+                    $query_vars,
+                    null,
+                    $visibility,
+                    false,
+                    $style_class
+                );
             }
             }
         }
         }
         return $html;
         return $html;
@@ -1416,8 +1438,8 @@ class MessageManager
 
 
     /**
     /**
      * Add children to messages by id is used for nested view messages
      * Add children to messages by id is used for nested view messages
-     * @param array  rows of messages
-     * @return array new list adding the item children
+     * @param array  $rows rows of messages
+     * @return array $first_seed new list adding the item children
      */
      */
     public static function calculate_children($rows, $first_seed)
     public static function calculate_children($rows, $first_seed)
     {
     {
@@ -1430,6 +1452,7 @@ class MessageManager
         $sorted_rows = array(0 => array());
         $sorted_rows = array(0 => array());
         self::message_recursive_sort($rows, $sorted_rows, $first_seed);
         self::message_recursive_sort($rows, $sorted_rows, $first_seed);
         unset($sorted_rows[0]);
         unset($sorted_rows[0]);
+
         return $sorted_rows;
         return $sorted_rows;
     }
     }
 
 
@@ -1458,8 +1481,8 @@ class MessageManager
 
 
     /**
     /**
      * Sort date by desc from a multi-dimensional array
      * Sort date by desc from a multi-dimensional array
-     * @param array1  first array to compare
-     * @param array2  second array to compare
+     * @param array $array1  first array to compare
+     * @param array $array2  second array to compare
      * @return bool
      * @return bool
      */
      */
     public function order_desc_date($array1, $array2)
     public function order_desc_date($array1, $array2)
@@ -1532,7 +1555,7 @@ class MessageManager
         $form->addText('subject', get_lang('Subject'), false, ['id' => 'subject_id']);
         $form->addText('subject', get_lang('Subject'), false, ['id' => 'subject_id']);
         $form->addTextarea('content', get_lang('Message'), ['id' => 'content_id', 'rows' => '5']);
         $form->addTextarea('content', get_lang('Message'), ['id' => 'content_id', 'rows' => '5']);
 
 
-        return $form->return_form();
+        return $form->returnForm();
     }
     }
 
 
     /**
     /**
@@ -1544,7 +1567,6 @@ class MessageManager
     public static function generate_invitation_form($id, $params = array())
     public static function generate_invitation_form($id, $params = array())
     {
     {
         $form = new FormValidator('send_invitation');
         $form = new FormValidator('send_invitation');
-        //$form->addElement('text', 'subject', get_lang('Subject'), array('id' => 'subject_id'));
         $form->addTextarea('content', get_lang('AddPersonalMessage'), ['id' => 'content_invitation_id', 'rows' => 5]);
         $form->addTextarea('content', get_lang('AddPersonalMessage'), ['id' => 'content_invitation_id', 'rows' => 5]);
         return $form->return_form();
         return $form->return_form();
     }
     }
@@ -1593,7 +1615,14 @@ class MessageManager
         }
         }
 
 
         // display sortable table with messages of the current user
         // display sortable table with messages of the current user
-        $table = new SortableTable('message_inbox', array('MessageManager', 'get_number_of_messages'), array('MessageManager', 'get_message_data'), 3, 20, 'DESC');
+        $table = new SortableTable(
+            'message_inbox',
+            array('MessageManager', 'get_number_of_messages'),
+            array('MessageManager', 'get_message_data'),
+            3,
+            20,
+            'DESC'
+        );
         $table->set_header(0, '', false, array('style' => 'width:15px;'));
         $table->set_header(0, '', false, array('style' => 'width:15px;'));
         $table->set_header(1, get_lang('Messages'), false);
         $table->set_header(1, get_lang('Messages'), false);
         $table->set_header(2, get_lang('Date'), true, array('style' => 'width:180px;'));
         $table->set_header(2, get_lang('Date'), true, array('style' => 'width:180px;'));
@@ -1603,7 +1632,13 @@ class MessageManager
             $parameters['f'] = 'social';
             $parameters['f'] = 'social';
             $table->set_additional_parameters($parameters);
             $table->set_additional_parameters($parameters);
         }
         }
-        $table->set_form_actions(array('delete' => get_lang('DeleteSelectedMessages'),'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),'mark_as_read' => get_lang('MailMarkSelectedAsRead')));
+        $table->set_form_actions(
+            array(
+                'delete' => get_lang('DeleteSelectedMessages'),
+                'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
+                'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
+            )
+        );
         $html .= $table->return_table();
         $html .= $table->return_table();
         return $html;
         return $html;
     }
     }

+ 0 - 1
main/inc/lib/model.lib.php

@@ -214,7 +214,6 @@ class Model
     {
     {
         $params = $this->clean_parameters($params);
         $params = $this->clean_parameters($params);
 
 
-
         if ($this->is_course_model) {
         if ($this->is_course_model) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
                 $params['c_id'] = api_get_course_int_id();
                 $params['c_id'] = api_get_course_int_id();

+ 6 - 4
main/inc/lib/myspace.lib.php

@@ -133,8 +133,8 @@ class MySpace
         }
         }
 
 
         // protect data
         // protect data
-        $user_id     = intval($user_id);
-        $session_id  = intval($session_id);
+        $user_id = intval($user_id);
+        $session_id = intval($session_id);
         $new_course_list = array();
         $new_course_list = array();
         foreach ($course_list as $course_item) {
         foreach ($course_list as $course_item) {
             $courseInfo = api_get_course_info($course_item['code']);
             $courseInfo = api_get_course_info($course_item['code']);
@@ -1023,10 +1023,12 @@ class MySpace
     }
     }
     /**
     /**
      * Display a sortable table that contains an overview off all the access to a session
      * Display a sortable table that contains an overview off all the access to a session
+     * @deprecated seem not to be used
      * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
      * @author César Perales <cesar.perales@beeznest.com>, Beeznest Team
      * @version Chamilo 1.9.6
      * @version Chamilo 1.9.6
      */
      */
-    static function display_tracking_access_overview($sessionId = 0, $courseId = 0, $studentId = '', $profile = '', $date_from, $date_to) {
+    static function display_tracking_access_overview($sessionId = 0, $courseId = 0, $studentId = '', $profile = '', $date_from, $date_to)
+    {
         //The order is important you need to check the the $column variable in the model.ajax.php file
         //The order is important you need to check the the $column variable in the model.ajax.php file
         $columns = array(
         $columns = array(
             get_lang('LoginDate'),
             get_lang('LoginDate'),
@@ -1239,7 +1241,7 @@ class MySpace
      * Fills in course reporting data
      * Fills in course reporting data
      *
      *
      * @param integer course code
      * @param integer course code
-     * @param array $url_params additonal url parameters
+     * @param array $url_params additional url parameters
      * @param array $row the row information (the other columns)
      * @param array $row the row information (the other columns)
      * @return string html code
      * @return string html code
      */
      */

+ 41 - 52
main/inc/lib/nanogong.lib.php

@@ -37,7 +37,6 @@ class Nanogong
      */
      */
     public function create_user_folder()
     public function create_user_folder()
     {
     {
-
 		//COURSE123/exercises/session_id/exercise_id/question_id/user_id
 		//COURSE123/exercises/session_id/exercise_id/question_id/user_id
 		if (empty($this->store_path)) {
 		if (empty($this->store_path)) {
 			return false;
 			return false;
@@ -78,46 +77,45 @@ class Nanogong
      */
      */
     public function set_parameters($params = array())
     public function set_parameters($params = array())
     {
     {
+        // Setting course id
+        if (isset($params['course_id'])) {
+            $this->course_id = intval($params['course_id']);
+        } else {
+            $this->course_id = $params['course_id'] = api_get_course_int_id();
+        }
 
 
-		//Setting course id
-		if (isset($params['course_id'])) {
-			$this->course_id = intval($params['course_id']);
-		} else {
-			$this->course_id = $params['course_id'] = api_get_course_int_id();
-		}
-
-		//Setting course info
-		if (isset($this->course_id)) {
-			$this->course_info = api_get_course_info_by_id($this->course_id);
-		}
+        //Setting course info
+        if (isset($this->course_id)) {
+            $this->course_info = api_get_course_info_by_id($this->course_id);
+        }
 
 
-		//Setting session id
-		if (isset($params['session_id'])) {
-			$this->session_id = intval($params['session_id']);
-		} else {
-			$this->session_id = $params['session_id'] = api_get_session_id();
-		}
+        //Setting session id
+        if (isset($params['session_id'])) {
+            $this->session_id = intval($params['session_id']);
+        } else {
+            $this->session_id = $params['session_id'] = api_get_session_id();
+        }
 
 
-		//Setting user ids
-		if (isset($params['user_id'])) {
-			$this->user_id = intval($params['user_id']);
-		} else {
-			$this->user_id = $params['user_id'] = api_get_user_id();
-		}
+        //Setting user ids
+        if (isset($params['user_id'])) {
+            $this->user_id = intval($params['user_id']);
+        } else {
+            $this->user_id = $params['user_id'] = api_get_user_id();
+        }
 
 
-		//Setting user ids
-		if (isset($params['exercise_id'])) {
-			$this->exercise_id = intval($params['exercise_id']);
-		} else {
-			$this->exercise_id = 0;
-		}
+        //Setting user ids
+        if (isset($params['exercise_id'])) {
+            $this->exercise_id = intval($params['exercise_id']);
+        } else {
+            $this->exercise_id = 0;
+        }
 
 
-		//Setting user ids
-		if (isset($params['question_id'])) {
-			$this->question_id = intval($params['question_id']);
-		} else {
-			$this->question_id = 0;
-		}
+        //Setting user ids
+        if (isset($params['question_id'])) {
+            $this->question_id = intval($params['question_id']);
+        } else {
+            $this->question_id = 0;
+        }
 
 
 		$this->can_edit  = false;
 		$this->can_edit  = false;
 
 
@@ -130,15 +128,12 @@ class Nanogong
 		}
 		}
 
 
 		//Settings the params array
 		//Settings the params array
-		$this->params 			= $params;
-
-		$this->store_path 		= api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/exercises/';
-
+		$this->params = $params;
+		$this->store_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/exercises/';
 		$this->create_user_folder();
 		$this->create_user_folder();
-
-		$this->store_path 		= $this->store_path.implode('/', array($this->session_id, $this->exercise_id, $this->question_id, $this->user_id)).'/';
-		$this->filename 		= $this->generate_filename();
-		$this->store_filename 	= $this->store_path.$this->filename;
+		$this->store_path = $this->store_path.implode('/', array($this->session_id, $this->exercise_id, $this->question_id, $this->user_id)).'/';
+		$this->filename = $this->generate_filename();
+		$this->store_filename = $this->store_path.$this->filename;
 	}
 	}
 
 
     /**
     /**
@@ -240,8 +235,8 @@ class Nanogong
 				$attempt_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 				$attempt_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 				$sql = "SELECT filename FROM $attempt_table
 				$sql = "SELECT filename FROM $attempt_table
                         WHERE
                         WHERE
-                            exe_id 		= ".$this->params['exe_id']." AND
-                            user_id 	= ".$this->params['user_id']." AND
+                            exe_id = ".$this->params['exe_id']." AND
+                            user_id = ".$this->params['user_id']." AND
                             question_id = ".$this->params['question_id']." AND
                             question_id = ".$this->params['question_id']." AND
                             session_id 	= ".$this->params['session_id']." AND
                             session_id 	= ".$this->params['session_id']." AND
                             course_code = '".$this->course_info['code']."'
                             course_code = '".$this->course_info['code']."'
@@ -272,8 +267,6 @@ class Nanogong
 	 */
 	 */
     public function get_public_url($force_download = 0)
     public function get_public_url($force_download = 0)
     {
     {
-		//$params = $this->get_params(true);
-		//$url = api_get_path(WEB_AJAX_PATH).'nanogong.ajax.php?a=get_file&download='.$force_download.'&'.$params;
 		$params = $this->get_params();
 		$params = $this->get_params();
 		$filename = basename($this->load_filename_if_exists());
 		$filename = basename($this->load_filename_if_exists());
         $url = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/exercises/'.$params['session_id'].'/'.$params['exercise_id'].'/'.$params['question_id'].'/'.$params['user_id'].'/'.$filename;
         $url = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/exercises/'.$params['session_id'].'/'.$params['exercise_id'].'/'.$params['question_id'].'/'.$params['user_id'].'/'.$filename;
@@ -286,7 +279,6 @@ class Nanogong
 	 */
 	 */
 	public function upload_file($is_nano = false)
 	public function upload_file($is_nano = false)
 	{
 	{
-
 		if (!empty($_FILES)) {
 		if (!empty($_FILES)) {
 			$upload_ok = process_uploaded_file($_FILES['file'], false);
 			$upload_ok = process_uploaded_file($_FILES['file'], false);
 
 
@@ -413,7 +405,6 @@ class Nanogong
         return $html;
         return $html;
 	}
 	}
 
 
-
 	/*
 	/*
 	var filename = document.getElementById("audio_title").value+".wav";
 	var filename = document.getElementById("audio_title").value+".wav";
 	var filename = filename.replace(/\s/g, "_");//replace spaces by _
 	var filename = filename.replace(/\s/g, "_");//replace spaces by _
@@ -607,7 +598,6 @@ class Nanogong
 		$html .= '<a href="#" class="btn btn-default"  onclick="send_voice()" />'.get_lang('SendRecord').'</a>';
 		$html .= '<a href="#" class="btn btn-default"  onclick="send_voice()" />'.get_lang('SendRecord').'</a>';
 		$html .= '</form></div>';
 		$html .= '</form></div>';
 
 
-
         $html .= Display::url(get_lang('ProblemsRecordingUploadYourOwnAudioFile'), 'javascript:void(0)', array('onclick' => 'show_simple_upload_form();'));
         $html .= Display::url(get_lang('ProblemsRecordingUploadYourOwnAudioFile'), 'javascript:void(0)', array('onclick' => 'show_simple_upload_form();'));
 
 
 		$html .= '<br /><br /><div id="no_nanogong_div">';
 		$html .= '<br /><br /><div id="no_nanogong_div">';
@@ -665,7 +655,6 @@ class Nanogong
             . $params_string
             . $params_string
             . '&TB_iframe=true';
             . '&TB_iframe=true';
 
 
-        $html = '<br />';
         $html = Display::url(
         $html = Display::url(
             get_lang('RecordAnswer'),
             get_lang('RecordAnswer'),
             $url,
             $url,

+ 19 - 5
main/inc/lib/notebook.lib.php

@@ -173,20 +173,32 @@ class NotebookManager
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
         $sql = "DELETE FROM $t_notebook
         $sql = "DELETE FROM $t_notebook
-                WHERE c_id = $course_id AND notebook_id='" . intval($notebook_id) . "' AND user_id = '" . api_get_user_id() . "'";
+                WHERE
+                    c_id = $course_id AND
+                    notebook_id='" . intval($notebook_id) . "' AND
+                    user_id = '" . api_get_user_id() . "'";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $affected_rows = Database::affected_rows($result);
         $affected_rows = Database::affected_rows($result);
         if ($affected_rows != 1) {
         if ($affected_rows != 1) {
             return false;
             return false;
         }
         }
         //update item_property (delete)
         //update item_property (delete)
-        api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, intval($notebook_id), 'delete', api_get_user_id());
+        api_item_property_update(
+            api_get_course_info(),
+            TOOL_NOTEBOOK,
+            intval($notebook_id),
+            'delete',
+            api_get_user_id()
+        );
         return true;
         return true;
     }
     }
 
 
+    /**
+     * Display notes
+     */
     static function display_notes()
     static function display_notes()
     {
     {
-        global $_user;
+        $_user = api_get_user_info();
         if (!isset($_GET['direction'])) {
         if (!isset($_GET['direction'])) {
             $sort_direction = 'ASC';
             $sort_direction = 'ASC';
             $link_sort_direction = 'DESC';
             $link_sort_direction = 'DESC';
@@ -202,9 +214,11 @@ class NotebookManager
         echo '<div class="actions">';
         echo '<div class="actions">';
         if (!api_is_anonymous()) {
         if (!api_is_anonymous()) {
             if (api_get_session_id() == 0)
             if (api_get_session_id() == 0)
-                echo '<a href="index.php?' . api_get_cidreq() . '&action=addnote">' . Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';
+                echo '<a href="index.php?' . api_get_cidreq() . '&action=addnote">' .
+                    Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';
             elseif (api_is_allowed_to_session_edit(false, true)) {
             elseif (api_is_allowed_to_session_edit(false, true)) {
-                echo '<a href="index.php?' . api_get_cidreq() . '&action=addnote">' . Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';
+                echo '<a href="index.php?' . api_get_cidreq() . '&action=addnote">' .
+                    Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';
             }
             }
         } else {
         } else {
             echo '<a href="javascript:void(0)">' . Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';
             echo '<a href="javascript:void(0)">' . Display::return_icon('new_note.png', get_lang('NoteAddNew'), '', '32') . '</a>';

+ 34 - 42
main/inc/lib/online.inc.php

@@ -19,33 +19,34 @@
 
 
 use ChamiloSession as Session;
 use ChamiloSession as Session;
 
 
-function LoginCheck($uid) {
-	$_course = api_get_course_info();
-	$uid = (int) $uid;
-	$online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+function LoginCheck($uid)
+{
+    $_course = api_get_course_info();
+    $uid = (int) $uid;
+    $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     if (!empty($uid)) {
     if (!empty($uid)) {
         $user_ip = '';
         $user_ip = '';
         if (!empty($_SERVER['REMOTE_ADDR'])) {
         if (!empty($_SERVER['REMOTE_ADDR'])) {
             $user_ip = Database::escape_string(api_get_real_ip());
             $user_ip = Database::escape_string(api_get_real_ip());
         }
         }
 
 
-		$login_date = api_get_utc_datetime();
-		$access_url_id = 1;
-		if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
-			$access_url_id = api_get_current_access_url_id();
-		}
-		$session_id = api_get_session_id();
-		// if the $_course array exists this means we are in a course and we have to store this in the who's online table also
-		// to have the x users in this course feature working
-		if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
+        $login_date = api_get_utc_datetime();
+        $access_url_id = 1;
+        if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
+            $access_url_id = api_get_current_access_url_id();
+        }
+        $session_id = api_get_session_id();
+        // if the $_course array exists this means we are in a course and we have to store this in the who's online table also
+        // to have the x users in this course feature working
+        if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
             $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
             $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
-            		  VALUES ($uid,$uid,'$login_date','$user_ip', '".$_course['real_id']."' , '$session_id' , '$access_url_id' )";
-		} else {
+                      VALUES ($uid,$uid,'$login_date','$user_ip', '".$_course['real_id']."' , '$session_id' , '$access_url_id' )";
+        } else {
             $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, session_id, access_url_id)
             $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, session_id, access_url_id)
                       VALUES ($uid,$uid,'$login_date','$user_ip', '$session_id', '$access_url_id')";
                       VALUES ($uid,$uid,'$login_date','$user_ip', '$session_id', '$access_url_id')";
-		}
-		@Database::query($query);
-	}
+        }
+        Database::query($query);
+    }
 }
 }
 
 
 /**
 /**
@@ -53,7 +54,6 @@ function LoginCheck($uid) {
  */
  */
 function preventMultipleLogin($userId)
 function preventMultipleLogin($userId)
 {
 {
-    global $_configuration;
     $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $userId = intval($userId);
     $userId = intval($userId);
 
 
@@ -93,7 +93,8 @@ function preventMultipleLogin($userId)
  * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
  * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
  * @author Fernando P. García <fernando@develcuy.com>
  * @author Fernando P. García <fernando@develcuy.com>
  */
  */
-function online_logout($user_id = null, $logout_redirect = false) {
+function online_logout($user_id = null, $logout_redirect = false)
+{
     global $extAuthSource;
     global $extAuthSource;
 
 
     // Database table definition
     // Database table definition
@@ -178,13 +179,13 @@ function LoginDelete($user_id)
 function user_is_online($user_id)
 function user_is_online($user_id)
 {
 {
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
+	$table_user = Database::get_main_table(TABLE_MAIN_USER);
 
 
-	$access_url_id		= api_get_current_access_url_id();
-	$time_limit			= api_get_setting('time_limit_whosonline');
+	$access_url_id = api_get_current_access_url_id();
+	$time_limit = api_get_setting('time_limit_whosonline');
 
 
-    $online_time 	= time() - $time_limit*60;
-    $limit_date		= api_get_utc_datetime($online_time);
+    $online_time = time() - $time_limit*60;
+    $limit_date = api_get_utc_datetime($online_time);
     $user_id = intval($user_id);
     $user_id = intval($user_id);
 
 
 	$query = " SELECT login_user_id,login_date
 	$query = " SELECT login_user_id,login_date
@@ -207,8 +208,8 @@ function user_is_online($user_id)
  * Gives a list of people online now (and in the last $valid minutes)
  * Gives a list of people online now (and in the last $valid minutes)
  * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
  * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
  */
  */
-function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false) {
-
+function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false)
+{
     // Time limit in seconds?
     // Time limit in seconds?
     if (empty($time_limit)) {
     if (empty($time_limit)) {
         $time_limit = api_get_setting('time_limit_whosonline');
         $time_limit = api_get_setting('time_limit_whosonline');
@@ -216,7 +217,7 @@ function who_is_online($from, $number_of_items, $column = null, $direction = nul
         $time_limit = intval($time_limit);
         $time_limit = intval($time_limit);
     }
     }
 
 
-    $from            = intval($from);
+    $from = intval($from);
     $number_of_items = intval($number_of_items);
     $number_of_items = intval($number_of_items);
 
 
     if (empty($column)) {
     if (empty($column)) {
@@ -234,12 +235,11 @@ function who_is_online($from, $number_of_items, $column = null, $direction = nul
         }
         }
     }
     }
 
 
-    $online_time 		= time() - $time_limit*60;
-	$current_date		= api_get_utc_datetime($online_time);
+    $online_time = time() - $time_limit * 60;
+    $current_date = api_get_utc_datetime($online_time);
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
 	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
 	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
 	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
-	$query              = '';
 
 
 	if ($friends) {
 	if ($friends) {
 		// 	who friends from social network is online
 		// 	who friends from social network is online
@@ -318,9 +318,6 @@ function who_is_online_count($time_limit = null, $friends = false)
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
 	$friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
 	$friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
 	$table_user = Database::get_main_table(TABLE_MAIN_USER);
 	$table_user = Database::get_main_table(TABLE_MAIN_USER);
-
-	$query = '';
-
 	$online_time = time() - $time_limit * 60;
 	$online_time = time() - $time_limit * 60;
 	$current_date = api_get_utc_datetime($online_time);
 	$current_date = api_get_utc_datetime($online_time);
 
 
@@ -414,16 +411,10 @@ function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit
 
 
 	$result = Database::query($query);
 	$result = Database::query($query);
 	if ($result) {
 	if ($result) {
-        /*$valid_date_time = new DateTime();
-        $diff = "PT".$time_limit.'M';
-        $valid_date_time->sub(new DateInterval($diff));*/
 		$users_online = array();
 		$users_online = array();
 
 
 		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
 		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
-            /*$user_login_date = new DateTime($login_date);
-			if ($user_login_date > $valid_date_time->format('Y-m-d H:i:s')) {*/
-				$users_online[] = $login_user_id;
-			//}
+            $users_online[] = $login_user_id;
 		}
 		}
 		return $users_online;
 		return $users_online;
 	} else {
 	} else {
@@ -487,7 +478,8 @@ function GetFullUserName($uid) {
  * @return  string  An HTML-formatted message
  * @return  string  An HTML-formatted message
  */
  */
 function chatcall() {
 function chatcall() {
-	global $_user, $_cid;
+    $_cid = api_get_course_id();
+    $_user = api_get_user_info();
 
 
 	if (!$_user['user_id']) {
 	if (!$_user['user_id']) {
 		return (false);
 		return (false);

+ 0 - 1
main/inc/lib/pdf.lib.php

@@ -76,7 +76,6 @@ class PDF
      */
      */
     public function html_to_pdf_with_template($content, $saveToFile = false, $returnHtml = false)
     public function html_to_pdf_with_template($content, $saveToFile = false, $returnHtml = false)
     {
     {
-        global $_configuration;
         Display :: display_no_header();
         Display :: display_no_header();
 
 
         // Assignments
         // Assignments

+ 15 - 13
main/inc/lib/plugin.class.php

@@ -70,13 +70,13 @@ class Plugin
     public function get_info()
     public function get_info()
     {
     {
         $result = array();
         $result = array();
-        $result['title']            = $this->get_title();
-        $result['comment']          = $this->get_comment();
-        $result['version']          = $this->get_version();
-        $result['author']           = $this->get_author();
-        $result['plugin_class']     = get_class($this);
+        $result['title'] = $this->get_title();
+        $result['comment'] = $this->get_comment();
+        $result['version'] = $this->get_version();
+        $result['author'] = $this->get_author();
+        $result['plugin_class'] = get_class($this);
         $result['is_course_plugin'] = $this->isCoursePlugin;
         $result['is_course_plugin'] = $this->isCoursePlugin;
-        $result['is_mail_plugin']   = $this->isMailPlugin;
+        $result['is_mail_plugin'] = $this->isMailPlugin;
 
 
         if ($form = $this->get_settings_form()) {
         if ($form = $this->get_settings_form()) {
             $result['settings_form'] = $form;
             $result['settings_form'] = $form;
@@ -88,6 +88,7 @@ class Plugin
                 $result[$name] = $value;
                 $result[$name] = $value;
             }
             }
         }
         }
+
         return $result;
         return $result;
     }
     }
 
 
@@ -489,6 +490,7 @@ class Plugin
      * Delete the fields added to the course settings page and the link to the
      * Delete the fields added to the course settings page and the link to the
      * tool on the course's homepage
      * tool on the course's homepage
      * @param int $courseId
      * @param int $courseId
+     *
      * @return void
      * @return void
      */
      */
     public function uninstall_course_fields($courseId)
     public function uninstall_course_fields($courseId)
@@ -548,7 +550,8 @@ class Plugin
     {
     {
         // Update existing courses to add conference settings
         // Update existing courses to add conference settings
         $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
         $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
-        $sql = "SELECT id FROM $t_courses ORDER BY id";
+        $sql = "SELECT id FROM $t_courses
+                ORDER BY id";
         $res = Database::query($sql);
         $res = Database::query($sql);
         while ($row = Database::fetch_assoc($res)) {
         while ($row = Database::fetch_assoc($res)) {
             $this->uninstall_course_fields($row['id']);
             $this->uninstall_course_fields($row['id']);
@@ -598,9 +601,9 @@ class Plugin
     public function addTab($tabName, $url)
     public function addTab($tabName, $url)
     {
     {
         $sql = "SELECT * FROM settings_current
         $sql = "SELECT * FROM settings_current
-            WHERE
-            variable = 'show_tabs' AND
-            subkey like 'custom_tab_%'";
+                WHERE
+                    variable = 'show_tabs' AND
+                    subkey LIKE 'custom_tab_%'";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $customTabsNum = Database::num_rows($result);
         $customTabsNum = Database::num_rows($result);
 
 
@@ -610,7 +613,6 @@ class Plugin
         $tabNameNoSpaces = preg_replace('/\s+/', '', $tabName);
         $tabNameNoSpaces = preg_replace('/\s+/', '', $tabName);
         $subkeytext = "Tabs" . $tabNameNoSpaces;
         $subkeytext = "Tabs" . $tabNameNoSpaces;
 
 
-
         //Check if it is already added
         //Check if it is already added
         $checkCondition = array(
         $checkCondition = array(
             'where' =>
             'where' =>
@@ -714,8 +716,8 @@ class Plugin
 
 
     /**
     /**
      * This method shows or hides plugin's tab
      * This method shows or hides plugin's tab
-     * @param boolean Shows or hides the main menu plugin tab
-     * @param string Plugin starter file path
+     * @param boolean $showTab Shows or hides the main menu plugin tab
+     * @param string $filePath Plugin starter file path
      */
      */
     public function manageTab($showTab, $filePath = 'index.php')
     public function manageTab($showTab, $filePath = 'index.php')
     {
     {

+ 1 - 0
main/inc/lib/plugin.lib.php

@@ -453,6 +453,7 @@ class AppPlugin
     /**
     /**
      * Get the template list
      * Get the template list
      * @param  string $pluginName
      * @param  string $pluginName
+     *
      * @return bool
      * @return bool
      */
      */
     public function get_templates_list($pluginName)
     public function get_templates_list($pluginName)

+ 3 - 1
main/inc/lib/promotion.lib.php

@@ -176,7 +176,6 @@ class Promotion extends Model
 
 
     /**
     /**
      * Returns a Form validator Obj
      * Returns a Form validator Obj
-     * @todo the form should be auto generated
      * @param   string $url
      * @param   string $url
      * @param   string $action
      * @param   string $action
      *
      *
@@ -251,6 +250,7 @@ class Promotion extends Model
      * @param array $params
      * @param array $params
      *
      *
      * @param bool $show_query
      * @param bool $show_query
+     *
      * @return bool
      * @return bool
      */
      */
     public function save($params, $show_query = false)
     public function save($params, $show_query = false)
@@ -265,11 +265,13 @@ class Promotion extends Model
                 api_get_user_id()
                 api_get_user_id()
             );
             );
         }
         }
+
         return $id;
         return $id;
     }
     }
 
 
     /**
     /**
      * @param int $id
      * @param int $id
+     *
      * @return bool
      * @return bool
      */
      */
     public function delete($id)
     public function delete($id)

+ 5 - 1
main/inc/lib/skill.lib.php

@@ -34,7 +34,7 @@ class SkillProfile extends Model
 
 
     /**
     /**
     * This function is for editing profile info from profile_id.
     * This function is for editing profile info from profile_id.
-    * @param int $profileId
+    * @param int    $profileId
     * @param string $name
     * @param string $name
     * @param string $description
     * @param string $description
     */
     */
@@ -71,6 +71,7 @@ class SkillProfile extends Model
                 return $profile_id;
                 return $profile_id;
             }
             }
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -139,6 +140,7 @@ class SkillRelProfile extends Model
                 WHERE p.profile_id = ".intval($profileId);
                 WHERE p.profile_id = ".intval($profileId);
         $result = Database::query($sql);
         $result = Database::query($sql);
         $profileData = Database::fetch_array($result, 'ASSOC');
         $profileData = Database::fetch_array($result, 'ASSOC');
+
         return $profileData;
         return $profileData;
     }
     }
 }
 }
@@ -270,6 +272,7 @@ class SkillRelSkill extends Model
         if ($result) {
         if ($result) {
             return true;
             return true;
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -284,6 +287,7 @@ class SkillRelSkill extends Model
             'all',
             'all',
             array('where' => array('skill_id = ? AND parent_id = ?' => array($skill_id, $parent_id)))
             array('where' => array('skill_id = ? AND parent_id = ?' => array($skill_id, $parent_id)))
         );
         );
+
         if (!empty($result)) {
         if (!empty($result)) {
             return true;
             return true;
         }
         }

+ 10 - 18
main/inc/lib/social.lib.php

@@ -221,9 +221,9 @@ class SocialManager extends UserManager
             return true;
             return true;
         } else {
         } else {
             // invitation already exist
             // invitation already exist
-            $sql_if_exist = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
-                             WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
-            $res_if_exist = Database::query($sql_if_exist);
+            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
+                    WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
+            $res_if_exist = Database::query($sql);
             $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
             $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
             if ($row_if_exist['count'] == 1) {
             if ($row_if_exist['count'] == 1) {
                 $sql = 'UPDATE '.$tbl_message.' SET
                 $sql = 'UPDATE '.$tbl_message.' SET
@@ -296,6 +296,7 @@ class SocialManager extends UserManager
         while ($row = Database::fetch_array($res, 'ASSOC')) {
         while ($row = Database::fetch_array($res, 'ASSOC')) {
             $list_friend_invitation[$row['user_receiver_id']] = $row;
             $list_friend_invitation[$row['user_receiver_id']] = $row;
         }
         }
+
         return $list_friend_invitation;
         return $list_friend_invitation;
     }
     }
 
 
@@ -1134,14 +1135,8 @@ class SocialManager extends UserManager
             'content' => $cleanMessageContent,
             'content' => $cleanMessageContent,
             'parent_id' => $messageId
             'parent_id' => $messageId
         );
         );
-        return Database::insert($tblMessage, $attributes);
-
-        /* Deprecated since 2014-10-29
-        $senderInfo = api_get_user_info($userId);
-        $notification = new Notification();
-        $notification->save_notification(Notification::NOTIFICATION_TYPE_WALL_MESSAGE, array($friendId), '', $messageContent, $senderInfo);
-        */
 
 
+        return Database::insert($tblMessage, $attributes);
     }
     }
 
 
     /**
     /**
@@ -1155,7 +1150,6 @@ class SocialManager extends UserManager
      */
      */
     public static function sendWallMessageAttachmentFile($userId, $fileAttach, $messageId, $fileComment = '')
     public static function sendWallMessageAttachmentFile($userId, $fileAttach, $messageId, $fileComment = '')
     {
     {
-        $flag = false;
         $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
         $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
 
         // create directory
         // create directory
@@ -1222,15 +1216,15 @@ class SocialManager extends UserManager
         }
         }
 
 
         $tblMessage = Database::get_main_table(TABLE_MESSAGE);
         $tblMessage = Database::get_main_table(TABLE_MESSAGE);
-        $tblMessageAttachement = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
+        $tblMessageAttachment = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
 
         $userId = intval($userId);
         $userId = intval($userId);
         $start = Database::escape_string($start);
         $start = Database::escape_string($start);
         $limit = intval($limit);
         $limit = intval($limit);
 
 
         $sql = "SELECT id, user_sender_id,user_receiver_id, send_date, content, parent_id,
         $sql = "SELECT id, user_sender_id,user_receiver_id, send_date, content, parent_id,
-          (SELECT ma.path FROM $tblMessageAttachement ma WHERE  ma.message_id = tm.id ) as path,
-          (SELECT ma.filename FROM $tblMessageAttachement ma WHERE  ma.message_id = tm.id ) as filename
+          (SELECT ma.path FROM $tblMessageAttachment ma WHERE  ma.message_id = tm.id ) as path,
+          (SELECT ma.filename FROM $tblMessageAttachment ma WHERE  ma.message_id = tm.id ) as filename
             FROM $tblMessage tm
             FROM $tblMessage tm
             WHERE user_receiver_id = $userId
             WHERE user_receiver_id = $userId
                 AND send_date > '$start' ";
                 AND send_date > '$start' ";
@@ -1518,6 +1512,7 @@ class SocialManager extends UserManager
         $tblMessage = Database::get_main_table(TABLE_MESSAGE);
         $tblMessage = Database::get_main_table(TABLE_MESSAGE);
         $statusMessage = MESSAGE_STATUS_WALL_DELETE;
         $statusMessage = MESSAGE_STATUS_WALL_DELETE;
         $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
         $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
+
         return Database::query($sql);
         return Database::query($sql);
     }
     }
 
 
@@ -1563,12 +1558,10 @@ class SocialManager extends UserManager
             $template->assign('gamification_points', $gamificationPoints);
             $template->assign('gamification_points', $gamificationPoints);
         }
         }
         $chatEnabled = api_is_global_chat_enabled();
         $chatEnabled = api_is_global_chat_enabled();
-        $templateName = $template->assign('chat_enabled', $chatEnabled);
-
+        $template->assign('chat_enabled', $chatEnabled);
         $templateName = $template->get_template('social/user_block.tpl');
         $templateName = $template->get_template('social/user_block.tpl');
 
 
         if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
         if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
-
             $templateName = $template->get_template('social/group_block.tpl');
             $templateName = $template->get_template('social/group_block.tpl');
         }
         }
 
 
@@ -1770,5 +1763,4 @@ class SocialManager extends UserManager
 
 
         return $template->fetch($skillBlock);
         return $template->fetch($skillBlock);
     }
     }
-
 }
 }

+ 147 - 86
main/inc/lib/specific_fields_manager.lib.php

@@ -3,9 +3,7 @@
  * Manage specific tools
  * Manage specific tools
  * @package chamilo.library
  * @package chamilo.library
  */
  */
-/**
- * Code
- */
+
 // Database table definitions
 // Database table definitions
 $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
 $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
 $table_sf_val   = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
 $table_sf_val   = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
@@ -14,41 +12,44 @@ $table_sf_val   = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
  * Add a specific field
  * Add a specific field
  * @param string $name specific field name
  * @param string $name specific field name
  */
  */
-function add_specific_field($name) {
-  $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
-  $name = trim($name);
-  if (empty($name)) {
-    return FALSE;
-  }
-  $sql = 'INSERT INTO %s(id, code, name) VALUES(NULL, \'%s\', \'%s\')';
-  $_safe_name = Database::escape_string($name);
-  $_safe_code = substr($_safe_name,0,1);
-  $_safe_code = get_specific_field_code_from_name($_safe_code);
-  if ($_safe_code === false) { return false; }
-  $sql = sprintf($sql, $table_sf, $_safe_code, $_safe_name);
-  $result = Database::query($sql);
-  if ($result) {
-    return Database::insert_id();
-  }
-  else {
-    return FALSE;
-  }
+function add_specific_field($name)
+{
+    $table_sf = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $name = trim($name);
+    if (empty($name)) {
+        return false;
+    }
+    $sql = 'INSERT INTO %s(id, code, name) VALUES(NULL, \'%s\', \'%s\')';
+    $_safe_name = Database::escape_string($name);
+    $_safe_code = substr($_safe_name, 0, 1);
+    $_safe_code = get_specific_field_code_from_name($_safe_code);
+    if ($_safe_code === false) {
+        return false;
+    }
+    $sql = sprintf($sql, $table_sf, $_safe_code, $_safe_name);
+    $result = Database::query($sql);
+    if ($result) {
+        return Database::insert_id();
+    } else {
+        return false;
+    }
 }
 }
 
 
 /**
 /**
  * Delete a specific field
  * Delete a specific field
  * @param int $id specific field id
  * @param int $id specific field id
  */
  */
-function delete_specific_field($id) {
-  $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
-  $id = (int)$id;
-  if (!is_numeric($id)) {
-    return FALSE;
-  }
-  $sql = 'DELETE FROM %s WHERE id=%s LIMIT 1';
-  $sql = sprintf($sql, $table_sf, $id);
-  $result = Database::query($sql);
-  //TODO also delete the corresponding values
+function delete_specific_field($id)
+{
+    $table_sf = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $id = (int)$id;
+    if (!is_numeric($id)) {
+        return false;
+    }
+    $sql = 'DELETE FROM %s WHERE id=%s LIMIT 1';
+    $sql = sprintf($sql, $table_sf, $id);
+    Database::query($sql);
+    //TODO also delete the corresponding values
 }
 }
 
 
 /**
 /**
@@ -56,15 +57,16 @@ function delete_specific_field($id) {
  * @param int $id specific field id
  * @param int $id specific field id
  * @param string $name new field name
  * @param string $name new field name
  */
  */
-function edit_specific_field($id, $name) {
-  $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
-  $id = (int)$id;
-  if (!is_numeric($id)) {
-    return FALSE;
-  }
-  $sql = 'UPDATE %s SET name = \'%s\' WHERE id = %s LIMIT 1';
-  $sql = sprintf($sql, $table_sf, $name, $id);
-  $result = Database::query($sql);
+function edit_specific_field($id, $name)
+{
+    $table_sf = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $id = (int)$id;
+    if (!is_numeric($id)) {
+        return false;
+    }
+    $sql = 'UPDATE %s SET name = \'%s\' WHERE id = %s LIMIT 1';
+    $sql = sprintf($sql, $table_sf, $name, $id);
+    $result = Database::query($sql);
 }
 }
 
 
 /**
 /**
@@ -72,27 +74,28 @@ function edit_specific_field($id, $name) {
  * @param array $order_by a list of fields on which to sort
  * @param array $order_by a list of fields on which to sort
  * @return array An array with all specific fields, at platform level
  * @return array An array with all specific fields, at platform level
  */
  */
-function get_specific_field_list($conditions = array(), $order_by = array()) {
-  $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
-  $return_array = array();
-  $sql = "SELECT * FROM $table_sf";
-  if (count($conditions) > 0) {
-    $sql .= ' WHERE ';
-    $conditions_string_array = array();
-    foreach ($conditions as $field => $value) {
-      $conditions_string_array[] = $field.' = '. $value;
-    }
-    $sql .= implode(' AND ', $conditions_string_array);
-  }
-  if (count($order_by) > 0) {
-    $sql .= ' ORDER BY '.implode(',',$order_by);
-  }
-  $sql_result = Database::query($sql);
-  while ($result = Database::fetch_array($sql_result)) {
-    $return_array[] = $result;
-  }
-
-  return $return_array;
+function get_specific_field_list($conditions = array(), $order_by = array())
+{
+    $table_sf = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $return_array = array();
+    $sql = "SELECT * FROM $table_sf";
+    if (count($conditions) > 0) {
+        $sql .= ' WHERE ';
+        $conditions_string_array = array();
+        foreach ($conditions as $field => $value) {
+            $conditions_string_array[] = $field.' = '.$value;
+        }
+        $sql .= implode(' AND ', $conditions_string_array);
+    }
+    if (count($order_by) > 0) {
+        $sql .= ' ORDER BY '.implode(',', $order_by);
+    }
+    $sql_result = Database::query($sql);
+    while ($result = Database::fetch_array($sql_result)) {
+        $return_array[] = $result;
+    }
+
+    return $return_array;
 }
 }
 
 
 /**
 /**
@@ -100,8 +103,11 @@ function get_specific_field_list($conditions = array(), $order_by = array()) {
  * @param array $order_by a list of fields on which sort
  * @param array $order_by a list of fields on which sort
  * @return array An array with all users of the platform.
  * @return array An array with all users of the platform.
  */
  */
-function get_specific_field_values_list($conditions = array(), $order_by = array()) {
-    $table_sfv     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
+function get_specific_field_values_list(
+    $conditions = array(),
+    $order_by = array()
+) {
+    $table_sfv = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
     $return_array = array();
     $return_array = array();
     $sql = "SELECT * FROM $table_sfv";
     $sql = "SELECT * FROM $table_sfv";
     if (count($conditions) > 0) {
     if (count($conditions) > 0) {
@@ -120,17 +126,18 @@ function get_specific_field_values_list($conditions = array(), $order_by = array
 
 
         $conditions_string_array = array();
         $conditions_string_array = array();
         foreach ($conditions as $field => $value) {
         foreach ($conditions as $field => $value) {
-            $conditions_string_array[] = $field.' = '. $value;
+            $conditions_string_array[] = $field.' = '.$value;
         }
         }
         $sql .= implode(' AND ', $conditions_string_array);
         $sql .= implode(' AND ', $conditions_string_array);
     }
     }
     if (count($order_by) > 0) {
     if (count($order_by) > 0) {
-        $sql .= ' ORDER BY '.implode(',',$order_by);
+        $sql .= ' ORDER BY '.implode(',', $order_by);
     }
     }
     $sql_result = Database::query($sql);
     $sql_result = Database::query($sql);
     while ($result = Database::fetch_array($sql_result)) {
     while ($result = Database::fetch_array($sql_result)) {
         $return_array[] = $result;
         $return_array[] = $result;
     }
     }
+
     return $return_array;
     return $return_array;
 }
 }
 
 
@@ -141,17 +148,31 @@ function get_specific_field_values_list($conditions = array(), $order_by = array
  * @param int $ref_id representative id inside one tool item
  * @param int $ref_id representative id inside one tool item
  * @return array
  * @return array
  */
  */
-function get_specific_field_values_list_by_prefix($prefix, $course_code, $tool_id, $ref_id) {
-  $table_sf = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
-  $table_sfv = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
-  $sql = 'SELECT sfv.value FROM %s sf LEFT JOIN %s sfv ON sf.id = sfv.field_id' .
-         ' WHERE sf.code = \'%s\' AND sfv.c_id = \'%s\' AND tool_id = \'%s\' AND sfv.ref_id = %s';
-  $sql = sprintf($sql, $table_sf, $table_sfv, $prefix, $course_code, $tool_id, $ref_id);
-  $sql_result = Database::query($sql);
-  while ($result = Database::fetch_array($sql_result)) {
-    $return_array[] = $result;
-  }
-  return $return_array;
+function get_specific_field_values_list_by_prefix(
+    $prefix,
+    $course_code,
+    $tool_id,
+    $ref_id
+) {
+    $table_sf = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $table_sfv = Database:: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
+    $sql = 'SELECT sfv.value FROM %s sf LEFT JOIN %s sfv ON sf.id = sfv.field_id'.
+        ' WHERE sf.code = \'%s\' AND sfv.c_id = \'%s\' AND tool_id = \'%s\' AND sfv.ref_id = %s';
+    $sql = sprintf(
+        $sql,
+        $table_sf,
+        $table_sfv,
+        $prefix,
+        $course_code,
+        $tool_id,
+        $ref_id
+    );
+    $sql_result = Database::query($sql);
+    while ($result = Database::fetch_array($sql_result)) {
+        $return_array[] = $result;
+    }
+
+    return $return_array;
 }
 }
 
 
 /**
 /**
@@ -162,14 +183,30 @@ function get_specific_field_values_list_by_prefix($prefix, $course_code, $tool_i
  * @param int $ref_id intern id inside specific tool table
  * @param int $ref_id intern id inside specific tool table
  * @param string $value specific field value
  * @param string $value specific field value
  */
  */
-function add_specific_field_value($id_specific_field, $course_id, $tool_id, $ref_id, $value) {
-    $table_sf_values = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
+function add_specific_field_value(
+    $id_specific_field,
+    $course_id,
+    $tool_id,
+    $ref_id,
+    $value
+) {
+    $table_sf_values = Database:: get_main_table(
+        TABLE_MAIN_SPECIFIC_FIELD_VALUES
+    );
     $value = trim($value);
     $value = trim($value);
     if (empty($value)) {
     if (empty($value)) {
         return false;
         return false;
     }
     }
     $sql = 'INSERT INTO %s(id, course_code, tool_id, ref_id, field_id, value) VALUES(NULL, \'%s\', \'%s\', %s, %s, \'%s\')';
     $sql = 'INSERT INTO %s(id, course_code, tool_id, ref_id, field_id, value) VALUES(NULL, \'%s\', \'%s\', %s, %s, \'%s\')';
-    $sql = sprintf($sql, $table_sf_values, $course_id, $tool_id, $ref_id, $id_specific_field, Database::escape_string($value));
+    $sql = sprintf(
+        $sql,
+        $table_sf_values,
+        $course_id,
+        $tool_id,
+        $ref_id,
+        $id_specific_field,
+        Database::escape_string($value)
+    );
     $result = Database::query($sql);
     $result = Database::query($sql);
     if ($result) {
     if ($result) {
         return Database::insert_id();
         return Database::insert_id();
@@ -186,10 +223,10 @@ function add_specific_field_value($id_specific_field, $course_id, $tool_id, $ref
  * @param int $ref_id intern id inside specific tool table
  * @param int $ref_id intern id inside specific tool table
  */
  */
 function delete_all_specific_field_value($course_id, $id_specific_field, $tool_id, $ref_id) {
 function delete_all_specific_field_value($course_id, $id_specific_field, $tool_id, $ref_id) {
-  $table_sf_values = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
-  $sql = 'DELETE FROM %s WHERE course_code = \'%s\' AND tool_id = \'%s\' AND ref_id = %s AND field_id = %s';
-  $sql = sprintf($sql, $table_sf_values, $course_id, $tool_id, $ref_id, $id_specific_field);
-  $result = Database::query($sql);
+    $table_sf_values = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD_VALUES);
+    $sql = 'DELETE FROM %s WHERE course_code = \'%s\' AND tool_id = \'%s\' AND ref_id = %s AND field_id = %s';
+    $sql = sprintf($sql, $table_sf_values, $course_id, $tool_id, $ref_id, $id_specific_field);
+    Database::query($sql);
 }
 }
 
 
 /**
 /**
@@ -216,8 +253,32 @@ function delete_all_values_for_item($course_id, $tool_id, $ref_id) {
 function get_specific_field_code_from_name($name) {
 function get_specific_field_code_from_name($name) {
     // Z is used internally by Xapian
     // Z is used internally by Xapian
     // O & C already used by tool_id and course_id
     // O & C already used by tool_id and course_id
-    $list = array('A','B','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y');
-    $table_sf     = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
+    $list = array(
+        'A',
+        'B',
+        'D',
+        'E',
+        'F',
+        'G',
+        'H',
+        'I',
+        'J',
+        'K',
+        'L',
+        'M',
+        'N',
+        'P',
+        'Q',
+        'R',
+        'S',
+        'T',
+        'U',
+        'V',
+        'W',
+        'X',
+        'Y',
+    );
+    $table_sf = Database :: get_main_table(TABLE_MAIN_SPECIFIC_FIELD);
     $sql = "SELECT code FROM $table_sf ORDER BY code";
     $sql = "SELECT code FROM $table_sf ORDER BY code";
     $res = Database::query($sql);
     $res = Database::query($sql);
     $code = strtoupper(substr($name,0,1));
     $code = strtoupper(substr($name,0,1));

+ 26 - 13
main/inc/lib/statistics.lib.php

@@ -52,6 +52,7 @@ class Statistics
         }
         }
         $res = Database::query($sql);
         $res = Database::query($sql);
         $obj = Database::fetch_object($res);
         $obj = Database::fetch_object($res);
+
         return $obj->number;
         return $obj->number;
     }
     }
 
 
@@ -69,7 +70,8 @@ class Statistics
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $current_url_id = api_get_current_access_url_id();
         $current_url_id = api_get_current_access_url_id();
         if (api_is_multiple_url_enabled()) {
         if (api_is_multiple_url_enabled()) {
-            $sql = "SELECT COUNT(*) AS number FROM ".$course_table." as c, ".$access_url_rel_course_table." as u
+            $sql = "SELECT COUNT(*) AS number
+                    FROM ".$course_table." as c, ".$access_url_rel_course_table." as u
                     WHERE u.c_id = c.id AND access_url_id='".$current_url_id."'";
                     WHERE u.c_id = c.id AND access_url_id='".$current_url_id."'";
             if (isset ($visibility)) {
             if (isset ($visibility)) {
                 $sql .= " AND visibility = ".intval($visibility);
                 $sql .= " AND visibility = ".intval($visibility);
@@ -139,6 +141,7 @@ class Statistics
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
         $obj = Database::fetch_object($res);
         $obj = Database::fetch_object($res);
+
         return $obj->number;
         return $obj->number;
     }
     }
 
 
@@ -152,7 +155,8 @@ class Statistics
         $access_url_rel_session_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $access_url_rel_session_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         if (api_is_multiple_url_enabled()) {
         if (api_is_multiple_url_enabled()) {
             $current_url_id = api_get_current_access_url_id();
             $current_url_id = api_get_current_access_url_id();
-            $sql = "SELECT COUNT(id) AS number FROM ".$session_table." as s, ".$access_url_rel_session_table." as u WHERE u.session_id=s.id AND access_url_id='".$current_url_id."'";
+            $sql = "SELECT COUNT(id) AS number FROM ".$session_table." as s, ".$access_url_rel_session_table." as u
+                    WHERE u.session_id=s.id AND access_url_id='".$current_url_id."'";
         } else {
         } else {
             $sql = "SELECT COUNT(id) AS number FROM ".$session_table." ";
             $sql = "SELECT COUNT(id) AS number FROM ".$session_table." ";
         }
         }
@@ -173,9 +177,13 @@ class Statistics
         $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $current_url_id = api_get_current_access_url_id();
         $current_url_id = api_get_current_access_url_id();
         if (api_is_multiple_url_enabled()) {
         if (api_is_multiple_url_enabled()) {
-            $sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user, $access_url_rel_user_table url WHERE default_user_id = user.user_id AND user.user_id=url.user_id AND access_url_id='".$current_url_id."'";
+            $sql = "SELECT count(default_id) AS total_number_of_items
+                    FROM $track_e_default, $table_user user, $access_url_rel_user_table url
+                    WHERE default_user_id = user.user_id AND user.user_id=url.user_id AND access_url_id='".$current_url_id."'";
         } else {
         } else {
-            $sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";
+            $sql = "SELECT count(default_id) AS total_number_of_items
+                    FROM $track_e_default, $table_user user
+                    WHERE default_user_id = user.user_id ";
         }
         }
 
 
         if (isset($_GET['keyword'])) {
         if (isset($_GET['keyword'])) {
@@ -185,6 +193,7 @@ class Statistics
 
 
         $res = Database::query($sql);
         $res = Database::query($sql);
         $obj = Database::fetch_object($res);
         $obj = Database::fetch_object($res);
+
         return $obj->total_number_of_items;
         return $obj->total_number_of_items;
     }
     }
 
 
@@ -198,14 +207,12 @@ class Statistics
      */
      */
     public static function getActivitiesData($from, $numberOfItems, $column, $direction)
     public static function getActivitiesData($from, $numberOfItems, $column, $direction)
     {
     {
-        global $dateTimeFormatLong;
-        $track_e_default    		= Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-        $table_user 				= Database::get_main_table(TABLE_MAIN_USER);
-        $access_url_rel_user_table	= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $current_url_id 			= api_get_current_access_url_id();
-
-        $column          = intval($column);
-        $from            = intval($from);
+        $track_e_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+        $table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $current_url_id = api_get_current_access_url_id();
+        $column = intval($column);
+        $from = intval($from);
         $numberOfItems = intval($numberOfItems);
         $numberOfItems = intval($numberOfItems);
 
 
         if (!in_array($direction, array('ASC','DESC'))) {
         if (!in_array($direction, array('ASC','DESC'))) {
@@ -289,6 +296,7 @@ class Statistics
             }
             }
             $activities[] = $row;
             $activities[] = $row;
         }
         }
+
         return $activities;
         return $activities;
     }
     }
 
 
@@ -305,6 +313,7 @@ class Statistics
         while ($category = Database::fetch_object($res)) {
         while ($category = Database::fetch_object($res)) {
             $categories[$category->code] = $category->name;
             $categories[$category->code] = $category->name;
         }
         }
+
         return $categories;
         return $categories;
     }
     }
 
 
@@ -326,6 +335,7 @@ class Statistics
         foreach ($data as $index => $value) {
         foreach ($data as $index => $value) {
             $result[$index] = (int) round($value * $delta);
             $result[$index] = (int) round($value * $delta);
         }
         }
+
         return $result;
         return $result;
     }
     }
 
 
@@ -399,7 +409,10 @@ class Statistics
 
 
         $period = get_lang('PeriodMonth');
         $period = get_lang('PeriodMonth');
         $periodCollection = api_get_months_long();
         $periodCollection = api_get_months_long();
-        $sql = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins FROM ".$table.$table_url.$where_url." GROUP BY stat_date ORDER BY login_date DESC";
+        $sql = "SELECT DATE_FORMAT( login_date, '%Y-%m' ) AS stat_date , count( login_id ) AS number_of_logins
+                FROM ".$table.$table_url.$where_url."
+                GROUP BY stat_date
+                ORDER BY login_date DESC";
         $sql_last_x = null;
         $sql_last_x = null;
 
 
         switch ($type) {
         switch ($type) {

+ 255 - 256
main/inc/lib/statsUtils.lib.inc.php

@@ -8,104 +8,104 @@
 */
 */
 class StatsUtils
 class StatsUtils
 {
 {
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @desc return one result from a sql query (1 single result)
-	 */
-	public static function getOneResult($sql)
-	{
-		$query = Database::query($sql);
-		if ($query !== false) {
-			$res = @Database::fetch_array($query, 'NUM');
-		} else {
-			$res = array();
-		}
-		return $res[0];
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @desc return one result from a sql query (1 single result)
+     */
+    public static function getOneResult($sql)
+    {
+        $query = Database::query($sql);
+        if ($query !== false) {
+            $res = @Database::fetch_array($query, 'NUM');
+        } else {
+            $res = array();
+        }
+        return $res[0];
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @desc Return many results of a query in a 1 column tab
-	 */
-	public static function getManyResults1Col($sql)
-	{
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$i = 0;
-			while ($resA = Database::fetch_array($res, 'NUM')) {
-				$resu[$i++] = $resA[0];
-			}
-		}
-		return $resu;
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @desc Return many results of a query in a 1 column tab
+     */
+    public static function getManyResults1Col($sql)
+    {
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $i = 0;
+            while ($resA = Database::fetch_array($res, 'NUM')) {
+                $resu[$i++] = $resA[0];
+            }
+        }
+        return $resu;
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @desc Return many results of a query
-	 */
-	public static function getManyResults2Col($sql)
-	{
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$i = 0;
-			while ($resA = Database::fetch_array($res, 'NUM')) {
-				$resu[$i][0] = $resA[0];
-				$resu[$i][1] = $resA[1];
-				$i++;
-			}
-		}
-		return $resu;
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @desc Return many results of a query
+     */
+    public static function getManyResults2Col($sql)
+    {
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $i = 0;
+            while ($resA = Database::fetch_array($res, 'NUM')) {
+                $resu[$i][0] = $resA[0];
+                $resu[$i][1] = $resA[1];
+                $i++;
+            }
+        }
+        return $resu;
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @desc Return many results of a query in a 3 column tab
-	 * in $resu[$i][0], $resu[$i][1],$resu[$i][2]
-	 */
-	public static function getManyResults3Col($sql)
-	{
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$i = 0;
-			while ($resA = Database::fetch_array($res, 'NUM')) {
-				$resu[$i][0] = $resA[0];
-				$resu[$i][1] = $resA[1];
-				$resu[$i][2] = $resA[2];
-				$i++;
-			}
-		}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @desc Return many results of a query in a 3 column tab
+     * in $resu[$i][0], $resu[$i][1],$resu[$i][2]
+     */
+    public static function getManyResults3Col($sql)
+    {
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $i = 0;
+            while ($resA = Database::fetch_array($res, 'NUM')) {
+                $resu[$i][0] = $resA[0];
+                $resu[$i][1] = $resA[1];
+                $resu[$i][2] = $resA[2];
+                $i++;
+            }
+        }
 
 
-		return $resu;
-	}
+        return $resu;
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @desc Return many results of a query in a X column tab
-	 * in $resu[$i][0], $resu[$i][1],$resu[$i][2],...
-	 * this function is more 'standard' but use a little
-	 * more ressources
-	 * So I encourage to use the dedicated for 1, 2 or 3
-	 * columns of results
-	 */
-	public static function getManyResultsXCol($sql, $X)
-	{
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$i = 0;
-			while ($resA = Database::fetch_array($res, 'NUM')) {
-				for ($j = 0; $j < $X; $j++) {
-					$resu[$i][$j] = $resA[$j];
-				}
-				$i++;
-			}
-		}
-		return $resu;
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @desc Return many results of a query in a X column tab
+     * in $resu[$i][0], $resu[$i][1],$resu[$i][2],...
+     * this function is more 'standard' but use a little
+     * more ressources
+     * So I encourage to use the dedicated for 1, 2 or 3
+     * columns of results
+     */
+    public static function getManyResultsXCol($sql, $X)
+    {
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $i = 0;
+            while ($resA = Database::fetch_array($res, 'NUM')) {
+                for ($j = 0; $j < $X; $j++) {
+                    $resu[$i][$j] = $resA[$j];
+                }
+                $i++;
+            }
+        }
+        return $resu;
+    }
 
 
 	/**
 	/**
 	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
 	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
@@ -115,170 +115,169 @@ class StatsUtils
 	 * the number of time this hours was found.
 	 * the number of time this hours was found.
 	 * key 'total' return the sum of all number of time hours
 	 * key 'total' return the sum of all number of time hours
 	 * appear
 	 * appear
-	 */
-	public static function hoursTab($sql)
-	{
-		$hours_array = array('total' => 0);
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$last_hours = -1;
-			while ($row = Database::fetch_row($res)) {
-				$date_array = getdate($row[0]);
-				if ($date_array['hours'] == $last_hours) {
-					$hours_array[$date_array['hours']]++;
-				} else {
-					$hours_array[$date_array['hours']] = 1;
-					$last_hours = $date_array['hours'];
-				}
-				$hours_array['total']++;
-			}
-			Database::free_result($res);
-		}
-		return $hours_array;
-	}
-
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @return days_array
-	 * @desc        Return an assoc array.  Keys are the days, values are
-	 * the number of time this hours was found.
-	 * key "total" return the sum of all number of time days
-	 * appear
-	 */
-	public static function daysTab($sql)
-	{
-		$MonthsShort = api_get_months_short();
-		$days_array = array('total' => 0);
-		$res = Database::query($sql);
-		if ($res !== false) {
-			$last_day = -1;
-			while ($row = Database::fetch_row($res)) {
-				$date_array = getdate($row[0]);
-				$display_date = $date_array['mday'] . ' ' . $MonthsShort[$date_array['mon'] - 1] . ' ' . $date_array['year'];
-				if ($date_array['mday'] == $last_day) {
-					$days_array[$display_date]++;
-				} else {
-					$days_array[$display_date] = 1;
-					$last_day = $display_date;
-				}
-				$days_array['total']++;
-			}
-			Database::free_result($res);
-		}
-		return $days_array;
-	}
+     */
+    public static function hoursTab($sql)
+    {
+        $hours_array = array('total' => 0);
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $last_hours = -1;
+            while ($row = Database::fetch_row($res)) {
+                $date_array = getdate($row[0]);
+                if ($date_array['hours'] == $last_hours) {
+                    $hours_array[$date_array['hours']]++;
+                } else {
+                    $hours_array[$date_array['hours']] = 1;
+                    $last_hours = $date_array['hours'];
+                }
+                $hours_array['total']++;
+            }
+            Database::free_result($res);
+        }
+        return $hours_array;
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param sql : a sql query (as a string)
-	 * @return month_array
-	 * @desc        Return an assoc array.  Keys are the days, values are
-	 * the number of time this hours was found.
-	 * key "total" return the sum of all number of time days
-	 * appear
-	 */
-	public static function monthTab($sql)
-	{
-		$MonthsLong = api_get_months_long();
-		$month_array = array('total' => 0);
-		$res = Database::query($sql);
-		if ($res !== false) {
-			// init tab with all months
-			for ($i = 0; $i < 12; $i++) {
-				$month_array[$MonthsLong[$i]] = 0;
-			}
-			while ($row = Database::fetch_row($res)) {
-				$date_array = getdate($row[0]);
-				$month_array[$MonthsLong[$date_array['mon'] - 1]]++;
-				$month_array['total']++;
-			}
-			Database::free_result($res);
-		}
-		return $month_array;
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @return days_array
+     * @desc        Return an assoc array.  Keys are the days, values are
+     * the number of time this hours was found.
+     * key "total" return the sum of all number of time days
+     * appear
+     */
+    public static function daysTab($sql)
+    {
+        $MonthsShort = api_get_months_short();
+        $days_array = array('total' => 0);
+        $res = Database::query($sql);
+        if ($res !== false) {
+            $last_day = -1;
+            while ($row = Database::fetch_row($res)) {
+                $date_array = getdate($row[0]);
+                $display_date = $date_array['mday'] . ' ' . $MonthsShort[$date_array['mon'] - 1] . ' ' . $date_array['year'];
+                if ($date_array['mday'] == $last_day) {
+                    $days_array[$display_date]++;
+                } else {
+                    $days_array[$display_date] = 1;
+                    $last_day = $display_date;
+                }
+                $days_array['total']++;
+            }
+            Database::free_result($res);
+        }
+        return $days_array;
+    }
 
 
-	/**
-	 * @author Sebastien Piraux <piraux_seb@hotmail.com>
-	 * @param period_array : an array provided by hoursTab($sql) or daysTab($sql)
-	 * @param periodTitle : title of the first column, type of period
-	 * @param linkOnPeriod :
-	 * @desc        Display a 4 column array
-	 * Columns are : hour of day, graph, number of hits and %
-	 * First line are titles
-	 * next are informations
-	 * Last is total number of hits
-	 */
-	public static function makeHitsTable($period_array, $periodTitle, $linkOnPeriod = '???')
-	{
-		echo "<table width='100%' cellpadding='0' cellspacing='1' border='0' align=center class='minitext'>";
-		// titles
-		echo "<tr bgcolor='#E6E6E6' align='center'>
-				<td width='15%' >
-					<b>$periodTitle</b>
-				</td>
-				<td width='60%'>
-					&nbsp;
-				</td>
-				<td width='10%'>
-					<b>" . get_lang('Hits') . "</b>
-				</td>
-				<td width='15%'>
-					<b>%</b>
-				</td>
-			</tr>
-		";
-		$factor = 4;
-		$maxSize = $factor * 100; //pixels
-		while (list($periodPiece, $cpt) = each($period_array)) {
-			if ($periodPiece != 'total') {
-				$pourcent = round(100 * $cpt / $period_array['total']);
-				$barwidth = $factor * $pourcent;
-				echo "<tr>
-					<td align='center' width='15%'>";
-				echo $periodPiece;
-				echo "</td>
-					<td width='60%' style='padding-top: 3px;' align='center'>"
-					// display hitbar
-					. "<img src='../img/bar_1.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
-				if ($pourcent != 0) {
-					echo "<img src='../img/bar_1u.gif' width='$barwidth' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
-				}
-				// display 100% bar
-				if ($pourcent != 100 && $pourcent != 0) {
-					echo "<img src='../img/bar_1m.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
-				}
-				if ($pourcent != 100) {
-					echo "<img src='../img/bar_1r.gif' width='" . ($maxSize - $barwidth) . "' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
-				}
-				echo "<img src='../img/bar_1.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />
-					</td>
-					<td align='center' width='10%'>
-						$cpt
-					</td>
-					<td align='center' width='15%'>
-						$pourcent %
-					</td>
-					</tr>
-				";
-			}
-		}
-		echo "<tr bgcolor='#E6E6E6'>
-				<td width='15%' align='center'>
-					" . get_lang('Total') . "
-				</td>
-				<td align='right' width='60%'>
-					&nbsp;
-				</td>
-				<td align='center' width='10%'>
-					" . $period_array['total'] . "
-				</td>
-				<td width='15%'>
-					&nbsp;
-				</td>
-			</tr>
-		";
-		echo "</table>";
-	}
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param sql : a sql query (as a string)
+     * @return month_array
+     * @desc        Return an assoc array.  Keys are the days, values are
+     * the number of time this hours was found.
+     * key "total" return the sum of all number of time days
+     * appear
+     */
+    public static function monthTab($sql)
+    {
+        $MonthsLong = api_get_months_long();
+        $month_array = array('total' => 0);
+        $res = Database::query($sql);
+        if ($res !== false) {
+            // init tab with all months
+            for ($i = 0; $i < 12; $i++) {
+                $month_array[$MonthsLong[$i]] = 0;
+            }
+            while ($row = Database::fetch_row($res)) {
+                $date_array = getdate($row[0]);
+                $month_array[$MonthsLong[$date_array['mon'] - 1]]++;
+                $month_array['total']++;
+            }
+            Database::free_result($res);
+        }
+        return $month_array;
+    }
 
 
+    /**
+     * @author Sebastien Piraux <piraux_seb@hotmail.com>
+     * @param period_array : an array provided by hoursTab($sql) or daysTab($sql)
+     * @param periodTitle : title of the first column, type of period
+     * @param linkOnPeriod :
+     * @desc        Display a 4 column array
+     * Columns are : hour of day, graph, number of hits and %
+     * First line are titles
+     * next are informations
+     * Last is total number of hits
+     */
+    public static function makeHitsTable($period_array, $periodTitle, $linkOnPeriod = '???')
+    {
+        echo "<table width='100%' cellpadding='0' cellspacing='1' border='0' align=center class='minitext'>";
+        // titles
+        echo "<tr bgcolor='#E6E6E6' align='center'>
+                <td width='15%' >
+                    <b>$periodTitle</b>
+                </td>
+                <td width='60%'>
+                    &nbsp;
+                </td>
+                <td width='10%'>
+                    <b>" . get_lang('Hits') . "</b>
+                </td>
+                <td width='15%'>
+                    <b>%</b>
+                </td>
+            </tr>
+        ";
+        $factor = 4;
+        $maxSize = $factor * 100; //pixels
+        while (list($periodPiece, $cpt) = each($period_array)) {
+            if ($periodPiece != 'total') {
+                $pourcent = round(100 * $cpt / $period_array['total']);
+                $barwidth = $factor * $pourcent;
+                echo "<tr>
+                    <td align='center' width='15%'>";
+                echo $periodPiece;
+                echo "</td>
+                    <td width='60%' style='padding-top: 3px;' align='center'>"
+                    // display hitbar
+                    . "<img src='../img/bar_1.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
+                if ($pourcent != 0) {
+                    echo "<img src='../img/bar_1u.gif' width='$barwidth' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
+                }
+                // display 100% bar
+                if ($pourcent != 100 && $pourcent != 0) {
+                    echo "<img src='../img/bar_1m.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
+                }
+                if ($pourcent != 100) {
+                    echo "<img src='../img/bar_1r.gif' width='" . ($maxSize - $barwidth) . "' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />";
+                }
+                echo "<img src='../img/bar_1.gif' width='1' height='12' alt='$periodPiece : $cpt hits &ndash; $pourcent %' />
+                    </td>
+                    <td align='center' width='10%'>
+                        $cpt
+                    </td>
+                    <td align='center' width='15%'>
+                        $pourcent %
+                    </td>
+                    </tr>
+                ";
+            }
+        }
+        echo "<tr bgcolor='#E6E6E6'>
+                <td width='15%' align='center'>
+                    " . get_lang('Total') . "
+                </td>
+                <td align='right' width='60%'>
+                    &nbsp;
+                </td>
+                <td align='center' width='10%'>
+                    " . $period_array['total'] . "
+                </td>
+                <td width='15%'>
+                    &nbsp;
+                </td>
+            </tr>
+        ";
+        echo "</table>";
+    }
 }
 }

+ 18 - 10
main/inc/lib/sub_language.class.php

@@ -4,7 +4,6 @@
 /**
 /**
  * Class SubLanguageManager
  * Class SubLanguageManager
  * @package chamilo.admin.sublanguage
  * @package chamilo.admin.sublanguage
- * @todo clean this lib and move to main/inc/lib
  */
  */
 class SubLanguageManager
 class SubLanguageManager
 {
 {
@@ -76,6 +75,7 @@ class SubLanguageManager
         while ($row = Database::fetch_array($rs, 'ASSOC')) {
         while ($row = Database::fetch_array($rs, 'ASSOC')) {
             $all_information = $row;
             $all_information = $row;
         }
         }
+
         return $all_information;
         return $all_information;
     }
     }
 
 
@@ -226,7 +226,9 @@ class SubLanguageManager
     public static function check_if_exist_language_by_id($language_id)
     public static function check_if_exist_language_by_id($language_id)
     {
     {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT count(*) as count FROM ' . $tbl_admin_languages . ' WHERE id="' . intval($language_id) . '"';
+        $sql = 'SELECT count(*) as count
+                FROM ' . $tbl_admin_languages . '
+                WHERE id="' . intval($language_id) . '"';
         $rs = Database::query($sql);
         $rs = Database::query($sql);
         if (Database::num_rows($rs) > 0) {
         if (Database::num_rows($rs) > 0) {
             if (Database::result($rs, 0, 'count') == 1) {
             if (Database::result($rs, 0, 'count') == 1) {
@@ -247,7 +249,9 @@ class SubLanguageManager
     public static function get_name_of_language_by_id($language_id)
     public static function get_name_of_language_by_id($language_id)
     {
     {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql = 'SELECT original_name FROM ' . $tbl_admin_languages . ' WHERE id= ' . intval($language_id) . '';
+        $sql = 'SELECT original_name
+                FROM ' . $tbl_admin_languages . '
+                WHERE id= ' . intval($language_id) . '';
         $rs = Database::query($sql);
         $rs = Database::query($sql);
         if (Database::num_rows($rs) > 0) {
         if (Database::num_rows($rs) > 0) {
             return Database::result($rs, 0, 'original_name');
             return Database::result($rs, 0, 'original_name');
@@ -320,8 +324,9 @@ class SubLanguageManager
     public static function make_unavailable_language($language_id)
     public static function make_unavailable_language($language_id)
     {
     {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql_make_unavailable = "UPDATE $tbl_admin_languages SET available='0' WHERE id = " . intval($language_id) . "";
-        $result = Database::query($sql_make_unavailable);
+        $sql = "UPDATE $tbl_admin_languages SET available='0'
+                WHERE id = " . intval($language_id) . "";
+        $result = Database::query($sql);
         return $result !== false; //only return false on sql error
         return $result !== false; //only return false on sql error
     }
     }
 
 
@@ -333,8 +338,9 @@ class SubLanguageManager
     public static function make_available_language($language_id)
     public static function make_available_language($language_id)
     {
     {
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-        $sql_make_available = "UPDATE $tbl_admin_languages SET available='1' WHERE id = " . intval($language_id) . "";
-        $result = Database::query($sql_make_available);
+        $sql = "UPDATE $tbl_admin_languages SET available='1'
+                WHERE id = " . intval($language_id) . "";
+        $result = Database::query($sql);
         return $result !== false; //only return false on sql error
         return $result !== false; //only return false on sql error
     }
     }
 
 
@@ -350,10 +356,12 @@ class SubLanguageManager
         }
         }
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
         $tbl_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
         $tbl_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-        $sql_update = "SELECT english_name FROM " . $tbl_admin_languages . " WHERE id= " . intval($language_id) . "";
-        $result = Database::query($sql_update);
+        $sql = "SELECT english_name FROM " . $tbl_admin_languages . "
+                WHERE id= " . intval($language_id) . "";
+        $result = Database::query($sql);
         $lang = Database::fetch_array($result);
         $lang = Database::fetch_array($result);
-        $sql_update_2 = "UPDATE " . $tbl_settings_current . " SET selected_value='" . $lang['english_name'] . "' WHERE variable='platformLanguage'";
+        $sql_update_2 = "UPDATE " . $tbl_settings_current . " SET selected_value='" . $lang['english_name'] . "'
+                         WHERE variable='platformLanguage'";
         $result_2 = Database::query($sql_update_2);
         $result_2 = Database::query($sql_update_2);
         Event::addEvent(
         Event::addEvent(
             LOG_PLATFORM_LANGUAGE_CHANGE,
             LOG_PLATFORM_LANGUAGE_CHANGE,

+ 2 - 2
main/inc/lib/surveymanager.lib.php

@@ -18,9 +18,9 @@ class SurveyTree
     public function __construct()
     public function __construct()
     {
     {
         // Database table definitions
         // Database table definitions
-        $table_survey 			= Database :: get_course_table(TABLE_SURVEY);
+        $table_survey = Database :: get_course_table(TABLE_SURVEY);
         $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
         $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-        $table_user 			= Database :: get_main_table(TABLE_MAIN_USER);
+        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
 
         // searching
         // searching
         $search_restriction = SurveyUtil::survey_search_restriction();
         $search_restriction = SurveyUtil::survey_search_restriction();

+ 2 - 2
main/inc/lib/system_announcements.lib.php

@@ -314,7 +314,7 @@ class SystemAnnouncementManager
         $visible_teacher = 0,
         $visible_teacher = 0,
         $visible_student = 0,
         $visible_student = 0,
         $visible_guest = 0,
         $visible_guest = 0,
-        $lang = null,
+        $lang = '',
         $send_mail = 0,
         $send_mail = 0,
         $add_to_calendar = false,
         $add_to_calendar = false,
         $sendEmailTest = false
         $sendEmailTest = false
@@ -357,7 +357,7 @@ class SystemAnnouncementManager
 		$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
 		$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
 		$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
 		$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
 
 
-        $lang = is_null($lang) ? 'NULL' : $lang;
+        $lang = is_null($lang) ? '' : $lang;
 
 
 		$current_access_url_id = 1;
 		$current_access_url_id = 1;
 		if (api_is_multiple_url_enabled()) {
 		if (api_is_multiple_url_enabled()) {

+ 1 - 3
main/inc/lib/table_sort.class.php

@@ -5,9 +5,7 @@
  *
  *
  *	@package chamilo.library
  *	@package chamilo.library
  */
  */
-/**
- * Code
- */
+
 define('SORT_DATE', 3);
 define('SORT_DATE', 3);
 define('SORT_IMAGE', 4);
 define('SORT_IMAGE', 4);
 
 

+ 10 - 27
main/inc/lib/template.lib.php

@@ -643,7 +643,8 @@ class Template
             $js_files[] = 'fontresize.js';
             $js_files[] = 'fontresize.js';
         }
         }
 
 
-        $js_files[] = 'tag/jquery.fcbkcomplete.min.js';
+        // Do not use minified version - generates errors (at least in the skills wheel)
+        $js_files[] = 'tag/jquery.fcbkcomplete.js';
 
 
         $js_file_to_string = null;
         $js_file_to_string = null;
         $isoCode = api_get_language_isocode();
         $isoCode = api_get_language_isocode();
@@ -733,7 +734,7 @@ class Template
      */
      */
     private function set_header_parameters()
     private function set_header_parameters()
     {
     {
-        global $httpHeadXtra, $_course, $interbreadcrumb, $language_file, $noPHP_SELF, $_configuration, $this_section;
+        global $httpHeadXtra, $_course, $interbreadcrumb, $language_file, $_configuration, $this_section;
         $help = $this->help;
         $help = $this->help;
         $nameTools             = $this->title;
         $nameTools             = $this->title;
         $navigation            = return_navigation_array();
         $navigation            = return_navigation_array();
@@ -827,17 +828,14 @@ class Template
         }
         }
 
 
         $this->assign('favico', $favico);
         $this->assign('favico', $favico);
-
-        $this->set_help();
+        $this->setHelp();
 
 
         //@todo move this in the template
         //@todo move this in the template
         $bug_notification_link = '';
         $bug_notification_link = '';
         if (api_get_setting('show_link_bug_notification') == 'true' && $this->user_is_logged_in) {
         if (api_get_setting('show_link_bug_notification') == 'true' && $this->user_is_logged_in) {
             $bug_notification_link = '<li class="report">
             $bug_notification_link = '<li class="report">
 		        						<a href="http://support.chamilo.org/projects/chamilo-18/wiki/How_to_report_bugs" target="_blank">
 		        						<a href="http://support.chamilo.org/projects/chamilo-18/wiki/How_to_report_bugs" target="_blank">
-		        						<img src="'.api_get_path(WEB_IMG_PATH).'bug.large.png" style="vertical-align: middle;" alt="'.get_lang('ReportABug').'" title="'.get_lang(
-                    'ReportABug'
-                ).'"/></a>
+		        						<img src="'.api_get_path(WEB_IMG_PATH).'bug.large.png" style="vertical-align: middle;" alt="'.get_lang('ReportABug').'" title="'.get_lang('ReportABug').'"/></a>
 		    						  </li>';
 		    						  </li>';
         }
         }
 
 
@@ -846,9 +844,9 @@ class Template
         $notification = return_notification_menu();
         $notification = return_notification_menu();
         $this->assign('notification_menu', $notification);
         $this->assign('notification_menu', $notification);
 
 
-        //Preparing values for the menu
+        // Preparing values for the menu
 
 
-        //Logout link
+        // Logout link
         $hideLogout = api_get_setting('hide_logout_button');
         $hideLogout = api_get_setting('hide_logout_button');
         if ($hideLogout === 'true') {
         if ($hideLogout === 'true') {
             $this->assign('logout_link', null);
             $this->assign('logout_link', null);
@@ -886,9 +884,7 @@ class Template
         $menu = return_menu();
         $menu = return_menu();
         $this->assign('menu', $menu);
         $this->assign('menu', $menu);
 
 
-        //Setting notifications
-
-
+        // Setting notifications
         $count_unread_message = 0;
         $count_unread_message = 0;
         if (api_get_setting('allow_message_tool') == 'true') {
         if (api_get_setting('allow_message_tool') == 'true') {
             // get count unread message and total invitations
             // get count unread message and total invitations
@@ -906,9 +902,10 @@ class Template
                 GROUP_USER_PERMISSION_PENDING_INVITATION,
                 GROUP_USER_PERMISSION_PENDING_INVITATION,
                 false
                 false
             );
             );
-            $group_pending_invitations = 0;
             if (!empty($group_pending_invitations)) {
             if (!empty($group_pending_invitations)) {
                 $group_pending_invitations = count($group_pending_invitations);
                 $group_pending_invitations = count($group_pending_invitations);
+            } else {
+                $group_pending_invitations = 0;
             }
             }
             $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval($count_unread_message);
             $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval($count_unread_message);
         }
         }
@@ -969,11 +966,6 @@ class Template
      */
      */
     private function set_footer_parameters()
     private function set_footer_parameters()
     {
     {
-        global $_configuration;
-
-        //Show admin data
-        //$this->assign('show_administrator_data', api_get_setting('show_administrator_data'));
-
         if (api_get_setting('show_administrator_data') == 'true') {
         if (api_get_setting('show_administrator_data') == 'true') {
             //Administrator name
             //Administrator name
             $administrator_data = get_lang('Manager').' : '.Display::encrypted_mailto_link(
             $administrator_data = get_lang('Manager').' : '.Display::encrypted_mailto_link(
@@ -1040,8 +1032,6 @@ class Template
                 $this->assign('teachers', $teacher_data);
                 $this->assign('teachers', $teacher_data);
             }
             }
         }
         }
-        /* $stats = '';
-          $this->assign('execution_stats', $stats); */
     }
     }
 
 
     /**
     /**
@@ -1266,12 +1256,6 @@ class Template
         $form->addButton('submitAuth', get_lang('LoginEnter'), null, 'primary', null, 'btn-block');
         $form->addButton('submitAuth', get_lang('LoginEnter'), null, 'primary', null, 'btn-block');
 
 
         $html = $form->returnForm();
         $html = $form->returnForm();
-        // The validation is located in the local.inc
-        /*if ($form->validate()) {
-            // Prevent re-use of the same CAPTCHA phrase
-            $captcha_question->destroy();
-        }*/
-
         if (api_get_setting('openid_authentication') == 'true') {
         if (api_get_setting('openid_authentication') == 'true') {
             include_once 'main/auth/openid/login.php';
             include_once 'main/auth/openid/login.php';
             $html .= '<div>'.openid_form().'</div>';
             $html .= '<div>'.openid_form().'</div>';
@@ -1294,5 +1278,4 @@ class Template
 
 
         $this->assign('_admin', $_admin);
         $this->assign('_admin', $_admin);
     }
     }
-
 }
 }

+ 17 - 12
main/inc/lib/thematic.lib.php

@@ -157,8 +157,8 @@ class Thematic
     public function get_max_thematic_item($use_session = true)
     public function get_max_thematic_item($use_session = true)
     {
     {
         // Database table definition
         // Database table definition
-        $tbl_thematic   = Database :: get_course_table(TABLE_THEMATIC);
-        $session_id     = api_get_session_id();
+        $tbl_thematic = Database :: get_course_table(TABLE_THEMATIC);
+        $session_id   = api_get_session_id();
         if ($use_session) {
         if ($use_session) {
             $condition_session = api_get_session_condition($session_id);
             $condition_session = api_get_session_condition($session_id);
         } else {
         } else {
@@ -166,7 +166,7 @@ class Thematic
         }
         }
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
         $sql = "SELECT MAX(display_order) FROM $tbl_thematic
         $sql = "SELECT MAX(display_order) FROM $tbl_thematic
-		        WHERE c_id = $course_id AND active = 1 $condition_session";
+                WHERE c_id = $course_id AND active = 1 $condition_session";
         $rs = Database::query($sql);
         $rs = Database::query($sql);
         $row = Database::fetch_array($rs);
         $row = Database::fetch_array($rs);
 
 
@@ -260,12 +260,10 @@ class Thematic
         }
         }
 
 
         $data = array();
         $data = array();
-        $condition = '';
         if (isset($thematic_id)) {
         if (isset($thematic_id)) {
             $thematic_id = intval($thematic_id);
             $thematic_id = intval($thematic_id);
             $condition = " WHERE id = $thematic_id AND active = 1 ";
             $condition = " WHERE id = $thematic_id AND active = 1 ";
         } else {
         } else {
-            $condition_session = '';
             if (empty($session_id)) {
             if (empty($session_id)) {
                 $condition_session = api_get_session_condition(0);
                 $condition_session = api_get_session_condition(0);
             } else {
             } else {
@@ -356,7 +354,6 @@ class Thematic
                 "ThematicUpdated",
                 "ThematicUpdated",
                 $user_id
                 $user_id
             );
             );
-
         }
         }
 
 
         return $last_id;
         return $last_id;
@@ -420,7 +417,12 @@ class Thematic
     {
     {
         $thematic = self::get_thematic_list($thematic_id, api_get_course_id(), 0);
         $thematic = self::get_thematic_list($thematic_id, api_get_course_id(), 0);
         $thematic_copy = new Thematic();
         $thematic_copy = new Thematic();
-        $thematic_copy->set_thematic_attributes('', $thematic['title'].' - '.get_lang('Copy'), $thematic['content'], api_get_session_id());
+        $thematic_copy->set_thematic_attributes(
+            '',
+            $thematic['title'].' - '.get_lang('Copy'),
+            $thematic['content'],
+            api_get_session_id()
+        );
 
 
         $new_thematic_id = $thematic_copy->thematic_save();
         $new_thematic_id = $thematic_copy->thematic_save();
         if (!empty($new_thematic_id)) {
         if (!empty($new_thematic_id)) {
@@ -504,7 +506,11 @@ class Thematic
     				ORDER BY col$column $direction
     				ORDER BY col$column $direction
     				LIMIT $from,$number_of_items ";
     				LIMIT $from,$number_of_items ";
 
 
-            $list = api_get_item_property_by_tool('thematic_advance', api_get_course_id(), api_get_session_id());
+            $list = api_get_item_property_by_tool(
+                'thematic_advance',
+                api_get_course_id(),
+                api_get_session_id()
+            );
 
 
             $elements = array();
             $elements = array();
             foreach ($list as $value) {
             foreach ($list as $value) {
@@ -706,7 +712,6 @@ class Thematic
                             $data[$row['thematic_id']][$row['id']] = $row;
                             $data[$row['thematic_id']][$row['id']] = $row;
                         }
                         }
                     }
                     }
-
                 }
                 }
             }
             }
         }
         }
@@ -831,7 +836,7 @@ class Thematic
     {
     {
         // definition database table
         // definition database table
         $tbl_thematic_plan = Database::get_course_table(TABLE_THEMATIC_PLAN);
         $tbl_thematic_plan = Database::get_course_table(TABLE_THEMATIC_PLAN);
-        $tbl_thematic      = Database::get_course_table(TABLE_THEMATIC);
+        $tbl_thematic = Database::get_course_table(TABLE_THEMATIC);
 
 
         $course_id = api_get_course_int_id();
         $course_id = api_get_course_int_id();
 
 
@@ -1029,8 +1034,8 @@ class Thematic
 
 
     /**
     /**
      * delete a thematic plan description
      * delete a thematic plan description
-     * @param	int		Thematic id
-     * @param	int		Description type
+     * @param	int		$thematic_id Thematic id
+     * @param	int		$description_type Description type
      * @return	int		Affected rows
      * @return	int		Affected rows
      */
      */
     public function thematic_plan_destroy($thematic_id, $description_type)
     public function thematic_plan_destroy($thematic_id, $description_type)

+ 64 - 86
main/inc/lib/tracking.lib.php

@@ -2089,14 +2089,14 @@ class Tracking
             }
             }
             $tutor = api_get_user_info($teacher['user_id']);
             $tutor = api_get_user_info($teacher['user_id']);
             $data[] = array(
             $data[] = array(
-                'course'        => $course['title'],
-                'session'       => $teacher['name'],
-                'tutor'         => $tutor['username'] . ' - ' . $tutor['lastname'] . ' ' . $tutor['firstname'],
-                'documents'     => $totalDocuments,
-                'links'         => $totalLinks,
-                'forums'        => $totalForums,
-                'works'         => $totalWorks,
-                'wikis'         => $totalWikis,
+                'course' => $course['title'],
+                'session' => $teacher['name'],
+                'tutor' => $tutor['username'] . ' - ' . $tutor['lastname'] . ' ' . $tutor['firstname'],
+                'documents' => $totalDocuments,
+                'links' => $totalLinks,
+                'forums' => $totalForums,
+                'works' => $totalWorks,
+                'wikis' => $totalWikis,
                 'announcements' => $totalAnnouncements,
                 'announcements' => $totalAnnouncements,
             );
             );
         }
         }
@@ -3628,7 +3628,7 @@ class Tracking
     public static function count_student_downloaded_documents($student_id, $courseId, $session_id = 0)
     public static function count_student_downloaded_documents($student_id, $courseId, $session_id = 0)
     {
     {
         $student_id  = intval($student_id);
         $student_id  = intval($student_id);
-        $course_code = intval($courseId);
+        $courseId = intval($courseId);
         $session_id  = intval($session_id);
         $session_id  = intval($session_id);
 
 
         // table definition
         // table definition
@@ -3645,8 +3645,8 @@ class Tracking
 
 
     /**
     /**
      * Get course list inside a session from a student
      * Get course list inside a session from a student
-     * @param    int        Student id
-     * @param    int        Session id (optional)
+     * @param    int        $user_id Student id
+     * @param    int        $id_session Session id (optional)
      * @return    array    Courses list
      * @return    array    Courses list
      */
      */
     public static function get_course_list_in_session_from_student($user_id, $id_session = 0)
     public static function get_course_list_in_session_from_student($user_id, $id_session = 0)
@@ -3726,9 +3726,9 @@ class Tracking
 
 
     /**
     /**
      * Get count login per student
      * Get count login per student
-     * @param    int        Student id
-     * @param    int     $courseId
-     * @param    int        Session id (optional)
+     * @param    int    $student_id    Student id
+     * @param    int    $courseId
+     * @param    int    $session_id    Session id (optional)
      * @return    int        count login
      * @return    int        count login
      */
      */
     public static function count_login_per_student($student_id, $courseId, $session_id = 0)
     public static function count_login_per_student($student_id, $courseId, $session_id = 0)
@@ -3763,7 +3763,7 @@ class Tracking
         $tbl_user     = Database :: get_main_table(TABLE_MAIN_USER);
         $tbl_user     = Database :: get_main_table(TABLE_MAIN_USER);
 
 
         $sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
         $sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
-            WHERE hr_dept_id='.$hr_dept_id;
+                WHERE hr_dept_id='.$hr_dept_id;
         $rs = Database::query($sql);
         $rs = Database::query($sql);
 
 
         while($user = Database :: fetch_array($rs)) {
         while($user = Database :: fetch_array($rs)) {
@@ -4588,11 +4588,6 @@ class Tracking
                     if (!empty($exercises)) {
                     if (!empty($exercises)) {
                         $count_exercises = count($exercises);
                         $count_exercises = count($exercises);
                     }
                     }
-                    //Count of user results
-                    //$done_exercises     = get_best_exercise_results_by_course($course_code, $session_id_from_get);
-
-                    //From course exercises NOT from LP exercises!!!
-                    //$done_exercises     = Event::get_count_exercises_attempted_by_course($course_code, $session_id_from_get);
                     $answered_exercises = 0;
                     $answered_exercises = 0;
                     foreach($exercises as $exercise_item) {
                     foreach($exercises as $exercise_item) {
                         $attempts = Event::count_exercise_attempts_by_user(
                         $attempts = Event::count_exercise_attempts_by_user(
@@ -6164,37 +6159,6 @@ class TrackingCourseLog
     	}
     	}
     }
     }
 
 
-    /**
-     * This function gets all the information of a certrain ($field_id) additional profile field.
-     * It gets the information of all the users so that it can be displayed in the sortable table or in the csv or xls export
-     *
-     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
-     * @since October 2009
-     * @version 1.8.7
-     */
-    public function get_addtional_profile_information_of_field($field_id)
-    {
-    	// Database table definition
-        $table_user = Database::get_main_table(TABLE_MAIN_USER);
-        $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
-        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
-        $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
-
-    	$sql = "SELECT user.user_id, v.value
-    	        FROM $table_user user INNER JOIN $table_user_field_values v
-    	        ON (user.user_id = v.item_id
-    	        INNER JOIN $extraFieldTable f
-    	        ON (f.id = v.field_id)
-                WHERE
-                    f.extra_field_type = $extraFieldType AND
-                    v.field_id='".intval($field_id)."'";
-    	$result = Database::query($sql);
-    	while($row = Database::fetch_array($result)) {
-    		$return[$row['item_id']][] = $row['value'];
-    	}
-    	return $return;
-    }
-
     /**
     /**
      * This function gets all the information of a certrain ($field_id)
      * This function gets all the information of a certrain ($field_id)
      * additional profile field for a specific list of users is more efficent
      * additional profile field for a specific list of users is more efficent
@@ -6312,11 +6276,11 @@ class TrackingCourseLog
     {
     {
         global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
         global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
 
 
-    	$course_code        = Database::escape_string($course_code);
-    	$tbl_user           = Database::get_main_table(TABLE_MAIN_USER);
-    	$tbl_url_rel_user   = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+    	$course_code = Database::escape_string($course_code);
+    	$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+    	$tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
 
-    	$access_url_id      = api_get_current_access_url_id();
+    	$access_url_id = api_get_current_access_url_id();
 
 
     	// get all users data from a course for sortable with limit
     	// get all users data from a course for sortable with limit
     	if (is_array($user_ids)) {
     	if (is_array($user_ids)) {
@@ -6434,7 +6398,7 @@ class TrackingCourseLog
             );
             );
 
 
     		if (empty($avg_student_progress)) {
     		if (empty($avg_student_progress)) {
-    			$avg_student_progress=0;
+                $avg_student_progress = 0;
     		}
     		}
     		$user['average_progress'] = $avg_student_progress.'%';
     		$user['average_progress'] = $avg_student_progress.'%';
 
 
@@ -6649,16 +6613,16 @@ class TrackingUserLog
     		echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('ExercicesDetails')."<br />";
     		echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('ExercicesDetails')."<br />";
 
 
     		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
     		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
-                FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
-                WHERE te.c_id = $courseId
-                    AND te.exe_user_id = ".intval($user_id)."
-                    AND te.exe_exo_id = ce.id
-                ORDER BY ce.title ASC, te.exe_date ASC";
+                    FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
+                    WHERE te.c_id = $courseId
+                        AND te.exe_user_id = ".intval($user_id)."
+                        AND te.exe_exo_id = ce.id
+                    ORDER BY ce.title ASC, te.exe_date ASC";
 
 
     		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
     		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
-                FROM $TBL_TRACK_HOTPOTATOES AS te
-                WHERE te.exe_user_id = '".intval($user_id)."' AND te.c_id = $courseId
-                ORDER BY te.c_id ASC, te.exe_date ASC";
+                        FROM $TBL_TRACK_HOTPOTATOES AS te
+                        WHERE te.exe_user_id = '".intval($user_id)."' AND te.c_id = $courseId
+                        ORDER BY te.c_id ASC, te.exe_date ASC";
 
 
     		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
     		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
 
 
@@ -6696,21 +6660,22 @@ class TrackingUserLog
     		}
     		}
 
 
     		// The Result of Tests
     		// The Result of Tests
-    		if(is_array($hpresults)) {
+    		if (is_array($hpresults)) {
     			for($i = 0; $i < sizeof($hpresults); $i++) {
     			for($i = 0; $i < sizeof($hpresults); $i++) {
     				$title = GetQuizName($hpresults[$i][0],'');
     				$title = GetQuizName($hpresults[$i][0],'');
     				if ($title == '')
     				if ($title == '')
     				$title = basename($hpresults[$i][0]);
     				$title = basename($hpresults[$i][0]);
     				$display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
     				$display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
     				?>
     				?>
-<tr>
-    <td class="content"><?php echo $title; ?></td>
-    <td class="content" align="center"><?php echo $display_date; ?></td>
-    <td class="content" align="center"><?php echo $hpresults[$i][1]; ?> / <?php echo $hpresults[$i][2]; ?>
-    </td>
-</tr>
-
-<?php        }
+                    <tr>
+                        <td class="content"><?php echo $title; ?></td>
+                        <td class="content" align="center"><?php echo $display_date; ?></td>
+                        <td class="content" align="center"><?php echo $hpresults[$i][1]; ?> / <?php echo $hpresults[$i][2]; ?>
+                        </td>
+                    </tr>
+
+                    <?php
+                }
     		} else {
     		} else {
     			$NoHPTestRes = 1;
     			$NoHPTestRes = 1;
     		}
     		}
@@ -6739,7 +6704,9 @@ class TrackingUserLog
      */
      */
     public function display_student_publications_tracking_info($view, $user_id, $course_id)
     public function display_student_publications_tracking_info($view, $user_id, $course_id)
     {
     {
-    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
+    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
+        $_course = api_get_course_info_by_id($course_id);
+
     	if (substr($view,2,1) == '1') {
     	if (substr($view,2,1) == '1') {
     		$new_view = substr_replace($view,'0',2,1);
     		$new_view = substr_replace($view,'0',2,1);
     		echo "<tr>
     		echo "<tr>
@@ -6932,22 +6899,32 @@ class TrackingUserLog
      * @return string IP address (or false on error)
      * @return string IP address (or false on error)
      * @assert (0,0) === false
      * @assert (0,0) === false
      */
      */
-    public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null) {
+    public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null)
+    {
         if (empty($user_id) or empty($event_date)) {
         if (empty($user_id) or empty($event_date)) {
             return false;
             return false;
         }
         }
+        $user_id = intval($user_id);
+        $event_date = Database::escape_string($event_date);
+
         $table_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
         $table_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-        $sql_ip = "SELECT login_date, user_ip FROM $table_login WHERE login_user_id = $user_id AND login_date < '$event_date' ORDER BY login_date DESC LIMIT 1";
+        $sql_ip = "SELECT login_date, user_ip FROM $table_login
+                   WHERE login_user_id = $user_id AND login_date < '$event_date'
+                   ORDER BY login_date DESC LIMIT 1";
         $ip = '';
         $ip = '';
         $res_ip = Database::query($sql_ip);
         $res_ip = Database::query($sql_ip);
         if ($res_ip !== false && Database::num_rows($res_ip)>0) {
         if ($res_ip !== false && Database::num_rows($res_ip)>0) {
             $row_ip = Database::fetch_row($res_ip);
             $row_ip = Database::fetch_row($res_ip);
             if ($return_as_link) {
             if ($return_as_link) {
-                $ip = Display::url((empty($body_replace)?$row_ip[1]:$body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1], array('title'=>get_lang('TraceIP'), 'target'=>'_blank'));
+                $ip = Display::url(
+                    (empty($body_replace)?$row_ip[1]:$body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1],
+                    array('title'=>get_lang('TraceIP'), 'target'=>'_blank')
+                );
             } else {
             } else {
                 $ip = $row_ip[1];
                 $ip = $row_ip[1];
             }
             }
         }
         }
+
         return $ip;
         return $ip;
     }
     }
 }
 }
@@ -7024,16 +7001,16 @@ class TrackingUserLogCSV
     		$title[1] = get_lang('ExercicesDetails');
     		$title[1] = get_lang('ExercicesDetails');
     		$line = '';
     		$line = '';
     		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
     		$sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
-                FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
-                WHERE te.c_id = $courseId
-                    AND te.exe_user_id = $userId
-                    AND te.exe_exo_id = ce.id
-                ORDER BY ce.title ASC, te.exe_date ASC";
+                    FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
+                    WHERE te.c_id = $courseId
+                        AND te.exe_user_id = $userId
+                        AND te.exe_exo_id = ce.id
+                    ORDER BY ce.title ASC, te.exe_date ASC";
 
 
     		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
     		$hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
-                FROM $TABLETRACK_HOTPOTATOES AS te
-                WHERE te.exe_user_id = '$userId' AND te.c_id = $courseId
-                ORDER BY te.c_id ASC, te.exe_date ASC";
+                        FROM $TABLETRACK_HOTPOTATOES AS te
+                        WHERE te.exe_user_id = '$userId' AND te.c_id = $courseId
+                        ORDER BY te.c_id ASC, te.exe_date ASC";
 
 
     		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
     		$hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
 
 
@@ -7085,7 +7062,8 @@ class TrackingUserLogCSV
      */
      */
     public function display_student_publications_tracking_info($view, $user_id, $course_id)
     public function display_student_publications_tracking_info($view, $user_id, $course_id)
     {
     {
-    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
+    	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
+        $_course = api_get_course_info();
         $user_id = intval($user_id);
         $user_id = intval($user_id);
         $course_id = intval($course_id);
         $course_id = intval($course_id);
 
 

+ 39 - 35
main/inc/lib/urlmanager.lib.php

@@ -23,8 +23,8 @@ class UrlManager
     public static function add($url, $description, $active)
     public static function add($url, $description, $active)
     {
     {
         $tms = time();
         $tms = time();
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql = "INSERT INTO $table_access_url
+        $table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "INSERT INTO $table
                 SET url 	= '".Database::escape_string($url)."',
                 SET url 	= '".Database::escape_string($url)."',
                 description = '".Database::escape_string($description)."',
                 description = '".Database::escape_string($description)."',
                 active 		= '".intval($active)."',
                 active 		= '".intval($active)."',
@@ -46,9 +46,9 @@ class UrlManager
     public static function update($url_id, $url, $description, $active)
     public static function update($url_id, $url, $description, $active)
     {
     {
         $url_id = intval($url_id);
         $url_id = intval($url_id);
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
         $tms = time();
         $tms = time();
-        $sql = "UPDATE $table_access_url
+        $sql = "UPDATE $table
                 SET url 	= '".Database::escape_string($url)."',
                 SET url 	= '".Database::escape_string($url)."',
                 description = '".Database::escape_string($description)."',
                 description = '".Database::escape_string($description)."',
                 active 		= '".intval($active)."',
                 active 		= '".intval($active)."',
@@ -56,6 +56,7 @@ class UrlManager
                 tms 		= FROM_UNIXTIME(".$tms.")
                 tms 		= FROM_UNIXTIME(".$tms.")
                 WHERE id = '$url_id'";
                 WHERE id = '$url_id'";
         $result = Database::query($sql);
         $result = Database::query($sql);
+
         return $result;
         return $result;
     }
     }
 
 
@@ -68,9 +69,10 @@ class UrlManager
     public static function delete($id)
     public static function delete($id)
     {
     {
         $id = intval($id);
         $id = intval($id);
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql= "DELETE FROM $table_access_url WHERE id = ".$id;
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql= "DELETE FROM $table WHERE id = ".$id;
         $result = Database::query($sql);
         $result = Database::query($sql);
+
         return $result;
         return $result;
     }
     }
 
 
@@ -80,10 +82,11 @@ class UrlManager
      */
      */
     public static function url_exist($url)
     public static function url_exist($url)
     {
     {
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql = "SELECT id FROM $table_access_url WHERE url = '".Database::escape_string($url)."' ";
+        $table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "SELECT id FROM $table WHERE url = '".Database::escape_string($url)."' ";
         $res = Database::query($sql);
         $res = Database::query($sql);
         $num = Database::num_rows($res);
         $num = Database::num_rows($res);
+
         return $num;
         return $num;
     }
     }
 
 
@@ -94,10 +97,11 @@ class UrlManager
     public static function url_id_exist($url)
     public static function url_id_exist($url)
     {
     {
         if (empty($url)) { return false; }
         if (empty($url)) { return false; }
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql = "SELECT id FROM $table_access_url WHERE id = ".intval($url)."";
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "SELECT id FROM $table WHERE id = ".intval($url)."";
         $res = Database::query($sql);
         $res = Database::query($sql);
         $num = Database::num_rows($res);
         $num = Database::num_rows($res);
+
         return $num;
         return $num;
     }
     }
 
 
@@ -113,6 +117,7 @@ class UrlManager
         $res = Database::query($sql);
         $res = Database::query($sql);
         $url = Database::fetch_array($res,'ASSOC');
         $url = Database::fetch_array($res,'ASSOC');
         $result = $url['count_result'];
         $result = $url['count_result'];
+
         return $result;
         return $result;
     }
     }
 
 
@@ -123,8 +128,8 @@ class UrlManager
      * */
      * */
     public static function get_url_data()
     public static function get_url_data()
     {
     {
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql = "SELECT id, url, description, active FROM $table_access_url ORDER BY id";
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "SELECT id, url, description, active FROM $table ORDER BY id";
         $res = Database::query($sql);
         $res = Database::query($sql);
         $urls = array ();
         $urls = array ();
         while ($url = Database::fetch_array($res)) {
         while ($url = Database::fetch_array($res)) {
@@ -142,8 +147,8 @@ class UrlManager
      * */
      * */
     public static function get_url_data_from_id($url_id)
     public static function get_url_data_from_id($url_id)
     {
     {
-        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-        $sql = "SELECT id, url, description, active FROM $table_access_url WHERE id = ".intval($url_id);
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql = "SELECT id, url, description, active FROM $table WHERE id = ".intval($url_id);
         $res = Database::query($sql);
         $res = Database::query($sql);
         $row = Database::fetch_array($res);
         $row = Database::fetch_array($res);
         return $row;
         return $row;
@@ -158,7 +163,7 @@ class UrlManager
      **/
      **/
     public static function get_url_rel_user_data($access_url_id = null, $order_by = null)
     public static function get_url_rel_user_data($access_url_id = null, $order_by = null)
     {
     {
-        $where              = '';
+        $where = '';
         $table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $tbl_user           = Database :: get_main_table(TABLE_MAIN_USER);
         $tbl_user           = Database :: get_main_table(TABLE_MAIN_USER);
         if (!empty($access_url_id)) {
         if (!empty($access_url_id)) {
@@ -171,10 +176,10 @@ class UrlManager
             $order_clause = $order_by;
             $order_clause = $order_by;
         }
         }
         $sql = "SELECT u.user_id, lastname, firstname, username, official_code, access_url_id
         $sql = "SELECT u.user_id, lastname, firstname, username, official_code, access_url_id
-			FROM $tbl_user u
-			INNER JOIN $table_url_rel_user
-			ON $table_url_rel_user.user_id = u.user_id
-			$where  $order_clause";
+                FROM $tbl_user u
+                INNER JOIN $table_url_rel_user
+                ON $table_url_rel_user.user_id = u.user_id
+                $where  $order_clause";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $users = Database::store_result($result);
         $users = Database::store_result($result);
 
 
@@ -239,13 +244,13 @@ class UrlManager
     public static function get_url_rel_session_data($access_url_id = null)
     public static function get_url_rel_session_data($access_url_id = null)
     {
     {
         $where ='';
         $where ='';
-        $table_url_rel_session	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-        $tbl_session 			= Database :: get_main_table(TABLE_MAIN_SESSION);
+        $table_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
 
 
         if (!empty($access_url_id))
         if (!empty($access_url_id))
             $where ="WHERE $table_url_rel_session.access_url_id = ".intval($access_url_id);
             $where ="WHERE $table_url_rel_session.access_url_id = ".intval($access_url_id);
 
 
-        $sql="SELECT id, name, access_url_id
+        $sql = "SELECT id, name, access_url_id
                 FROM $tbl_session u
                 FROM $tbl_session u
                 INNER JOIN $table_url_rel_session
                 INNER JOIN $table_url_rel_session
                 ON $table_url_rel_session.session_id = id
                 ON $table_url_rel_session.session_id = id
@@ -306,11 +311,11 @@ class UrlManager
         $where .= " AND (parent_id IS NULL) ";
         $where .= " AND (parent_id IS NULL) ";
 
 
         $sql = "SELECT id, name, access_url_id
         $sql = "SELECT id, name, access_url_id
-            FROM $table u
-            INNER JOIN $table_url_rel
-            ON $table_url_rel.course_category_id = u.id
-            $where
-            ORDER BY name";
+                FROM $table u
+                INNER JOIN $table_url_rel
+                ON $table_url_rel.course_category_id = u.id
+                $where
+                ORDER BY name";
 
 
         $result = Database::query($sql);
         $result = Database::query($sql);
         $courses = Database::store_result($result, 'ASSOC');
         $courses = Database::store_result($result, 'ASSOC');
@@ -332,11 +337,10 @@ class UrlManager
         if ($status == 'unlock') {
         if ($status == 'unlock') {
             $status_db = '1';
             $status_db = '1';
         }
         }
-        if (($status_db == '1' OR $status_db == '0') AND is_numeric($url_id)) {
-            $sql    = "UPDATE $url_table SET active='".intval(
-                    $status_db
-                )."' WHERE id='".intval($url_id)."'";
-            $result = Database::query($sql);
+        if (($status_db == '1' || $status_db == '0') && is_numeric($url_id)) {
+            $sql = "UPDATE $url_table SET active='".intval($status_db)."'
+                    WHERE id='".intval($url_id)."'";
+            Database::query($sql);
         }
         }
     }
     }
 
 
@@ -349,9 +353,9 @@ class UrlManager
     * */
     * */
     public static function relation_url_user_exist($user_id, $url_id)
     public static function relation_url_user_exist($user_id, $url_id)
     {
     {
-        $table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        $sql= "SELECT user_id FROM $table_url_rel_user
-               WHERE access_url_id = ".intval($url_id)." AND  user_id = ".intval($user_id)." ";
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $sql= "SELECT user_id FROM $table
+               WHERE access_url_id = ".intval($url_id)." AND user_id = ".intval($user_id)." ";
         $result = Database::query($sql);
         $result = Database::query($sql);
         $num = Database::num_rows($result);
         $num = Database::num_rows($result);
 
 

+ 22 - 7
main/inc/lib/usermanager.lib.php

@@ -362,13 +362,23 @@ class UserManager
             }
             }
 
 
             if (!empty($email) && $send_mail) {
             if (!empty($email) && $send_mail) {
-                $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
+                $recipient_name = api_get_person_name(
+                    $firstName,
+                    $lastName,
+                    null,
+                    PERSON_NAME_EMAIL_ADDRESS
+                );
                 $tplSubject = new Template(null, false, false, false, false, false);
                 $tplSubject = new Template(null, false, false, false, false, false);
                 $layoutSubject = $tplSubject->get_template(
                 $layoutSubject = $tplSubject->get_template(
                     'mail/subject_registration_platform.tpl'
                     'mail/subject_registration_platform.tpl'
                 );
                 );
                 $emailSubject = $tplSubject->fetch($layoutSubject);
                 $emailSubject = $tplSubject->fetch($layoutSubject);
-                $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+                $sender_name = api_get_person_name(
+                    api_get_setting('administratorName'),
+                    api_get_setting('administratorSurname'),
+                    null,
+                    PERSON_NAME_EMAIL_ADDRESS
+                );
                 $email_admin = api_get_setting('emailAdministrator');
                 $email_admin = api_get_setting('emailAdministrator');
 
 
                 if (api_is_multiple_url_enabled()) {
                 if (api_is_multiple_url_enabled()) {
@@ -667,6 +677,7 @@ class UserManager
             $deleted = self::delete_user($id);
             $deleted = self::delete_user($id);
             $result = $deleted || $result;
             $result = $deleted || $result;
         }
         }
+
         return $result;
         return $result;
     }
     }
 
 
@@ -955,6 +966,7 @@ class UserManager
         if ($r !== false) {
         if ($r !== false) {
             Event::addEvent($ev, LOG_USER_ID, $user_id);
             Event::addEvent($ev, LOG_USER_ID, $user_id);
         }
         }
+
         return $r;
         return $r;
     }
     }
 
 
@@ -1437,7 +1449,6 @@ class UserManager
                 $userPath = api_get_path(REL_UPLOAD_PATH).$userPath;
                 $userPath = api_get_path(REL_UPLOAD_PATH).$userPath;
                 break;
                 break;
             case 'last': // Only the last part starting with users/
             case 'last': // Only the last part starting with users/
-                $userPath = $userPath;
                 break;
                 break;
         }
         }
 
 
@@ -1702,6 +1713,7 @@ class UserManager
      *
      *
      * @param    int $user_id    User id
      * @param    int $user_id    User id
      * @param    $force    Optional parameter to force building after a removal request
      * @param    $force    Optional parameter to force building after a removal request
+     *
      * @return    A string containing the XHTML code to dipslay the production list, or FALSE
      * @return    A string containing the XHTML code to dipslay the production list, or FALSE
      */
      */
     public static function build_production_list($user_id, $force = false, $showdelete = false)
     public static function build_production_list($user_id, $force = false, $showdelete = false)
@@ -1773,8 +1785,8 @@ class UserManager
     /**
     /**
      * Remove a user production.
      * Remove a user production.
      *
      *
-     * @param    $user_id        User id
-     * @param    $production    The production to remove
+     * @param   int $user_id        User id
+     * @param   string $production    The production to remove
      */
      */
     public static function remove_user_production($user_id, $production)
     public static function remove_user_production($user_id, $production)
     {
     {
@@ -1963,6 +1975,7 @@ class UserManager
                 $files[] = $path.$extra_files;
                 $files[] = $path.$extra_files;
             }
             }
         }
         }
+
         return $files; // can be an empty array
         return $files; // can be an empty array
     }
     }
 
 
@@ -2114,6 +2127,7 @@ class UserManager
                 }
                 }
             }
             }
         }
         }
+
         return $extra_data;
         return $extra_data;
     }
     }
 
 
@@ -2141,7 +2155,8 @@ class UserManager
         $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
         $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
         $user_id = intval($user_id);
         $user_id = intval($user_id);
 
 
-        $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type FROM $t_uf f
+        $sql = "SELECT f.id as id, f.variable as fvar, f.field_type as type
+                FROM $t_uf f
                 WHERE f.variable = '$field_variable' ";
                 WHERE f.variable = '$field_variable' ";
 
 
         if (!$all_visibility) {
         if (!$all_visibility) {
@@ -2967,7 +2982,7 @@ class UserManager
         if (empty($api_service))
         if (empty($api_service))
             return false;
             return false;
         $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
         $t_api = Database::get_main_table(TABLE_MAIN_USER_API_KEY);
-        $service_name = Database::escape_string($api_service);
+        $api_service = Database::escape_string($api_service);
         $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
         $sql = "SELECT id FROM $t_api WHERE user_id=".$user_id." AND api_service='".$api_service."'";
         $res = Database::query($sql);
         $res = Database::query($sql);
         if (Database::num_rows($res) < 1) {
         if (Database::num_rows($res) < 1) {

+ 48 - 19
main/inc/lib/userportal.lib.php

@@ -45,10 +45,13 @@ class IndexManager
         $exercise_list = array();
         $exercise_list = array();
         if (!empty($personal_course_list)) {
         if (!empty($personal_course_list)) {
             foreach($personal_course_list as  $course_item) {
             foreach($personal_course_list as  $course_item) {
-                $course_code     = $course_item['c'];
-                $session_id     = $course_item['id_session'];
+                $course_code = $course_item['c'];
+                $session_id = $course_item['id_session'];
 
 
-                $exercises = ExerciseLib::get_exercises_to_be_taken($course_code, $session_id);
+                $exercises = ExerciseLib::get_exercises_to_be_taken(
+                    $course_code,
+                    $session_id
+                );
 
 
                 foreach($exercises as $exercise_item) {
                 foreach($exercises as $exercise_item) {
                     $exercise_item['course_code']     = $course_code;
                     $exercise_item['course_code']     = $course_code;
@@ -68,7 +71,8 @@ class IndexManager
         }
         }
     }
     }
 
 
-    function return_announcements($show_slide = true) {
+    function return_announcements($show_slide = true)
+    {
         //// Display System announcements
         //// Display System announcements
         $hideAnnouncements = api_get_setting('hide_global_announcements_when_not_connected');
         $hideAnnouncements = api_get_setting('hide_global_announcements_when_not_connected');
         if ($hideAnnouncements == 'true' && empty($userId)) {
         if ($hideAnnouncements == 'true' && empty($userId)) {
@@ -80,17 +84,30 @@ class IndexManager
         if (!api_is_anonymous() && $this->user_id) {
         if (!api_is_anonymous() && $this->user_id) {
             $visibility = api_is_allowed_to_create_course() ? SystemAnnouncementManager::VISIBLE_TEACHER : SystemAnnouncementManager::VISIBLE_STUDENT;
             $visibility = api_is_allowed_to_create_course() ? SystemAnnouncementManager::VISIBLE_TEACHER : SystemAnnouncementManager::VISIBLE_STUDENT;
             if ($show_slide) {
             if ($show_slide) {
-                $announcements = SystemAnnouncementManager :: display_announcements_slider($visibility, $announcement);
+                $announcements = SystemAnnouncementManager:: display_announcements_slider(
+                    $visibility,
+                    $announcement
+                );
             } else {
             } else {
-                $announcements = SystemAnnouncementManager :: display_all_announcements($visibility, $announcement);
+                $announcements = SystemAnnouncementManager:: display_all_announcements(
+                    $visibility,
+                    $announcement
+                );
             }
             }
         } else {
         } else {
             if ($show_slide) {
             if ($show_slide) {
-                $announcements = SystemAnnouncementManager :: display_announcements_slider(SystemAnnouncementManager::VISIBLE_GUEST, $announcement);
+                $announcements = SystemAnnouncementManager:: display_announcements_slider(
+                    SystemAnnouncementManager::VISIBLE_GUEST,
+                    $announcement
+                );
             } else {
             } else {
-                $announcements = SystemAnnouncementManager :: display_all_announcements(SystemAnnouncementManager::VISIBLE_GUEST, $announcement);
+                $announcements = SystemAnnouncementManager:: display_all_announcements(
+                    SystemAnnouncementManager::VISIBLE_GUEST,
+                    $announcement
+                );
             }
             }
         }
         }
+
         return $announcements;
         return $announcements;
     }
     }
 
 
@@ -98,7 +115,8 @@ class IndexManager
      * Alias for the online_logout() function
      * Alias for the online_logout() function
      * @param   bool    $redirect   Whether to ask online_logout to redirect to index.php or not
      * @param   bool    $redirect   Whether to ask online_logout to redirect to index.php or not
      */
      */
-    function logout($redirect = true) {
+    function logout($redirect = true)
+    {
         online_logout($this->user_id, true);
         online_logout($this->user_id, true);
     }
     }
 
 
@@ -108,7 +126,8 @@ class IndexManager
      * @param string $category
      * @param string $category
      * @return boolean
      * @return boolean
      */
      */
-    function category_has_open_courses($category) {
+    function category_has_open_courses($category)
+    {
         $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
         $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
         $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
         $main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
         $category = Database::escape_string($category);
         $category = Database::escape_string($category);
@@ -125,6 +144,7 @@ class IndexManager
                 }
                 }
             }
             }
         }
         }
+
         return false;
         return false;
     }
     }
 
 
@@ -136,7 +156,8 @@ class IndexManager
      * @version 1.0.1
      * @version 1.0.1
      * @todo does $_plugins need to be global?
      * @todo does $_plugins need to be global?
      */
      */
-    function display_anonymous_right_menu() {
+    function display_anonymous_right_menu()
+    {
         global $loginFailed, $_user;
         global $loginFailed, $_user;
         $display_add_course_link    = api_is_allowed_to_create_course() && ($_SESSION['studentview'] != 'studentenview');
         $display_add_course_link    = api_is_allowed_to_create_course() && ($_SESSION['studentview'] != 'studentenview');
         $current_user_id            = api_get_user_id();
         $current_user_id            = api_get_user_id();
@@ -207,7 +228,6 @@ class IndexManager
     public function return_home_page()
     public function return_home_page()
     {
     {
         $userId = api_get_user_id();
         $userId = api_get_user_id();
-        global $_configuration;
         // Including the page for the news
         // Including the page for the news
         $html = '';
         $html = '';
 
 
@@ -257,7 +277,8 @@ class IndexManager
 		return $html;
 		return $html;
 	}
 	}
 
 
-    function return_notice() {
+    function return_notice()
+    {
         $sys_path               = api_get_path(SYS_PATH);
         $sys_path               = api_get_path(SYS_PATH);
         $user_selected_language = api_get_interface_language();
         $user_selected_language = api_get_interface_language();
 
 
@@ -276,7 +297,8 @@ class IndexManager
         return $html;
         return $html;
     }
     }
 
 
-    function return_help() {
+    function return_help()
+    {
         $user_selected_language = api_get_interface_language();
         $user_selected_language = api_get_interface_language();
         $sys_path               = api_get_path(SYS_PATH);
         $sys_path               = api_get_path(SYS_PATH);
         $platformLanguage       = api_get_setting('platformLanguage');
         $platformLanguage       = api_get_setting('platformLanguage');
@@ -299,8 +321,8 @@ class IndexManager
         return $html;
         return $html;
     }
     }
 
 
-    function return_skills_links() {
-        $html = '';
+    function return_skills_links()
+    {
         $content = '';
         $content = '';
         $content .= '<ul class="nav nav-pills nav-stacked">';
         $content .= '<ul class="nav nav-pills nav-stacked">';
         /**
         /**
@@ -350,7 +372,15 @@ class IndexManager
             }
             }
         }
         }
         $content .= '</ul>';
         $content .= '</ul>';
-        $html = self::show_right_block(get_lang("Skills"), $content, 'skill_block',null, 'skills', 'skillsCollapse');
+        $html = self::show_right_block(
+            get_lang("Skills"),
+            $content,
+            'skill_block',
+            null,
+            'skills',
+            'skillsCollapse'
+        );
+
         return $html;
         return $html;
     }
     }
 
 
@@ -394,7 +424,6 @@ class IndexManager
                                     ORDER BY title, UPPER(visual_code)";
                                     ORDER BY title, UPPER(visual_code)";
 
 
         // Showing only the courses of the current access_url_id.
         // Showing only the courses of the current access_url_id.
-        global $_configuration;
         if (api_is_multiple_url_enabled()) {
         if (api_is_multiple_url_enabled()) {
             $url_access_id = api_get_current_access_url_id();
             $url_access_id = api_get_current_access_url_id();
             if ($url_access_id != -1) {
             if ($url_access_id != -1) {
@@ -692,7 +721,7 @@ class IndexManager
             $html .= '<div id="'.$idCollpase.'" class="panel-collapse collapse in" role="tabpanel">' . PHP_EOL;
             $html .= '<div id="'.$idCollpase.'" class="panel-collapse collapse in" role="tabpanel">' . PHP_EOL;
             $html .= '<div class="panel-body">'.$content.'</div>' . PHP_EOL;
             $html .= '<div class="panel-body">'.$content.'</div>' . PHP_EOL;
             $html .= '</div></div></div>' . PHP_EOL;
             $html .= '</div></div></div>' . PHP_EOL;
-            
+
         } else {
         } else {
             if (!empty($id)) {
             if (!empty($id)) {
                 $params['id'] = $id;
                 $params['id'] = $id;

+ 1 - 1
main/social/group_add.php

@@ -29,7 +29,7 @@ if ($form->validate()) {
     $values['group_type'] = UserGroup::SOCIAL_CLASS;
     $values['group_type'] = UserGroup::SOCIAL_CLASS;
     $values['relation_type'] = GROUP_USER_PERMISSION_ADMIN;
     $values['relation_type'] = GROUP_USER_PERMISSION_ADMIN;
     $groupId = $usergroup->save($values);
     $groupId = $usergroup->save($values);
-    Display::addFlash(DIsplay::return_message(get_lang('GroupAdded')));
+    Display::addFlash(Display::return_message(get_lang('GroupAdded')));
     header('Location: group_view.php?id='.$groupId);
     header('Location: group_view.php?id='.$groupId);
     exit();
     exit();
 }
 }

+ 8 - 6
main/social/group_topics.php

@@ -40,9 +40,11 @@ if (empty($group_id)) {
 if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete') {
 if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete') {
     $group_role = $usergroup->get_user_group_role(api_get_user_id(), $group_id);
     $group_role = $usergroup->get_user_group_role(api_get_user_id(), $group_id);
 
 
-    if (api_is_platform_admin() || in_array($group_role, array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR))) {
+    if (api_is_platform_admin() ||
+        in_array($group_role, array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR))
+    ) {
         $usergroup->delete_topic($group_id, $topic_id);
         $usergroup->delete_topic($group_id, $topic_id);
-        Display::addFlash(DIsplay::return_message(get_lang('Deleted')));
+        Display::addFlash(Display::return_message(get_lang('Deleted')));
         header("Location: group_view.php?id=$group_id");
         header("Location: group_view.php?id=$group_id");
         exit;
         exit;
     }
     }
@@ -52,10 +54,10 @@ $content = null;
 $social_right_content = '';
 $social_right_content = '';
 
 
 if (isset($_POST['action'])) {
 if (isset($_POST['action'])) {
-    $title        = isset($_POST['title']) ? $_POST['title'] : null;
-    $content      = $_POST['content'];
-    $group_id     = intval($_POST['group_id']);
-    $parent_id    = intval($_POST['parent_id']);
+    $title = isset($_POST['title']) ? $_POST['title'] : null;
+    $content = $_POST['content'];
+    $group_id = intval($_POST['group_id']);
+    $parent_id = intval($_POST['parent_id']);
 
 
     if ($_POST['action'] == 'reply_message_group') {
     if ($_POST['action'] == 'reply_message_group') {
         $title = cut($content, 50);
         $title = cut($content, 50);

+ 5 - 3
main/social/group_view.php

@@ -205,7 +205,7 @@ if ($is_group_member || $group_info['visibility'] == GROUP_PERMISSION_OPEN) {
                     'view_panel' => 1,
                     'view_panel' => 1,
                     'user_friend' => api_get_user_id(),
                     'user_friend' => api_get_user_id(),
                     'group_id' => $group_id,
                     'group_id' => $group_id,
-                    'action' => add_message_group,
+                    'action' => 'add_message_group',
                 ]);
                 ]);
             $create_thread_link = Display::url(
             $create_thread_link = Display::url(
                 get_lang('NewTopic'),
                 get_lang('NewTopic'),
@@ -232,13 +232,15 @@ if ($is_group_member || $group_info['visibility'] == GROUP_PERMISSION_OPEN) {
         }
         }
         foreach ($members as $member) {
         foreach ($members as $member) {
             // if is a member
             // if is a member
-            if (in_array($member['relation_type'], array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_READER,GROUP_USER_PERMISSION_MODERATOR))) {
+            if (in_array($member['relation_type'],
+                array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_READER,GROUP_USER_PERMISSION_MODERATOR))
+            ) {
                 //add icons
                 //add icons
                 if ($member['relation_type'] == GROUP_USER_PERMISSION_ADMIN) {
                 if ($member['relation_type'] == GROUP_USER_PERMISSION_ADMIN) {
                     $icon= Display::return_icon('social_group_admin.png', get_lang('Admin'));
                     $icon= Display::return_icon('social_group_admin.png', get_lang('Admin'));
                 } elseif ($member['relation_type'] == GROUP_USER_PERMISSION_MODERATOR) {
                 } elseif ($member['relation_type'] == GROUP_USER_PERMISSION_MODERATOR) {
                     $icon= Display::return_icon('social_group_moderator.png', get_lang('Moderator'));
                     $icon= Display::return_icon('social_group_moderator.png', get_lang('Moderator'));
-                } else{
+                } else {
                     $icon= '';
                     $icon= '';
                 }
                 }
 
 

+ 1 - 1
main/social/search.php

@@ -68,7 +68,7 @@ if ($query != '' || ($query_vars['search_type']=='1' && count($query_vars)>2) )
     }
     }
 
 
     if (empty($users) && empty($groups)) {
     if (empty($users) && empty($groups)) {
-        $social_right_content .= get_lang('SorryNoResults');
+        Display::addFlash(Display::return_message(get_lang('SorryNoResults')));
     }
     }
 
 
     $results = '<div id="online_grid_container">';
     $results = '<div id="online_grid_container">';

+ 119 - 113
main/template/default/auth/courses_categories.php

@@ -108,7 +108,7 @@ $code = isset($code) ? $code : null;
 <div class="row">
 <div class="row">
     <div class="col-md-4">
     <div class="col-md-4">
         <h5><?php echo get_lang('Search'); ?></h5>
         <h5><?php echo get_lang('Search'); ?></h5>
-        <?php 
+        <?php
         if ($showCourses) {
         if ($showCourses) {
             if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) { ?>
             if (!isset($_GET['hidden_links']) || intval($_GET['hidden_links']) != 1) { ?>
             <form class="form-horizontal" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
             <form class="form-horizontal" method="post" action="<?php echo getCourseCategoryUrl(1, $pageLength, 'ALL', 0, 'subscribe'); ?>">
@@ -127,8 +127,8 @@ $code = isset($code) ? $code : null;
     </div>
     </div>
     <div class="col-md-4">
     <div class="col-md-4">
         <h5><?php echo get_lang('CourseCategories'); ?></h5>
         <h5><?php echo get_lang('CourseCategories'); ?></h5>
-        <?php      
-                   
+        <?php
+
             $webAction = api_get_path(WEB_CODE_PATH).'auth/courses.php';
             $webAction = api_get_path(WEB_CODE_PATH).'auth/courses.php';
             $action = (!empty($_REQUEST['action'])?Security::remove_XSS($_REQUEST['action']):'display_courses');
             $action = (!empty($_REQUEST['action'])?Security::remove_XSS($_REQUEST['action']):'display_courses');
             $pageLength = (!empty($_REQUEST['pageLength'])?intval($_REQUEST['pageLength']):10);
             $pageLength = (!empty($_REQUEST['pageLength'])?intval($_REQUEST['pageLength']):10);
@@ -140,11 +140,11 @@ $code = isset($code) ? $code : null;
             $form .= '<div class="form-group">';
             $form .= '<div class="form-group">';
             $form .= '<div class="col-sm-12">';
             $form .= '<div class="col-sm-12">';
             $form .= '<select name="category_code" onchange="submit();" class="chzn-select form-control">';
             $form .= '<select name="category_code" onchange="submit();" class="chzn-select form-control">';
-            $codeType = Security::remove_XSS($_REQUEST['category_code']);    
+            $codeType = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : '';
             foreach ($browse_course_categories[0] as $category) {
             foreach ($browse_course_categories[0] as $category) {
                 $categoryCode = $category['code'];
                 $categoryCode = $category['code'];
                 $countCourse = $category['count_courses'];
                 $countCourse = $category['count_courses'];
-                       
+
                 $form .= '<option '. ($categoryCode == $codeType? 'selected="selected" ':'') .' value="' . $category['code'] . '">' . $category['name'] . ' ( '. $countCourse .' ) </option>';
                 $form .= '<option '. ($categoryCode == $codeType? 'selected="selected" ':'') .' value="' . $category['code'] . '">' . $category['name'] . ' ( '. $countCourse .' ) </option>';
                 if (!empty($browse_course_categories[$categoryCode])) {
                 if (!empty($browse_course_categories[$categoryCode])) {
                     foreach ($browse_course_categories[$categoryCode] as $subCategory){
                     foreach ($browse_course_categories[$categoryCode] as $subCategory){
@@ -155,128 +155,129 @@ $code = isset($code) ? $code : null;
             }
             }
             $form .= '</select>';
             $form .= '</select>';
             $form .= '</div>';
             $form .= '</div>';
-            $from .= '</form>';
+            $form .= '</form>';
             echo $form;
             echo $form;
         ?>
         ?>
     </div>
     </div>
     </div>
     </div>
 <?php
 <?php
-        
-        if ($showSessions) { ?>
-            <div class="col-md-4">
-                <h5><?php echo get_lang('Sessions'); ?></h5>
-                <a class="btn btn-default btn-block" href="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>"><?php echo get_lang('SessionList'); ?></a>
-            </div>
-        <?php } ?>
+    if ($showSessions) { ?>
+        <div class="col-md-4">
+            <h5><?php echo get_lang('Sessions'); ?></h5>
+            <a class="btn btn-default btn-block" href="<?php echo getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions'); ?>">
+                <?php echo get_lang('SessionList'); ?>
+            </a>
+        </div>
+    <?php } ?>
 </div>
 </div>
  <?php  } ?>
  <?php  } ?>
-<div class="row"> 
- <?php if ($showCourses && $action != 'display_sessions') { 
-            
+<div class="row">
+<?php
+if ($showCourses && $action != 'display_sessions') {
 
 
-            if (!empty($message)) {
-                Display::display_confirmation_message($message, false);
-            }
-            if (!empty($error)) {
-                Display::display_error_message($error, false);
-            }
+    if (!empty($message)) {
+        Display::display_confirmation_message($message, false);
+    }
+    if (!empty($error)) {
+        Display::display_error_message($error, false);
+    }
 
 
-            if (!empty($content)) {
-                echo $content;
-            }
+    if (!empty($content)) {
+        echo $content;
+    }
 
 
-            if (!empty($search_term)) {
-                echo "<p><strong>".get_lang('SearchResultsFor')." ".Security::remove_XSS($_POST['search_term'])."</strong><br />";
-            }
+    if (!empty($search_term)) {
+        echo "<p><strong>".get_lang('SearchResultsFor')." ".Security::remove_XSS($_POST['search_term'])."</strong><br />";
+    }
+
+    $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
+    $user_id = api_get_user_id();
+
+    if (!empty($browse_courses_in_category)) {
+        foreach ($browse_courses_in_category as $course) {
+            $course_hidden = ($course['visibility'] == COURSE_VISIBILITY_HIDDEN);
 
 
-            $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
-            $user_id = api_get_user_id();
-            
-            if (!empty($browse_courses_in_category)) {
-                foreach ($browse_courses_in_category as $course) {
-                    $course_hidden = ($course['visibility'] == COURSE_VISIBILITY_HIDDEN);
+            if ($course_hidden) {
+                continue;
+            }
 
 
-                    if ($course_hidden) {
-                        continue;
+            $user_registerd_in_course = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
+            $user_registerd_in_course_as_teacher = CourseManager::is_course_teacher($user_id, $course['code']);
+            $user_registerd_in_course_as_student = ($user_registerd_in_course && !$user_registerd_in_course_as_teacher);
+            $course_public = ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
+            $course_open = ($course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
+            $course_private = ($course['visibility'] == COURSE_VISIBILITY_REGISTERED);
+            $course_closed = ($course['visibility'] == COURSE_VISIBILITY_CLOSED);
+
+            $course_subscribe_allowed = ($course['subscribe'] == 1);
+            $course_unsubscribe_allowed = ($course['unsubscribe'] == 1);
+            $count_connections = $course['count_connections'];
+            $creation_date = substr($course['creation_date'],0,10);
+
+            $icon_title = null;
+            $html = null;
+            // display the course bloc
+            $html .= '<div class="col-md-3"><div class="items-course">';
+
+            // display thumbnail
+            $html .= return_thumbnail($course, $icon_title);
+
+            // display course title and button bloc
+            $html .= '<div class="items-course-info">';
+            $html .= return_title($course);
+            // display button line
+            $html .= '<div class="btn-toolbar">';
+            // if user registered as student
+            if ($user_registerd_in_course_as_student) {
+                if (!$course_closed) {
+                    if ($course_unsubscribe_allowed) {
+                        $html .= return_unregister_button($course, $stok, $search_term, $code);
                     }
                     }
+                    $html .= return_already_registered_label('student');
+                }
+                $html .= return_description_button($course, $icon_title);
+            } elseif ($user_registerd_in_course_as_teacher) {
+                // if user registered as teacher
+                //$html .= return_goto_button($course);
 
 
-                    $user_registerd_in_course = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
-                    $user_registerd_in_course_as_teacher = CourseManager::is_course_teacher($user_id, $course['code']);
-                    $user_registerd_in_course_as_student = ($user_registerd_in_course && !$user_registerd_in_course_as_teacher);
-                    $course_public = ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
-                    $course_open = ($course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
-                    $course_private = ($course['visibility'] == COURSE_VISIBILITY_REGISTERED);
-                    $course_closed = ($course['visibility'] == COURSE_VISIBILITY_CLOSED);
-                  
-                    $course_subscribe_allowed = ($course['subscribe'] == 1);
-                    $course_unsubscribe_allowed = ($course['unsubscribe'] == 1);
-                    $count_connections = $course['count_connections'];
-                    $creation_date = substr($course['creation_date'],0,10);
-
-                    $icon_title = null;
-                    $html = null;
-                    // display the course bloc
-                    $html .= '<div class="col-md-3"><div class="items-course">';
-
-                    // display thumbnail
-                    $html .= return_thumbnail($course, $icon_title);
-
-                    // display course title and button bloc
-                    $html .= '<div class="items-course-info">';
-                    $html .= return_title($course);
-                    // display button line
-                    $html .= '<div class="btn-toolbar">';
-                    // if user registered as student
-                    if ($user_registerd_in_course_as_student) {
-                        if (!$course_closed) {                        
-                            if ($course_unsubscribe_allowed) {
-                                $html .= return_unregister_button($course, $stok, $search_term, $code);
-                            }
-                            $html .= return_already_registered_label('student');
-                        }
-                        $html .= return_description_button($course, $icon_title);
-                    } elseif ($user_registerd_in_course_as_teacher) {
-                        // if user registered as teacher
+                if ($course_unsubscribe_allowed) {
+                    $html .= return_unregister_button($course, $stok, $search_term, $code);
+                }
+                $html .= return_already_registered_label('teacher');
+                $html .= return_description_button($course, $icon_title);
+            } else {
+                // if user not registered in the course
+                if (!$course_closed) {
+                    if (!$course_private) {
                         //$html .= return_goto_button($course);
                         //$html .= return_goto_button($course);
-                        
-                        if ($course_unsubscribe_allowed) {
-                            $html .= return_unregister_button($course, $stok, $search_term, $code);
-                        }
-                        $html .= return_already_registered_label('teacher');
-                        $html .= return_description_button($course, $icon_title);
-                    } else {
-                        // if user not registered in the course
-                        if (!$course_closed) {
-                            if (!$course_private) {
-                                //$html .= return_goto_button($course);
-                                if ($course_subscribe_allowed) {
-                                    $html .= return_register_button($course, $stok, $code, $search_term);
-                                }
-                            }
+                        if ($course_subscribe_allowed) {
+                            $html .= return_register_button($course, $stok, $code, $search_term);
                         }
                         }
-                        $html .= return_description_button($course, $icon_title);
                     }
                     }
-                    
-                    $html .= '</div>';
-                    $html .= '</div>';
-                    $html .= '</div>';
-                    $html .= '</div>';
-                    echo $html;
-                
                 }
                 }
-            } else {
-                if (!isset($_REQUEST['subscribe_user_with_password']) &&
-                    !isset($_REQUEST['subscribe_course'])
-                ) {
-                    Display::display_warning_message(get_lang('ThereAreNoCoursesInThisCategory'));
-                }
-            } 
+                $html .= return_description_button($course, $icon_title);
+            }
+
+            $html .= '</div>';
+            $html .= '</div>';
+            $html .= '</div>';
+            $html .= '</div>';
+            echo $html;
+
         }
         }
-    echo $cataloguePagination;
+    } else {
+        if (!isset($_REQUEST['subscribe_user_with_password']) &&
+            !isset($_REQUEST['subscribe_course'])
+        ) {
+            Display::display_warning_message(get_lang('ThereAreNoCoursesInThisCategory'));
+        }
+    }
+}
+echo $cataloguePagination;
 
 
-?>   
+?>
 </div>
 </div>
-   
+
 <?php
 <?php
 
 
 /**
 /**
@@ -290,7 +291,7 @@ function return_thumbnail($course, $icon_title)
     $title = cut($course['title'], 70);
     $title = cut($course['title'], 70);
     // course path
     // course path
     $course_path = api_get_path(SYS_COURSE_PATH).$course['directory'];
     $course_path = api_get_path(SYS_COURSE_PATH).$course['directory'];
-    
+
     if (file_exists($course_path.'/course-pic.png')) {
     if (file_exists($course_path.'/course-pic.png')) {
         $course_medium_image = api_get_path(WEB_COURSE_PATH).$course['directory'].'/course-pic.png'; // redimensioned image 85x85
         $course_medium_image = api_get_path(WEB_COURSE_PATH).$course['directory'].'/course-pic.png'; // redimensioned image 85x85
     } else {
     } else {
@@ -298,7 +299,7 @@ function return_thumbnail($course, $icon_title)
     }
     }
 
 
     // course image
     // course image
-    
+
     $html .= '<div class="items-course-image">';
     $html .= '<div class="items-course-image">';
     if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
     if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
         $html .= '<a class="ajax" href="'.api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&amp;code='.$course['code'].'" title="'.$icon_title.'" rel="gb_page_center[778]">';
         $html .= '<a class="ajax" href="'.api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&amp;code='.$course['code'].'" title="'.$icon_title.'" rel="gb_page_center[778]">';
@@ -308,6 +309,7 @@ function return_thumbnail($course, $icon_title)
         $html .= '<img class="img-responsive" src="'.$course_medium_image.'" alt="'.api_htmlentities($title).'"/>';
         $html .= '<img class="img-responsive" src="'.$course_medium_image.'" alt="'.api_htmlentities($title).'"/>';
     }
     }
     $html .= '</div>';  // thumbail
     $html .= '</div>';  // thumbail
+
     return $html;
     return $html;
 }
 }
 
 
@@ -316,15 +318,17 @@ function return_thumbnail($course, $icon_title)
  * @param $course
  * @param $course
  */
  */
 function return_title($course)
 function return_title($course)
-{   $html = '';
+{
+    $html = '';
     $linkCourse = api_get_course_url($course['code']);
     $linkCourse = api_get_course_url($course['code']);
     $title = cut($course['title'], 70);
     $title = cut($course['title'], 70);
     $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
     $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
     $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['code']);
     $teachers = CourseManager::get_teacher_list_from_course_code_to_string($course['code']);
-    $rating = Display::return_rating_system('star_'.$course['real_id'], $ajax_url.'&amp;course_id='.$course['real_id'], $course['point_info']);    
+    $rating = Display::return_rating_system('star_'.$course['real_id'], $ajax_url.'&amp;course_id='.$course['real_id'], $course['point_info']);
     $html .=  '<h4 class="title"><a href="' . $linkCourse . '">' . cut($title, 60) . '</a></h4>';
     $html .=  '<h4 class="title"><a href="' . $linkCourse . '">' . cut($title, 60) . '</a></h4>';
     $html .= '<div class="teachers">'.$teachers.'</div>';
     $html .= '<div class="teachers">'.$teachers.'</div>';
     $html .= '<div class="ranking">'. $rating . '</div>';
     $html .= '<div class="ranking">'. $rating . '</div>';
+
     return $html;
     return $html;
 }
 }
 
 
@@ -334,11 +338,13 @@ function return_title($course)
  * @param $icon_title
  * @param $icon_title
  */
  */
 function return_description_button($course, $icon_title)
 function return_description_button($course, $icon_title)
-{   
+{
     $title = $course['title'];
     $title = $course['title'];
+    $html = '';
     if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
     if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
         $html = '<a data-title="' . $title . '" class="ajax btn btn-default btn-sm btn-block" href="'.api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&amp;code='.$course['code'].'" title="'.$icon_title.'">'.get_lang('Description').'</a>';
         $html = '<a data-title="' . $title . '" class="ajax btn btn-default btn-sm btn-block" href="'.api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&amp;code='.$course['code'].'" title="'.$icon_title.'">'.get_lang('Description').'</a>';
     }
     }
+
     return $html;
     return $html;
 }
 }
 
 
@@ -349,6 +355,7 @@ function return_description_button($course, $icon_title)
 function return_goto_button($course)
 function return_goto_button($course)
 {
 {
     $html = ' <a class="btn btn-primary" href="'.api_get_course_url($course['code']).'">'.get_lang('GoToCourse').'</a>';
     $html = ' <a class="btn btn-primary" href="'.api_get_course_url($course['code']).'">'.get_lang('GoToCourse').'</a>';
+
     return $html;
     return $html;
 }
 }
 
 
@@ -363,6 +370,7 @@ function return_already_registered_label($in_status)
         $icon = Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);
         $icon = Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);
     }
     }
     $html = Display::div($icon.' '.get_lang("AlreadyRegisteredToCourse"), array('id' => 'register', 'class' => 'user-register'));
     $html = Display::div($icon.' '.get_lang("AlreadyRegisteredToCourse"), array('id' => 'register', 'class' => 'user-register'));
+
     return $html;
     return $html;
 }
 }
 
 
@@ -377,7 +385,6 @@ function return_register_button($course, $stok, $code, $search_term)
 {
 {
     $html = ' <a class="btn btn-success btn-block btn-sm" href="'.api_get_self().'?action=subscribe_course&amp;sec_token='.$stok.'&amp;subscribe_course='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Subscribe').'</a>';
     $html = ' <a class="btn btn-success btn-block btn-sm" href="'.api_get_self().'?action=subscribe_course&amp;sec_token='.$stok.'&amp;subscribe_course='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Subscribe').'</a>';
     return $html;
     return $html;
-    
 }
 }
 
 
 /**
 /**
@@ -391,5 +398,4 @@ function return_unregister_button($course, $stok, $search_term, $code)
 {
 {
     $html = ' <a class="btn btn-primary" href="'. api_get_self().'?action=unsubscribe&amp;sec_token='.$stok.'&amp;unsubscribe='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Unsubscribe').'</a>';
     $html = ' <a class="btn btn-primary" href="'. api_get_self().'?action=unsubscribe&amp;sec_token='.$stok.'&amp;unsubscribe='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Unsubscribe').'</a>';
     return $html;
     return $html;
-    
 }
 }

+ 111 - 0
main/template/default/layout/footer.js.tpl

@@ -0,0 +1,111 @@
+<script>
+    $("form").on("click", ' .advanced_parameters', function() {
+        /*var id = $(this).attr('id') + '_options';
+         console.log(id);
+         $("#"+id).toggleClass('active');
+         var button = $(this);
+         $("#"+id).toggle(function() {
+         $("#"+id).toggleClass('active');
+         });*/
+    });
+
+    /* Makes row highlighting possible */
+    $(document).ready( function() {
+        // Date time settings.
+        moment.locale('{{ locale }}');
+        $.datepicker.setDefaults($.datepicker.regional["{{ locale }}"]);
+        $.datepicker.regional["local"] = $.datepicker.regional["{{ locale }}"];
+
+        // Chosen select
+        $(".chzn-select").chosen({
+            disable_search_threshold: 10,
+            no_results_text: '{{ 'SearchNoResultsFound' | get_lang }}',
+            placeholder_text_multiple: '{{ 'SelectSomeOptions' | get_lang }}',
+            placeholder_text_single: '{{ 'SelectAnOption' | get_lang }}',
+            width: "100%"
+        });
+
+        // Bootstrap tabs.
+        $('.tab-wrapper a').click(function (e) {
+            e.preventDefault();
+            $(this).tab('show');
+
+            //$('#tabs a:first').tab('show') // Select first tab
+        });
+
+        // Fixes bug when loading links inside a tab.
+        $('.tab-wrapper .tab-pane a').unbind();
+
+        /**
+         * Advanced options
+         * Usage
+         * <a id="link" href="url">Advanced</a>
+         * <div id="link_options">
+         *     hidden content :)
+         * </div>
+         * */
+        $(".advanced_options").on("click", function (event) {
+            event.preventDefault();
+            var id = $(this).attr('id') + '_options';
+            var button = $(this);
+            button.toggleClass('active');
+            $("#" + id).toggle();
+        });
+
+        /**
+         * <a class="advanced_options_open" href="http://" rel="div_id">Open</a>
+         * <a class="advanced_options_close" href="http://" rel="div_id">Close</a>
+         * <div id="div_id">Div content</div>
+         * */
+        $(".advanced_options_open").on("click", function (event) {
+            event.preventDefault();
+            var id = $(this).attr('rel');
+            $("#" + id).show();
+        });
+
+        $(".advanced_options_close").on("click", function (event) {
+            event.preventDefault();
+            var id = $(this).attr('rel');
+            $("#" + id).hide();
+        });
+
+        // Adv multi-select search input.
+        $('.select_class_filter').on('focus', function () {
+            var inputId = $(this).attr('id');
+            inputId = inputId.replace('-filter', '');
+            $("#" + inputId).filterByText($("#" + inputId + "-filter"));
+        });
+
+        $(".jp-jplayer audio").addClass('skip');
+
+        // Mediaelement
+        jQuery('video:not(.skip), audio:not(.skip)').mediaelementplayer(/* Options */);
+
+        // Table highlight.
+        $("form .data_table input:checkbox").click(function () {
+            if ($(this).is(":checked")) {
+                $(this).parentsUntil("tr").parent().addClass("row_selected");
+
+            } else {
+                $(this).parentsUntil("tr").parent().removeClass("row_selected");
+            }
+        });
+
+        /* For non HTML5 browsers */
+        if ($("#formLogin".length > 1)) {
+            $("input[name=login]").focus();
+        }
+
+        /* For IOS users */
+        $('.autocapitalize_off').attr('autocapitalize', 'off');
+
+        // Tool tip (in exercises)
+        var tip_options = {
+            placement: 'right'
+        };
+        $('.boot-tooltip').tooltip(tip_options);
+    });
+
+
+
+</script>

+ 1 - 155
main/template/default/layout/footer.tpl

@@ -72,160 +72,6 @@
     </div>
     </div>
 </div>
 </div>
 
 
-<script>
-    $("form").on("click", ' .advanced_parameters', function() {
-        /*var id = $(this).attr('id') + '_options';
-        console.log(id);
-        $("#"+id).toggleClass('active');
-        var button = $(this);
-        $("#"+id).toggle(function() {
-            $("#"+id).toggleClass('active');
-        });*/
-    });
-
-    /* Makes row highlighting possible */
-    $(document).ready( function() {
-        // Date time settings.
-        moment.locale('{{ locale }}');
-        $.datepicker.setDefaults($.datepicker.regional["{{ locale }}"]);
-        $.datepicker.regional["local"] = $.datepicker.regional["{{ locale }}"];
-
-        // Bootstrap tabs.
-        $('.tab-wrapper a').click(function (e) {
-            e.preventDefault();
-            $(this).tab('show');
-
-            //$('#tabs a:first').tab('show') // Select first tab
-        });
-
-        // Fixes bug when loading links inside a tab.
-        $('.tab-wrapper .tab-pane a').unbind();
-
-        /**
-         * Advanced options
-         * Usage
-         * <a id="link" href="url">Advanced</a>
-         * <div id="link_options">
-         *     hidden content :)
-         * </div>
-         * */
-        $(".advanced_options").on("click", function(event) {
-            event.preventDefault();
-            var id = $(this).attr('id') + '_options';
-            var button = $(this);
-            button.toggleClass('active');
-            $("#"+id).toggle();
-        });
-
-        /**
-         * <a class="advanced_options_open" href="http://" rel="div_id">Open</a>
-         * <a class="advanced_options_close" href="http://" rel="div_id">Close</a>
-         * <div id="div_id">Div content</div>
-         * */
-        $(".advanced_options_open").on("click", function(event) {
-            event.preventDefault();
-            var id = $(this).attr('rel');
-            $("#"+id).show();
-        });
-
-        $(".advanced_options_close").on("click", function(event) {
-            event.preventDefault();
-            var id = $(this).attr('rel');
-            $("#"+id).hide();
-        });
-
-        // Chosen select
-        $(".chzn-select").chosen({
-            disable_search_threshold: 10,
-            no_results_text: '{{ 'SearchNoResultsFound' | get_lang }}',
-            placeholder_text_multiple: '{{ 'SelectSomeOptions' | get_lang }}',
-            placeholder_text_single: '{{ 'SelectAnOption' | get_lang }}',
-            width: "100%"
-        });
-
-        // Adv multi-select search input.
-        $('.select_class_filter').on('focus', function() {
-            var inputId = $(this).attr('id');
-            inputId = inputId.replace('-filter', '');
-            $("#"+ inputId).filterByText($("#"+inputId+"-filter"));
-        });
-
-        $(".jp-jplayer audio").addClass('skip');
-
-        // Mediaelement
-        jQuery('video:not(.skip), audio:not(.skip)').mediaelementplayer(/* Options */);
-
-        // Table highlight.
-        $("form .data_table input:checkbox").click(function() {
-            if ($(this).is(":checked")) {
-                $(this).parentsUntil("tr").parent().addClass("row_selected");
-
-            } else {
-                $(this).parentsUntil("tr").parent().removeClass("row_selected");
-            }
-        });
-
-        /* For non HTML5 browsers */
-        if ($("#formLogin".length > 1)) {
-            $("input[name=login]").focus();
-        }
-
-        /* For IOS users */
-        $('.autocapitalize_off').attr('autocapitalize', 'off');
-
-        // Tool tip (in exercises)
-        var tip_options = {
-            placement : 'right'
-        };
-        $('.boot-tooltip').tooltip(tip_options);
-    });
-
-    // @todo move in a chamilo.js js lib.
-
-    jQuery.fn.filterByText = function(textbox) {
-        return this.each(function() {
-            var select = this;
-            var options = [];
-            $(select).find('option').each(function() {
-                options.push({value: $(this).val(), text: $(this).text()});
-            });
-            $(select).data('options', options);
-
-            $(textbox).bind('change keyup', function() {
-                var options = $(select).empty().data('options');
-                var search = $.trim($(this).val());
-                var regex = new RegExp(search,"gi");
-
-                $.each(options, function(i) {
-                    var option = options[i];
-                    if(option.text.match(regex) !== null) {
-                        $(select).append(
-                            $('<option>').text(option.text).val(option.value)
-                        );
-                    }
-                });
-            });
-        });
-    };
-
-    /**
-     * Generic function to replace the deprecated jQuery toggle function
-     * @param inId          : id of block to hide / unhide
-     * @param inIdTxt       : id of the button
-     * @param inTxtHide     : text one of the button
-     * @param inTxtUnhide   : text two of the button
-     * @todo : allow to detect if text is from a button or from a <a>
-     */
-    function hideUnhide(inId, inIdTxt, inTxtHide, inTxtUnhide)
-    {
-        if ($('#'+inId).css("display") == "none") {
-            $('#'+inId).show(400);
-            $('#'+inIdTxt).attr("value", inTxtUnhide);
-        } else {
-            $('#'+inId).hide(400);
-            $('#'+inIdTxt).attr("value", inTxtHide);
-        }
-    }
-</script>
+{% include template ~ '/layout/footer.js.tpl' %}
 
 
 {{ execution_stats }}
 {{ execution_stats }}

+ 6 - 392
main/template/default/layout/head.tpl

@@ -15,405 +15,19 @@
 {{ social_meta }}
 {{ social_meta }}
 {{ css_static_file_to_string }}
 {{ css_static_file_to_string }}
 {{ js_file_to_string }}
 {{ js_file_to_string }}
-<script>
-
-// External plugins not part of the default Ckeditor package.
-var plugins = [
-    'asciimath',
-    'asciisvg',
-    'audio',
-    //'ckeditor_wiris',
-    'dialogui',
-    'glossary',
-    'leaflet',
-    'mapping',
-    'maximize',
-    'mathjax',
-    'oembed',
-    'toolbar',
-    'toolbarswitch',
-    'video',
-    'wikilink',
-    'wordcount',
-    'youtube'
-];
-
-plugins.forEach(function(plugin) {
-    CKEDITOR.plugins.addExternal(plugin, '{{ _p.web_main ~ 'inc/lib/javascript/ckeditor/plugins/' }}' + plugin + '/');
-});
-
-/**
- * Function use to load templates in a div
-**/
-var showTemplates = function (ckeditorName) {
-    var editorName = 'content';
-    if (ckeditorName && ckeditorName.length > 0) {
-        editorName = ckeditorName;
-    }
-    CKEDITOR.editorConfig(CKEDITOR.config);
-    CKEDITOR.loadTemplates(CKEDITOR.config.templates_files, function (a){
-        var templatesConfig = CKEDITOR.getTemplates("default");
-
-        var $templatesUL = $("<ul>");
-
-        $.each(templatesConfig.templates, function () {
-            var template = this;
-            var $templateLi = $("<li>");
-
-            var templateHTML = "<img src=\"" + templatesConfig.imagesPath + template.image + "\" ><div>";
-            templateHTML += "<b>" + template.title + "</b>";
-
-            if (template.description) {
-                templateHTML += "<div class=description>" + template.description + "</div>";
-            }
-
-            templateHTML += "</div>";
-
-            $("<a>", {
-                href: "#",
-                html: templateHTML,
-                click: function (e) {
-                    e.preventDefault();
-                    if (CKEDITOR.instances[editorName]) {
-                        CKEDITOR.instances[editorName].setData(template.html, function () {
-                            this.checkDirty();
-                        });
-                    }
-                }
-            }).appendTo($templateLi);
-
-            $templatesUL.append($templateLi);
-        });
-
-        $templatesUL.appendTo("#frmModel");
-    });
-};
-
-</script>
 {{ extra_headers }}
 {{ extra_headers }}
 <script>
 <script>
 
 
-function setCheckbox(value, table_id) {
-    checkboxes = $("#"+table_id+" input:checkbox");
-    $.each(checkboxes, function(index, checkbox) {
-         checkbox.checked = value;
-        if (value) {
-            $(checkbox).parentsUntil("tr").parent().addClass("row_selected");
-        } else {
-            $(checkbox).parentsUntil("tr").parent().removeClass("row_selected");
-        }
-    });
-    return false;
-}
-
-function action_click(element, table_id) {
-    d = $("#"+table_id);
-    if (!confirm('{{ "ConfirmYourChoice"|get_lang }}')) {
-        return false;
-    } else {
-        var action =$(element).attr("data-action");
-        $('#'+table_id+' input[name="action"] ').attr("value", action);
-        d.submit();
-        return false;
-    }
-}
-
 /* Global chat variables */
 /* Global chat variables */
-var ajax_url        = '{{ _p.web_ajax }}chat.ajax.php';
-var online_button   = '{{ online_button }}';
-var offline_button  = '{{ offline_button }}';
-var connect_lang    = '{{ "ChatConnected"|get_lang }}';
+var ajax_url = '{{ _p.web_ajax }}chat.ajax.php';
+var online_button = '{{ online_button }}';
+var offline_button = '{{ offline_button }}';
+var connect_lang = '{{ "ChatConnected"|get_lang }}';
 var disconnect_lang = '{{ "ChatDisconnected"|get_lang }}';
 var disconnect_lang = '{{ "ChatDisconnected"|get_lang }}';
+</script>
 
 
-function get_url_params(q, attribute) {
-    var vars;
-    var hash;
-    if (q != undefined) {
-        q = q.split('&');
-        for(var i = 0; i < q.length; i++){
-            hash = q[i].split('=');
-            if (hash[0] == attribute) {
-                return hash[1];
-            }
-        }
-    }
-}
-$(document).ready(function(){
-    $("#open-view-list").click(function(){
-        $("#student-list-work").fadeIn(300);
-    });
-    $("#closed-view-list").click(function(){
-        $("#student-list-work").fadeOut(300);
-    });
-});
-function check_brand() {
-    if ($('.subnav').length) {
-        if ($(window).width() >= 969) {
-            $('.subnav .brand').hide();
-        } else {
-            $('.subnav .brand').show();
-        }
-    }
-}
-
-$(window).resize(function() {
-    check_brand();
-});
-
-$(document).scroll(function() {
-
-    //Exercise warning fixed at the top
-    var fixed =  $("#exercise_clock_warning");
-    if (fixed.length) {
-        if (!fixed.attr('data-top')) {
-            // If already fixed, then do nothing
-            if (fixed.hasClass('subnav-fixed')) return;
-            // Remember top position
-            var offset = fixed.offset();
-            fixed.attr('data-top', offset.top);
-            fixed.css('width', '100%');
-        }
-
-        if (fixed.attr('data-top') - fixed.outerHeight() <= $(this).scrollTop()) {
-            fixed.addClass('subnav-fixed');
-            fixed.css('width', '100%');
-        } else {
-            fixed.removeClass('subnav-fixed');
-            fixed.css('width', '200px');
-        }
-    }
-
-    // Admin -> Settings toolbar.
-    if ($('body').width() > 959) {
-        if ($('.new_actions').length) {
-            if (!$('.new_actions').attr('data-top')) {
-                // If already fixed, then do nothing
-                if ($('.new_actions').hasClass('new_actions-fixed')) return;
-                // Remember top position
-                var offset = $('.new_actions').offset();
-
-                var more_top = 0;
-                if ($('.subnav').hasClass('new_actions-fixed')) {
-                    more_top = 50;
-                }
-                $('.new_actions').attr('data-top', offset.top + more_top);
-            }
-
-            if ($('.new_actions').attr('data-top') - $('.new_actions').outerHeight() <= $(this).scrollTop()) {
-                $('.new_actions').addClass('new_actions-fixed');
-            } else {
-                $('.new_actions').removeClass('new_actions-fixed');
-            }
-        }
-    }
-
-    // Bottom actions.
-    if ($('.bottom_actions').length) {
-        if (!$('.bottom_actions').attr('data-top')) {
-            // If already fixed, then do nothing
-            if ($('.bottom_actions').hasClass('bottom_actions_fixed')) return;
-
-            // Remember top position
-            var offset = $('.bottom_actions').offset();
-            $('.bottom_actions').attr('data-top', offset.top);
-        }
-
-        if ($('.bottom_actions').attr('data-top') > $('body').outerHeight()) {
-            if ( ($('.bottom_actions').attr('data-top') - $('body').outerHeight() - $('.bottom_actions').outerHeight()) >= $(this).scrollTop()) {
-                $('.bottom_actions').addClass('bottom_actions_fixed');
-                $('.bottom_actions').css("width", "100%");
-            } else {
-                $('.bottom_actions').css("width", "");
-                $('.bottom_actions').removeClass('bottom_actions_fixed');
-            }
-        } else {
-            if ( ($('.bottom_actions').attr('data-top') -  $('.bottom_actions').outerHeight()) <= $(this).scrollTop()) {
-                $('.bottom_actions').addClass('bottom_actions_fixed');
-                $('.bottom_actions').css("width", "100%");
-            } else {
-                $('.bottom_actions').removeClass('bottom_actions_fixed');
-                $('.bottom_actions').css("width", "");
-            }
-        }
-    }
-});
-
-function showConfirmationPopup(obj, urlParam)
-{
-    if (urlParam) {
-        url = urlParam
-    } else {
-        url = obj.href;
-    }
-
-    var dialog  = $("#dialog");
-    if ($("#dialog").length == 0) {
-        dialog  = $('<div id="dialog" style="display:none">{{ "ConfirmYourChoice" | get_lang }} </div>').appendTo('body');
-    }
-
-    var width_value = 350;
-    var height_value = 150;
-    var resizable_value = true;
-
-    var new_param = get_url_params(url, 'width');
-    if (new_param) {
-        width_value = new_param;
-    }
-
-    var new_param = get_url_params(url, 'height')
-    if (new_param) {
-        height_value = new_param;
-    }
-
-    var new_param = get_url_params(url, 'resizable');
-    if (new_param) {
-        resizable_value = new_param;
-    }
-
-    // Show dialog
-    dialog.dialog({
-        modal       : true,
-        width       : width_value,
-        height      : height_value,
-        resizable   : resizable_value,
-        buttons: [
-            {
-                text: '{{ 'Yes' | get_lang }}',
-                click: function() {
-                    window.location = url;
-                },
-                icons:{
-                    primary:'ui-icon-locked'
-                }
-            },
-            {
-                text: '{{ 'No' | get_lang }}',
-                click: function() { $(this).dialog("close"); },
-                icons:{
-                    primary:'ui-icon-locked'
-                }
-            }
-        ]
-    });
-    // prevent the browser to follow the link
-    return false;
-}
-
-$(function() {
-
-    check_brand();
-    //if exists the toolbar admin
-
-    if($('#toolbar').length){
-        var heigthToolBar= $('#toolbar').height();
-        $('header').css('margin-top', heigthToolBar+'px');
-        $('#page-back').css('padding-top', heigthToolBar+20+'px');
-    }
-
-    // Removes the yellow input in Chrome
-    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
-        $(window).load(function(){
-            $('input:-webkit-autofill').each(function(){
-                var text = $(this).val();
-                var name = $(this).attr('name');
-                $(this).after(this.outerHTML).remove();
-                $('input[name=' + name + ']').val(text);
-            });
-        });
-    }
-
-    $(".accordion_jquery").accordion({
-        autoHeight: false,
-        active: false, // all items closed by default
-        collapsible: true,
-        header: ".accordion-heading"
-    });
-
-    // Global popup
-    $('body').on('click', 'a.ajax', function(e) {
-        e.preventDefault();
-
-        var contentUrl = this.href,
-            loadModalContent = $.get(contentUrl),
-            self = $(this);
-
-        $.when(loadModalContent).done(function(modalContent) {
-            var modalDialog = $('#global-modal').find('.modal-dialog'),
-                modalSize = self.data('size') || get_url_params(contentUrl, 'modal_size'),
-                modalWidth = self.data('width') || get_url_params(contentUrl, 'width'),
-                modalTitle = self.data('title') || ' ';
-
-            modalDialog.removeClass('modal-lg modal-sm').css('width', '');
-
-            if (modalSize) {
-                switch (modalSize) {
-                    case 'lg':
-                        modalDialog.addClass('modal-lg');
-                        break;
-                    case 'sm':
-                        modalDialog.addClass('modal-sm');
-                        break;
-                }
-            } else if (modalWidth) {
-                modalDialog.css('width', modalWidth + 'px');
-            }
-
-            $('#global-modal').find('.modal-title').text(modalTitle);
-            $('#global-modal').find('.modal-body').html(modalContent);
-
-            $('#global-modal').modal('show');
-        });
-    });
-
-    $('a.expand-image').on('click', function(e) {
-        e.preventDefault();
-
-        var title = $(this).attr('title');
-
-        var image = new Image();
-        image.onload = function() {
-            if (title) {
-                $('#expand-image-modal').find('.modal-title').text(title);
-            } else {
-                $('#expand-image-modal').find('.modal-title').html('&nbsp;');
-            }
-
-            $('#expand-image-modal').find('.modal-body').html(image);
-            $('#expand-image-modal').modal({
-                show: true
-            });
-        };
-        image.src = this.href;
-    });
-
-    // Global confirmation
-    $('.popup-confirmation').on('click', function() {
-        showConfirmationPopup(this);
-        return false;
-    });
-
-    // old jquery.menu.js
-    $('#navigation a').stop().animate({
-        'marginLeft':'50px'
-    },1000);
-
-    $('#navigation > li').hover(
-        function () {
-            $('a',$(this)).stop().animate({
-                'marginLeft':'1px'
-            },200);
-        },
-        function () {
-            $('a',$(this)).stop().animate({
-                'marginLeft':'50px'
-            },200);
-        }
-    );
+{% include template ~ '/layout/header.js.tpl' %}
 
 
-    /* Make responsive image maps */
-    $('map').imageMapResize();
-});
-</script>
 {{ css_custom_file_to_string }}
 {{ css_custom_file_to_string }}
 {{ css_style_print }}
 {{ css_style_print }}
 {# Extra header configured in admin section, only shown to non-admins #}
 {# Extra header configured in admin section, only shown to non-admins #}

+ 425 - 0
main/template/default/layout/header.js.tpl

@@ -0,0 +1,425 @@
+<script>
+// External plugins not part of the default Ckeditor package.
+var plugins = [
+    'asciimath',
+    'asciisvg',
+    'audio',
+    //'ckeditor_wiris',
+    'dialogui',
+    'glossary',
+    'leaflet',
+    'mapping',
+    'maximize',
+    'mathjax',
+    'oembed',
+    'toolbar',
+    'toolbarswitch',
+    'video',
+    'wikilink',
+    'wordcount',
+    'youtube'
+];
+
+plugins.forEach(function(plugin) {
+    CKEDITOR.plugins.addExternal(plugin, '{{ _p.web_main ~ 'inc/lib/javascript/ckeditor/plugins/' }}' + plugin + '/');
+});
+
+/**
+ * Function use to load templates in a div
+ **/
+var showTemplates = function (ckeditorName) {
+    var editorName = 'content';
+    if (ckeditorName && ckeditorName.length > 0) {
+        editorName = ckeditorName;
+    }
+    CKEDITOR.editorConfig(CKEDITOR.config);
+    CKEDITOR.loadTemplates(CKEDITOR.config.templates_files, function (a){
+        var templatesConfig = CKEDITOR.getTemplates("default");
+
+        var $templatesUL = $("<ul>");
+
+        $.each(templatesConfig.templates, function () {
+            var template = this;
+            var $templateLi = $("<li>");
+
+            var templateHTML = "<img src=\"" + templatesConfig.imagesPath + template.image + "\" ><div>";
+            templateHTML += "<b>" + template.title + "</b>";
+
+            if (template.description) {
+                templateHTML += "<div class=description>" + template.description + "</div>";
+            }
+
+            templateHTML += "</div>";
+
+            $("<a>", {
+                href: "#",
+                html: templateHTML,
+                click: function (e) {
+                    e.preventDefault();
+                    if (CKEDITOR.instances[editorName]) {
+                        CKEDITOR.instances[editorName].setData(template.html, function () {
+                            this.checkDirty();
+                        });
+                    }
+                }
+            }).appendTo($templateLi);
+            $templatesUL.append($templateLi);
+        });
+        $templatesUL.appendTo("#frmModel");
+    });
+};
+
+$(document).ready(function(){
+    $("#open-view-list").click(function(){
+        $("#student-list-work").fadeIn(300);
+    });
+    $("#closed-view-list").click(function(){
+        $("#student-list-work").fadeOut(300);
+    });
+
+    check_brand();
+    //if exists the toolbar admin
+
+    if($('#toolbar').length){
+        var heigthToolBar= $('#toolbar').height();
+        $('header').css('margin-top', heigthToolBar+'px');
+        $('#page-back').css('padding-top', heigthToolBar+20+'px');
+    }
+
+    // Removes the yellow input in Chrome
+    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
+        $(window).load(function(){
+            $('input:-webkit-autofill').each(function(){
+                var text = $(this).val();
+                var name = $(this).attr('name');
+                $(this).after(this.outerHTML).remove();
+                $('input[name=' + name + ']').val(text);
+            });
+        });
+    }
+
+    $(".accordion_jquery").accordion({
+        autoHeight: false,
+        active: false, // all items closed by default
+        collapsible: true,
+        header: ".accordion-heading"
+    });
+
+    // Global popup
+    $('body').on('click', 'a.ajax', function(e) {
+        e.preventDefault();
+
+        var contentUrl = this.href,
+                loadModalContent = $.get(contentUrl),
+                self = $(this);
+
+        $.when(loadModalContent).done(function(modalContent) {
+            var modalDialog = $('#global-modal').find('.modal-dialog'),
+                    modalSize = self.data('size') || get_url_params(contentUrl, 'modal_size'),
+                    modalWidth = self.data('width') || get_url_params(contentUrl, 'width'),
+                    modalTitle = self.data('title') || ' ';
+
+            modalDialog.removeClass('modal-lg modal-sm').css('width', '');
+
+            if (modalSize) {
+                switch (modalSize) {
+                    case 'lg':
+                        modalDialog.addClass('modal-lg');
+                        break;
+                    case 'sm':
+                        modalDialog.addClass('modal-sm');
+                        break;
+                }
+            } else if (modalWidth) {
+                modalDialog.css('width', modalWidth + 'px');
+            }
+
+            $('#global-modal').find('.modal-title').text(modalTitle);
+            $('#global-modal').find('.modal-body').html(modalContent);
+            $('#global-modal').modal('show');
+        });
+    });
+
+    $('a.expand-image').on('click', function(e) {
+        e.preventDefault();
+        var title = $(this).attr('title');
+        var image = new Image();
+        image.onload = function() {
+            if (title) {
+                $('#expand-image-modal').find('.modal-title').text(title);
+            } else {
+                $('#expand-image-modal').find('.modal-title').html('&nbsp;');
+            }
+
+            $('#expand-image-modal').find('.modal-body').html(image);
+            $('#expand-image-modal').modal({
+                show: true
+            });
+        };
+        image.src = this.href;
+    });
+
+    // Global confirmation
+    $('.popup-confirmation').on('click', function() {
+        showConfirmationPopup(this);
+        return false;
+    });
+
+    // old jquery.menu.js
+    $('#navigation a').stop().animate({
+        'marginLeft':'50px'
+    },1000);
+
+    $('#navigation > li').hover(
+        function () {
+            $('a',$(this)).stop().animate({
+                'marginLeft':'1px'
+            },200);
+        },
+        function () {
+            $('a',$(this)).stop().animate({
+                'marginLeft':'50px'
+            },200);
+        }
+    );
+
+    /* Make responsive image maps */
+    $('map').imageMapResize();
+
+    jQuery.fn.filterByText = function(textbox) {
+        return this.each(function() {
+            var select = this;
+            var options = [];
+            $(select).find('option').each(function() {
+                options.push({value: $(this).val(), text: $(this).text()});
+            });
+            $(select).data('options', options);
+
+            $(textbox).bind('change keyup', function() {
+                var options = $(select).empty().data('options');
+                var search = $.trim($(this).val());
+                var regex = new RegExp(search,"gi");
+
+                $.each(options, function(i) {
+                    var option = options[i];
+                    if(option.text.match(regex) !== null) {
+                        $(select).append(
+                                $('<option>').text(option.text).val(option.value)
+                        );
+                    }
+                });
+            });
+        });
+    };
+});
+
+$(window).resize(function() {
+    check_brand();
+});
+
+$(document).scroll(function() {
+
+    //Exercise warning fixed at the top
+    var fixed =  $("#exercise_clock_warning");
+    if (fixed.length) {
+        if (!fixed.attr('data-top')) {
+            // If already fixed, then do nothing
+            if (fixed.hasClass('subnav-fixed')) return;
+            // Remember top position
+            var offset = fixed.offset();
+            fixed.attr('data-top', offset.top);
+            fixed.css('width', '100%');
+        }
+
+        if (fixed.attr('data-top') - fixed.outerHeight() <= $(this).scrollTop()) {
+            fixed.addClass('subnav-fixed');
+            fixed.css('width', '100%');
+        } else {
+            fixed.removeClass('subnav-fixed');
+            fixed.css('width', '200px');
+        }
+    }
+
+    // Admin -> Settings toolbar.
+    if ($('body').width() > 959) {
+        if ($('.new_actions').length) {
+            if (!$('.new_actions').attr('data-top')) {
+                // If already fixed, then do nothing
+                if ($('.new_actions').hasClass('new_actions-fixed')) return;
+                // Remember top position
+                var offset = $('.new_actions').offset();
+
+                var more_top = 0;
+                if ($('.subnav').hasClass('new_actions-fixed')) {
+                    more_top = 50;
+                }
+                $('.new_actions').attr('data-top', offset.top + more_top);
+            }
+
+            if ($('.new_actions').attr('data-top') - $('.new_actions').outerHeight() <= $(this).scrollTop()) {
+                $('.new_actions').addClass('new_actions-fixed');
+            } else {
+                $('.new_actions').removeClass('new_actions-fixed');
+            }
+        }
+    }
+
+    // Bottom actions.
+    if ($('.bottom_actions').length) {
+        if (!$('.bottom_actions').attr('data-top')) {
+            // If already fixed, then do nothing
+            if ($('.bottom_actions').hasClass('bottom_actions_fixed')) return;
+
+            // Remember top position
+            var offset = $('.bottom_actions').offset();
+            $('.bottom_actions').attr('data-top', offset.top);
+        }
+
+        if ($('.bottom_actions').attr('data-top') > $('body').outerHeight()) {
+            if ( ($('.bottom_actions').attr('data-top') - $('body').outerHeight() - $('.bottom_actions').outerHeight()) >= $(this).scrollTop()) {
+                $('.bottom_actions').addClass('bottom_actions_fixed');
+                $('.bottom_actions').css("width", "100%");
+            } else {
+                $('.bottom_actions').css("width", "");
+                $('.bottom_actions').removeClass('bottom_actions_fixed');
+            }
+        } else {
+            if ( ($('.bottom_actions').attr('data-top') -  $('.bottom_actions').outerHeight()) <= $(this).scrollTop()) {
+                $('.bottom_actions').addClass('bottom_actions_fixed');
+                $('.bottom_actions').css("width", "100%");
+            } else {
+                $('.bottom_actions').removeClass('bottom_actions_fixed');
+                $('.bottom_actions').css("width", "");
+            }
+        }
+    }
+});
+
+function get_url_params(q, attribute) {
+    var vars;
+    var hash;
+    if (q != undefined) {
+        q = q.split('&');
+        for(var i = 0; i < q.length; i++){
+            hash = q[i].split('=');
+            if (hash[0] == attribute) {
+                return hash[1];
+            }
+        }
+    }
+}
+
+function check_brand() {
+    if ($('.subnav').length) {
+        if ($(window).width() >= 969) {
+            $('.subnav .brand').hide();
+        } else {
+            $('.subnav .brand').show();
+        }
+    }
+}
+
+function showConfirmationPopup(obj, urlParam) {
+    if (urlParam) {
+        url = urlParam
+    } else {
+        url = obj.href;
+    }
+
+    var dialog  = $("#dialog");
+    if ($("#dialog").length == 0) {
+        dialog  = $('<div id="dialog" style="display:none">{{ "ConfirmYourChoice" | get_lang }} </div>').appendTo('body');
+    }
+
+    var width_value = 350;
+    var height_value = 150;
+    var resizable_value = true;
+
+    var new_param = get_url_params(url, 'width');
+    if (new_param) {
+        width_value = new_param;
+    }
+
+    var new_param = get_url_params(url, 'height')
+    if (new_param) {
+        height_value = new_param;
+    }
+
+    var new_param = get_url_params(url, 'resizable');
+    if (new_param) {
+        resizable_value = new_param;
+    }
+
+    // Show dialog
+    dialog.dialog({
+        modal       : true,
+        width       : width_value,
+        height      : height_value,
+        resizable   : resizable_value,
+        buttons: [
+            {
+                text: '{{ 'Yes' | get_lang }}',
+                click: function() {
+                    window.location = url;
+                },
+                icons:{
+                    primary:'ui-icon-locked'
+                }
+            },
+            {
+                text: '{{ 'No' | get_lang }}',
+                click: function() { $(this).dialog("close"); },
+                icons:{
+                    primary:'ui-icon-locked'
+                }
+            }
+        ]
+    });
+    // prevent the browser to follow the link
+    return false;
+}
+
+function setCheckbox(value, table_id) {
+    checkboxes = $("#"+table_id+" input:checkbox");
+    $.each(checkboxes, function(index, checkbox) {
+        checkbox.checked = value;
+        if (value) {
+            $(checkbox).parentsUntil("tr").parent().addClass("row_selected");
+        } else {
+            $(checkbox).parentsUntil("tr").parent().removeClass("row_selected");
+        }
+    });
+    return false;
+}
+
+function action_click(element, table_id) {
+    d = $("#"+table_id);
+    if (!confirm('{{ "ConfirmYourChoice"|get_lang }}')) {
+        return false;
+    } else {
+        var action =$(element).attr("data-action");
+        $('#'+table_id+' input[name="action"] ').attr("value", action);
+        d.submit();
+        return false;
+    }
+}
+
+/**
+ * Generic function to replace the deprecated jQuery toggle function
+ * @param inId          : id of block to hide / unhide
+ * @param inIdTxt       : id of the button
+ * @param inTxtHide     : text one of the button
+ * @param inTxtUnhide   : text two of the button
+ * @todo : allow to detect if text is from a button or from a <a>
+ */
+function hideUnhide(inId, inIdTxt, inTxtHide, inTxtUnhide)
+{
+    if ($('#'+inId).css("display") == "none") {
+        $('#'+inId).show(400);
+        $('#'+inIdTxt).attr("value", inTxtUnhide);
+    } else {
+        $('#'+inId).hide(400);
+        $('#'+inIdTxt).attr("value", inTxtHide);
+    }
+}
+</script>

+ 35 - 42
tests/main/inc/lib/tracking.lib.test.php

@@ -21,8 +21,8 @@ class TestTracking extends UnitTestCase {
 	 	if(!is_null($res))$this->assertTrue(is_bool($res));
 	 	if(!is_null($res))$this->assertTrue(is_bool($res));
 	 	//var_dump($res);
 	 	//var_dump($res);
 	}
 	}
-	
-	
+
+
 	function testchat_connections_during_last_x_days_by_course() {
 	function testchat_connections_during_last_x_days_by_course() {
 	 	global $_course;
 	 	global $_course;
 	 	$course_code=$_course;
 	 	$course_code=$_course;
@@ -113,7 +113,7 @@ class TestTracking extends UnitTestCase {
 	 	$student_id=$_user;
 	 	$student_id=$_user;
 	 	$course_code=$_course;
 	 	$course_code=$_course;
 	 	$a_course = CourseManager :: get_course_information($course_code);
 	 	$a_course = CourseManager :: get_course_information($course_code);
-		
+
 		$res=Tracking::count_student_messages($student_id, $course_code);
 		$res=Tracking::count_student_messages($student_id, $course_code);
 		$this->assertTrue(is_object($this->tracking));
 		$this->assertTrue(is_object($this->tracking));
 		if(!is_numeric($res))$this->assertTrue(is_null($res));
 		if(!is_numeric($res))$this->assertTrue(is_null($res));
@@ -212,7 +212,7 @@ class TestTracking extends UnitTestCase {
 
 
 	function testget_inactives_students_in_course() {
 	function testget_inactives_students_in_course() {
 		global $_course;
 		global $_course;
-		$course_code = $_course; 
+		$course_code = $_course;
 		$since='2010-10-02';
 		$since='2010-10-02';
 		$session_id='';
 		$session_id='';
 		$res=Tracking::get_inactives_students_in_course($course_code, $since, $session_id);
 		$res=Tracking::get_inactives_students_in_course($course_code, $since, $session_id);
@@ -271,7 +271,7 @@ class TestTracking extends UnitTestCase {
 	 	if(!is_null($res))$this->assertTrue(is_bool($res));
 	 	if(!is_null($res))$this->assertTrue(is_bool($res));
 	 	//var_dump($res);
 	 	//var_dump($res);
 	}
 	}
-	
+
 	function testchat_last_connection() {
 	function testchat_last_connection() {
 		require_once (api_get_path(LIBRARY_PATH) . 'course.lib.php');
 		require_once (api_get_path(LIBRARY_PATH) . 'course.lib.php');
 		global $_course;
 		global $_course;
@@ -282,7 +282,7 @@ class TestTracking extends UnitTestCase {
 		$this->assertTrue(is_object($this->tracking));
 		$this->assertTrue(is_object($this->tracking));
 		if(!is_string($res))$this->assertTrue(is_null($res));
 		if(!is_string($res))$this->assertTrue(is_null($res));
 	}
 	}
-	
+
 		function testget_last_connection_date() {
 		function testget_last_connection_date() {
 		$student_id=1;
 		$student_id=1;
 		$res=Tracking::get_last_connection_date($student_id);
 		$res=Tracking::get_last_connection_date($student_id);
@@ -304,32 +304,25 @@ class TestTrackingCourseLog extends UnitTestCase {
 	function testCountItemResources() {
 	function testCountItemResources() {
 		//ob_start();
 		//ob_start();
 		$res = TrackingCourseLog::count_item_resources();
 		$res = TrackingCourseLog::count_item_resources();
-		$this->assertTrue(is_numeric($res)); 
+		$this->assertTrue(is_numeric($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
-	}	
+	}
 
 
 	function testDisplayAdditionalProfileFields() {
 	function testDisplayAdditionalProfileFields() {
 		//ob_start();
 		//ob_start();
 		$res = TrackingCourseLog::display_additional_profile_fields();
 		$res = TrackingCourseLog::display_additional_profile_fields();
-		$this->assertTrue(is_string($res)); 
-		//ob_end_clean();
-		//var_dump($res);
-	}
-	function testGetAddtionalProfileInformationOfField() {
-		//ob_start();
-		$field_id=1;
-		$res = TrackingCourseLog::get_addtional_profile_information_of_field($field_id);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_string($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
+
 	function testGetAddtionalProfileInformationOfFieldByUser() {
 	function testGetAddtionalProfileInformationOfFieldByUser() {
 		//ob_start();
 		//ob_start();
 		$field_id=1;
 		$field_id=1;
 		$users=array(1,2,3);
 		$users=array(1,2,3);
 		$res = TrackingCourseLog::get_addtional_profile_information_of_field_by_user($field_id, $users);
 		$res = TrackingCourseLog::get_addtional_profile_information_of_field_by_user($field_id, $users);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -340,14 +333,14 @@ class TestTrackingCourseLog extends UnitTestCase {
 		$column=1;
 		$column=1;
 		$direction='ASC';
 		$direction='ASC';
 		$res = TrackingCourseLog::get_item_resources_data($from, $number_of_items, $column, $direction);
 		$res = TrackingCourseLog::get_item_resources_data($from, $number_of_items, $column, $direction);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
 	function testGetNumberOfUsers() {
 	function testGetNumberOfUsers() {
 		//ob_start();
 		//ob_start();
 		$res = TrackingCourseLog::get_number_of_users();
 		$res = TrackingCourseLog::get_number_of_users();
-		$this->assertTrue(is_numeric($res)); 
+		$this->assertTrue(is_numeric($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -355,7 +348,7 @@ class TestTrackingCourseLog extends UnitTestCase {
 		//ob_start();
 		//ob_start();
 		$tool='';
 		$tool='';
 		$res = TrackingCourseLog::get_tool_name_table($tool);
 		$res = TrackingCourseLog::get_tool_name_table($tool);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -366,32 +359,32 @@ class TestTrackingCourseLog extends UnitTestCase {
 		$column='';
 		$column='';
 		$direction='';
 		$direction='';
 		$res = TrackingCourseLog::get_user_data($from, $number_of_items, $column, $direction);
 		$res = TrackingCourseLog::get_user_data($from, $number_of_items, $column, $direction);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
-	
+
 }
 }
 
 
 class TestTrackingUserLog extends UnitTestCase {
 class TestTrackingUserLog extends UnitTestCase {
-	
+
 	function testDisplayDocumentTrackingInfo() {
 	function testDisplayDocumentTrackingInfo() {
 		ob_start();
 		ob_start();
 		$view = '';
 		$view = '';
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLog::display_document_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLog::display_document_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
-	}	
+	}
 	function testDisplayExerciseTrackingInfo() {
 	function testDisplayExerciseTrackingInfo() {
 		ob_start();
 		ob_start();
 		$view = '';
 		$view = '';
 		$user_id = 1;
 		$user_id = 1;
 		$courseCode = 'TEST';
 		$courseCode = 'TEST';
 		$res = TrackingUserLog::display_exercise_tracking_info($view, $user_id, $courseCode);
 		$res = TrackingUserLog::display_exercise_tracking_info($view, $user_id, $courseCode);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -401,7 +394,7 @@ class TestTrackingUserLog extends UnitTestCase {
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLog::display_links_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLog::display_links_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -411,7 +404,7 @@ class TestTrackingUserLog extends UnitTestCase {
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLog::display_login_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLog::display_login_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -421,43 +414,43 @@ class TestTrackingUserLog extends UnitTestCase {
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLog::display_student_publications_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLog::display_student_publications_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_null($res)); 
+		$this->assertTrue(is_null($res));
 		ob_end_clean();
 		ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
-	
+
 }
 }
 
 
 class TestTrackingUserLogCSV extends UnitTestCase {
 class TestTrackingUserLogCSV extends UnitTestCase {
-	
+
 	function testDisplayDocumentTrackingInfo() {
 	function testDisplayDocumentTrackingInfo() {
 		//ob_start();
 		//ob_start();
 		$view = '';
 		$view = '';
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLogCSV::display_document_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLogCSV::display_document_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
-	}	
+	}
 	function testDisplayExerciseTrackingInfo() {
 	function testDisplayExerciseTrackingInfo() {
 		//ob_start();
 		//ob_start();
 		$view = '';
 		$view = '';
 		$user_id = 1;
 		$user_id = 1;
 		$courseCode = 'TEST';
 		$courseCode = 'TEST';
 		$res = TrackingUserLogCSV::display_exercise_tracking_info($view, $user_id, $courseCode);
 		$res = TrackingUserLogCSV::display_exercise_tracking_info($view, $user_id, $courseCode);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
-	} 
-	
+	}
+
 	function testDisplayLinksTrackingInfo() {
 	function testDisplayLinksTrackingInfo() {
 		//ob_start();
 		//ob_start();
 		$view = '';
 		$view = '';
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLogCSV::display_links_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLogCSV::display_links_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -467,7 +460,7 @@ class TestTrackingUserLogCSV extends UnitTestCase {
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLogCSV::display_login_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLogCSV::display_login_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
 	}
 	}
@@ -477,9 +470,9 @@ class TestTrackingUserLogCSV extends UnitTestCase {
 		$user_id = 1;
 		$user_id = 1;
 		$course_id = 1;
 		$course_id = 1;
 		$res = TrackingUserLogCSV::display_student_publications_tracking_info($view, $user_id, $course_id);
 		$res = TrackingUserLogCSV::display_student_publications_tracking_info($view, $user_id, $course_id);
-		$this->assertTrue(is_array($res)); 
+		$this->assertTrue(is_array($res));
 		//ob_end_clean();
 		//ob_end_clean();
 		//var_dump($res);
 		//var_dump($res);
-	}	
+	}
 }
 }
-?>
+?>