Browse Source

Update after merge with 1.11.x

Julio Montoya 5 years ago
parent
commit
1f232314dd
38 changed files with 486 additions and 574 deletions
  1. 4 18
      main/admin/access_url_add_courses_to_url.php
  2. 0 5
      main/admin/access_url_add_usergroup_to_url.php
  3. 0 4
      main/admin/access_url_add_users_to_url.php
  4. 0 9
      main/admin/access_url_edit_courses_to_url.php
  5. 1 5
      main/admin/access_url_edit_usergroup_to_url.php
  6. 0 5
      main/admin/access_url_edit_users_to_url.php
  7. 2 2
      main/admin/access_urls.php
  8. 0 4
      main/admin/add_courses_to_usergroup.php
  9. 0 2
      main/admin/add_sessions_to_usergroup.php
  10. 1 1
      main/admin/career_dashboard.php
  11. 1 2
      main/inc/ajax/exercise.ajax.php
  12. 0 2
      main/inc/ajax/lp.ajax.php
  13. 1 1
      main/inc/ajax/message.ajax.php
  14. 0 3
      main/inc/ajax/social.ajax.php
  15. 2 2
      main/inc/lib/CourseChatUtils.php
  16. 0 4
      main/inc/lib/api.lib.php
  17. 15 0
      main/inc/lib/banner.lib.php
  18. 1 1
      main/inc/lib/display.lib.php
  19. 29 30
      main/inc/lib/exercise.lib.php
  20. 17 13
      main/inc/lib/geometry.lib.php
  21. 322 198
      main/inc/lib/message.lib.php
  22. 1 1
      main/inc/lib/notebook.lib.php
  23. 10 2
      main/inc/lib/notification.lib.php
  24. 9 11
      main/inc/lib/social.lib.php
  25. 1 1
      main/inc/lib/sortable_table.class.php
  26. 3 0
      main/inc/lib/userportal.lib.php
  27. 9 27
      main/lp/learnpath.class.php
  28. 6 5
      main/messages/download.php
  29. 1 83
      main/messages/inbox.php
  30. 1 1
      main/messages/new_message.php
  31. 2 31
      main/messages/outbox.php
  32. 16 14
      main/messages/view_message.php
  33. 1 1
      main/mySpace/access_details_session.php
  34. 0 2
      main/social/home.php
  35. 1 41
      main/social/promoted_messages.php
  36. 5 17
      main/social/view_promoted_message.php
  37. 10 10
      main/user/subscribe_user.php
  38. 14 16
      main/user/user.php

+ 4 - 18
main/admin/access_url_add_courses_to_url.php

@@ -13,7 +13,6 @@ $cidReset = true;
 require_once __DIR__.'/../inc/global.inc.php';
 
 $this_section = SECTION_PLATFORM_ADMIN;
-
 api_protect_global_admin_script();
 
 if (!api_get_multiple_access_url()) {
@@ -21,15 +20,12 @@ if (!api_get_multiple_access_url()) {
     exit;
 }
 
-$form_sent = 0;
 $first_letter_course = '';
 $courses = [];
 $url_list = [];
 $users = [];
 
-$tbl_access_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 $tbl_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
 $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
 
 /*	Header   */
@@ -68,29 +64,19 @@ if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     }
 }
 
-if (empty($first_letter_user)) {
-    $sql = "SELECT count(*) as num_courses FROM $tbl_course";
-    $result = Database::query($sql);
-    $num_row = Database::fetch_array($result);
-    if ($num_row['num_courses'] > 1000) {
-        //if there are too much num_courses to gracefully handle with the HTML select list,
-        // assign a default filter on users names
-        $first_letter_user = 'A';
-    }
-    unset($result);
-}
-
 $first_letter_course_lower = Database::escape_string(api_strtolower($first_letter_course));
 
 $sql = "SELECT code, title FROM $tbl_course
-		WHERE title LIKE '".$first_letter_course_lower."%' OR title LIKE '".$first_letter_course_lower."%'
+		WHERE 
+            title LIKE '".$first_letter_course_lower."%' OR 
+		    title LIKE '".$first_letter_course_lower."%'
 		ORDER BY title, code DESC ";
 
 $result = Database::query($sql);
 $db_courses = Database::store_result($result);
 unset($result);
 
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
+$sql = "SELECT id, url FROM $tbl_access_url WHERE active = 1 ORDER BY url";
 $result = Database::query($sql);
 $db_urls = Database::store_result($result);
 unset($result);

+ 0 - 5
main/admin/access_url_add_usergroup_to_url.php

@@ -20,16 +20,11 @@ if (!api_get_multiple_access_url()) {
 }
 
 $userGroup = new UserGroup();
-$form_sent = 0;
 $firstLetterUserGroup = null;
 $courses = [];
 $url_list = [];
 
-$tbl_access_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 $tbl_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-
 $tool_name = get_lang('AddUserGroupToURL');
 $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
 $interbreadcrumb[] = ['url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs')];

+ 0 - 4
main/admin/access_url_add_users_to_url.php

@@ -19,14 +19,10 @@ if (!api_get_multiple_access_url()) {
     exit;
 }
 
-$form_sent = 0;
 $first_letter_user = '';
-$first_letter_course = '';
-$courses = [];
 $url_list = [];
 $users = [];
 
-$tbl_access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 $tbl_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
 $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
 

+ 0 - 9
main/admin/access_url_edit_courses_to_url.php

@@ -26,11 +26,6 @@ if (!api_get_multiple_access_url()) {
     exit;
 }
 
-// Database Table Definitions
-$tbl_access_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-
 // setting breadcrumbs
 $tool_name = get_lang('EditCoursesToURL');
 $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
@@ -76,10 +71,6 @@ function remove_item(origin) {
 }
 </script>';
 
-$form_sent = 0;
-$UserList = $SessionList = [];
-$users = $sessions = [];
-
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent = $_POST['form_sent'];
     $course_list = $_POST['course_list'];

+ 1 - 5
main/admin/access_url_edit_usergroup_to_url.php

@@ -71,11 +71,7 @@ function remove_item(origin) {
 }
 </script>';
 
-$form_sent = 0;
 $errorMsg = '';
-$UserList = $SessionList = [];
-$users = $sessions = [];
-
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent = $_POST['form_sent'];
     $course_list = $_POST['course_list'];
@@ -130,7 +126,7 @@ if ($ajax_search) {
 $link_add_type_unique = ['class' => 'disabled'];
 $link_add_type_multiple = [];
 
-if ($add_type == 'multiple') {
+if ($add_type === 'multiple') {
     $link_add_type_unique = [];
     $link_add_type_multiple = ['class' => 'disabled'];
 }

+ 0 - 5
main/admin/access_url_edit_users_to_url.php

@@ -25,9 +25,6 @@ if (!api_get_multiple_access_url()) {
 
 // Database Table Definitions
 $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
-$tbl_access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-$tbl_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
-
 // setting breadcrumbs
 $tool_name = get_lang('EditUsersToURL');
 $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
@@ -73,9 +70,7 @@ function remove_item(origin) {
 }
 </script>';
 
-$form_sent = 0;
 $errorMsg = '';
-$UserList = [];
 $message = '';
 
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {

+ 2 - 2
main/admin/access_urls.php

@@ -20,7 +20,7 @@ if (!api_get_multiple_access_url()) {
     exit;
 }
 
-$interbreadcrumb[] = ["url" => 'index.php', 'name' => get_lang('PlatformAdmin')];
+$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
 $tool_name = get_lang('MultipleAccessURLs');
 Display :: display_header($tool_name);
 
@@ -30,7 +30,7 @@ $url_list = UrlManager::get_url_data();
 
 // Actions
 if (isset($_GET['action'])) {
-    $url_id = (empty($_GET['url_id']) ? 0 : intval($_GET['url_id']));
+    $url_id = empty($_GET['url_id']) ? 0 : (int) $_GET['url_id'];
 
     switch ($_GET['action']) {
         case 'delete_url':

+ 0 - 4
main/admin/add_courses_to_usergroup.php

@@ -47,10 +47,7 @@ function remove_item(origin) {
 
 </script>';
 
-$form_sent = 0;
 $errorMsg = '';
-$sessions = [];
-
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent = $_POST['form_sent'];
     $elements_posted = $_POST['elements_in_name'];
@@ -301,7 +298,6 @@ unset($sessionUsersList);
 </tr>
 </table>
 </form>
-
 <script>
 function moveItem(origin , destination) {
     for(var i = 0 ; i<origin.options.length ; i++) {

+ 0 - 2
main/admin/add_sessions_to_usergroup.php

@@ -73,9 +73,7 @@ function validate_filter() {
 }
 </script>';
 
-$form_sent = 0;
 $errorMsg = '';
-$sessions = [];
 if (isset($_POST['form_sent']) && $_POST['form_sent']) {
     $form_sent = $_POST['form_sent'];
     $elements_posted = $_POST['elements_in_name'];

+ 1 - 1
main/admin/career_dashboard.php

@@ -37,7 +37,7 @@ $career = new Career();
 $condition = ['status = ?' => 1];
 if ($form->validate()) {
     $data = $form->getSubmitValues();
-    $filter = intval($data['filter']);
+    $filter = (int) $data['filter'];
     if (!empty($filter)) {
         $condition = ['status = ? AND id = ? ' => [1, $filter]];
     }

+ 1 - 2
main/inc/ajax/exercise.ajax.php

@@ -549,7 +549,7 @@ switch ($action) {
                     $hotspot_delineation_result = $_SESSION['hotspot_delineation_result'][$objExercise->selectId()][$my_question_id];
                 }
 
-                if ($type == 'simple') {
+                if ($type === 'simple') {
                     // Getting old attempt in order to decrees the total score.
                     $old_result = $objExercise->manage_answer(
                         $exeId,
@@ -563,7 +563,6 @@ switch ($action) {
                         $objExercise->selectPropagateNeg(),
                         []
                     );
-
                     // Removing old score.
                     $total_score = $total_score - $old_result['score'];
                 }

+ 0 - 2
main/inc/ajax/lp.ajax.php

@@ -80,8 +80,6 @@ switch ($action) {
         if (api_is_allowed_to_edit(null, true)) {
             $new_order = $_POST['new_order'];
             $sections = explode('^', $new_order);
-            $new_array = [];
-
             // We have to update parent_item_id, previous_item_id, next_item_id, display_order in the database
             $itemList = new LpItemOrderList();
             foreach ($sections as $items) {

+ 1 - 1
main/inc/ajax/message.ajax.php

@@ -22,7 +22,7 @@ switch ($action) {
         $count_unread_message = 0;
         if (api_get_setting('allow_message_tool') === 'true') {
             // get count unread message and total invitations
-            $count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
+            $count_unread_message = MessageManager::getCountNewMessagesFromDB($userId);
         }
 
         if (api_get_setting('allow_social_tool') === 'true') {

+ 0 - 3
main/inc/ajax/social.ajax.php

@@ -73,7 +73,6 @@ switch ($action) {
         }
         $user_id = api_get_user_id();
         $name_search = Security::remove_XSS($_POST['search_name_q']);
-        $number_friends = 0;
 
         if (isset($name_search) && $name_search != 'undefined') {
             $friends = SocialManager::get_friends($user_id, null, $name_search);
@@ -193,7 +192,6 @@ switch ($action) {
                 }
                 break;
             case 'unload_course':
-                break;
             default:
                 break;
         }
@@ -264,7 +262,6 @@ switch ($action) {
             break;
         }
         $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
-        $length = isset($_REQUEST['length']) ? (int) $_REQUEST['length'] : 10;
         $userId = isset($_REQUEST['u']) ? (int) $_REQUEST['u'] : api_get_user_id();
 
         $html = '';

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

@@ -177,7 +177,7 @@ class CourseChatUtils
             $fileContent = '
                 <div class="message-teacher">
                     <div class="content-message">
-                        <div class="chat-message-block-name">'.$user->getCompleteName().'</div>
+                        <div class="chat-message-block-name">'.UserManager::formatUserFullName($user).'</div>
                         <div class="chat-message-block-content">'.$message.'</div>
                         <div class="message-date">'.$timeNow.'</div>
                     </div>
@@ -191,7 +191,7 @@ class CourseChatUtils
                     <img class="chat-image" src="'.$userPhoto.'">
                     <div class="icon-message"></div>
                     <div class="content-message">
-                        <div class="chat-message-block-name">'.$user->getCompleteName().'</div>
+                        <div class="chat-message-block-name">'.UserManager::formatUserFullName($user).'</div>
                         <div class="chat-message-block-content">'.$message.'</div>
                         <div class="message-date">'.$timeNow.'</div>
                     </div>

+ 0 - 4
main/inc/lib/api.lib.php

@@ -17,10 +17,6 @@ use Symfony\Component\Finder\Finder;
  * @package chamilo.library
  */
 
-/**
- * Constants declaration.
- */
-
 // PHP version requirement.
 define('REQUIRED_PHP_VERSION', '5.6');
 define('REQUIRED_MIN_MEMORY_LIMIT', '128');

+ 15 - 0
main/inc/lib/banner.lib.php

@@ -222,6 +222,21 @@ function accessToWhoIsOnline()
         $access = true;
     }
 
+    if ($access === true) {
+        $profileList = api_get_configuration_value('allow_online_users_by_status');
+        if (!empty($profileList) && isset($profileList['status'])) {
+            $userInfo = api_get_user_info();
+            if ($userInfo['is_admin']) {
+                $userInfo['status'] = PLATFORM_ADMIN;
+            }
+            $profileList = $profileList['status'];
+            $access = false;
+            if (in_array($userInfo['status'], $profileList)) {
+                $access = true;
+            }
+        }
+    }
+
     return $access;
 }
 

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

@@ -1804,7 +1804,7 @@ class Display
             $session = [];
             $session['category_id'] = $session_info['session_category_id'];
             $session['title'] = $session_info['name'];
-            $session['id_coach'] = $session_info['id_coach'];
+            $session['coach_id'] = $session['id_coach'] = $session_info['id_coach'];
             $session['dates'] = '';
             $session['coach'] = '';
             if (api_get_setting('show_session_coach') === 'true' && isset($coachInfo['complete_name'])) {

+ 29 - 30
main/inc/lib/exercise.lib.php

@@ -48,6 +48,7 @@ class ExerciseLib
         $show_icon = false
     ) {
         $course_id = $exercise->course_id;
+        $exerciseId = $exercise->iId;
 
         if (empty($course_id)) {
             return '';
@@ -198,7 +199,7 @@ class ExerciseLib
                     // Add nanog
                     if (api_get_setting('enable_record_audio') === 'true') {
                         //@todo pass this as a parameter
-                        global $exercise_stat_info, $exerciseId;
+                        global $exercise_stat_info;
                         if (!empty($exercise_stat_info)) {
                             $objQuestionTmp->initFile(
                                 api_get_session_id(),
@@ -339,8 +340,7 @@ class ExerciseLib
                              $('.question-validate-btn').attr('disabled', 'disabled');
                         } else {
                             $('.question-validate-btn').removeAttr('disabled');
-                        }
-                    
+                        }                    
                     });
                 </script>";
 
@@ -359,6 +359,7 @@ class ExerciseLib
                         $header .= Display::tag('th', $item);
                     }
                 }
+
                 if ($show_comment) {
                     $header .= Display::tag('th', get_lang('Feedback'));
                 }
@@ -372,15 +373,18 @@ class ExerciseLib
                 foreach ($objQuestionTmp->options as $item) {
                     $colorBorder1 = ($cpt1 == (count($objQuestionTmp->options) - 1))
                         ? '' : 'border-right: solid #FFFFFF 1px;';
-                    if ($item == 'True' || $item == 'False') {
-                        $header1 .= Display::tag('th',
+                    if ($item === 'True' || $item === 'False') {
+                        $header1 .= Display::tag(
+                            'th',
                             get_lang($item),
                             ['style' => 'background-color: #F7C9B4; color: black;'.$colorBorder1]
                         );
                     } else {
-                        $header1 .= Display::tag('th',
+                        $header1 .= Display::tag(
+                            'th',
                             $item,
-                            ['style' => 'background-color: #e6e6ff; color: black;padding:5px; '.$colorBorder1]);
+                            ['style' => 'background-color: #e6e6ff; color: black;padding:5px; '.$colorBorder1]
+                        );
                     }
                     $cpt1++;
                 }
@@ -401,7 +405,6 @@ class ExerciseLib
                     get_lang('DegreeOfCertaintyIAmVerySure'),
                 ];
                 $counter2 = 0;
-
                 foreach ($objQuestionTmp->options as $item) {
                     if ($item == 'True' || $item == 'False') {
                         $header2 .= Display::tag('td',
@@ -1385,7 +1388,7 @@ HTML;
             }
             echo $s;
         } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
-            global $exerciseId, $exe_id;
+            global $exe_id;
             // Question is a HOT_SPOT
             // Checking document/images visibility
             if (api_is_platform_admin() || api_is_course_admin()) {
@@ -1462,14 +1465,14 @@ HTML;
                             </div>
                         </div>
                         <script>
-                                new ".($answerType == HOT_SPOT ? "HotspotQuestion" : "DelineationQuestion")."({
-                                    questionId: $questionId,
-                                    exerciseId: $exerciseId,
-                                    exeId: 0,
-                                    selector: '#hotspot-preview-$questionId',
-                                    for: 'preview',
-                                    relPath: '$relPath'
-                                });
+                            new ".($answerType == HOT_SPOT ? "HotspotQuestion" : "DelineationQuestion")."({
+                                questionId: $questionId,
+                                exerciseId: $exerciseId,
+                                exeId: 0,
+                                selector: '#hotspot-preview-$questionId',
+                                for: 'preview',
+                                relPath: '$relPath'
+                            });
                         </script>
                     ";
 
@@ -1500,7 +1503,7 @@ HOTSPOT;
                         $(function() {
                             new ".($answerType == HOT_SPOT_DELINEATION ? 'DelineationQuestion' : 'HotspotQuestion')."({
                                 questionId: $questionId,
-                                exerciseId: $exe_id,
+                                exerciseId: $exerciseId,
                                 selector: '#question_div_' + $questionId + ' .hotspot-image',
                                 for: 'user',
                                 relPath: '$relPath'
@@ -1565,7 +1568,7 @@ HOTSPOT;
                                 <script>
                                     AnnotationQuestion({
                                         questionId: '.$questionId.',
-                                        exerciseId: '.$exe_id.',
+                                        exerciseId: '.$exerciseId.',
                                         relPath: \''.$relPath.'\',
                                         courseId: '.$course_id.',
                                     });
@@ -1969,8 +1972,7 @@ HOTSPOT;
         $roundValues = false
     ) {
         //@todo replace all this globals
-        global $documentPath, $filter;
-
+        global $filter;
         $courseCode = empty($courseCode) ? api_get_course_id() : $courseCode;
         $courseInfo = api_get_course_info($courseCode);
 
@@ -1978,6 +1980,8 @@ HOTSPOT;
             return [];
         }
 
+        $documentPath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
+
         $course_id = $courseInfo['real_id'];
         $sessionId = api_get_session_id();
         $exercise_id = (int) $exercise_id;
@@ -2131,7 +2135,7 @@ HOTSPOT;
             $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname";
 
             if ($get_count) {
-                $sql_select = "SELECT count(te.exe_id) ";
+                $sql_select = 'SELECT count(te.exe_id) ';
             } else {
                 $sql_select = "SELECT DISTINCT
                     user_id,
@@ -2197,8 +2201,8 @@ HOTSPOT;
                     AND tth.c_id = $course_id
                     $hotpotatoe_where
                     $sqlWhereOption
-                    AND user.status NOT IN(".api_get_users_status_ignored_in_reports('string').")
-                ORDER BY tth.c_id ASC, tth.exe_date DESC";
+                    AND user.status NOT IN (".api_get_users_status_ignored_in_reports('string').")
+                ORDER BY tth.c_id ASC, tth.exe_date DESC ";
         }
 
         if (empty($sql)) {
@@ -2212,9 +2216,7 @@ HOTSPOT;
             return $rowx[0];
         }
 
-        $teacher_list = CourseManager::get_teacher_list_from_course_code(
-            $courseCode
-        );
+        $teacher_list = CourseManager::get_teacher_list_from_course_code($courseCode);
         $teacher_id_list = [];
         if (!empty($teacher_list)) {
             foreach ($teacher_list as $teacher) {
@@ -2268,7 +2270,6 @@ HOTSPOT;
                     $from_gradebook = true;
                 }
                 $sizeof = count($results);
-                $user_list_id = [];
                 $locked = api_resource_is_locked_by_gradebook(
                     $exercise_id,
                     LINK_EXERCISE
@@ -2347,7 +2348,6 @@ HOTSPOT;
                     }
 
                     $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0;
-                    $user_list_id[] = $results[$i]['exe_user_id'];
                     $id = $results[$i]['exe_id'];
                     $dt = api_convert_and_format_date($results[$i]['exe_weighting']);
 
@@ -4415,7 +4415,6 @@ EOT;
         // Hide results
         $show_results = false;
         $show_only_score = false;
-
         if (in_array($objExercise->results_disabled,
             [
                 RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,

+ 17 - 13
main/inc/lib/geometry.lib.php

@@ -6,6 +6,7 @@
  * @package chamilo.include.geometry
  */
 define('DEBUG', false);
+
 /**
  * poly_init -    build the array which will store the image of the polygone.
  *
@@ -52,7 +53,6 @@ function poly_compile($poly, $max, $test = false)
     // looking for EDGES
     // may be optimized by a dynamic choice
     // between Y and X based on max[y]<max[x]
-
     /*
      * bords    cointains the edges of the polygone
      *        it is an array of array,
@@ -66,7 +66,6 @@ function poly_compile($poly, $max, $test = false)
         $bord_lenght = $max['y'];
     }
 
-    //$bords = array_fill(0, $bord_lenght-1, array()); // building this array
     $bords = array_fill(0, $bord_lenght, []); // building this array
 
     /* adding the first point of the polygone */
@@ -78,7 +77,7 @@ function poly_compile($poly, $max, $test = false)
     $i = 1; // we re-use $i and $old_pente bellow the loop
     $old_pente = 0;
     // for each points of the polygon but the first
-    for (; $i < sizeof($poly) && (!empty($poly[$i]['x']) && !empty($poly[$i]['y'])); $i++) {
+    for (; $i < count($poly) && (!empty($poly[$i]['x']) && !empty($poly[$i]['y'])); $i++) {
         /* special cases */
         if ($poly[$i - 1]['y'] == $poly[$i]['y']) {
             if ($poly[$i - 1]['x'] == $poly[$i]['x']) {
@@ -95,9 +94,15 @@ function poly_compile($poly, $max, $test = false)
 
         //echo 'point:'.$poly[$i]['y']; bug here
         // adding the point as a part of an edge
-        if (is_array($bords[$poly[$i]['y']])) { //avoid warning
-        array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
+        if (isset($poly[$i]) &&
+            isset($poly[$i]['y']) &&
+            isset($bords[$poly[$i]['y']]) &&
+            is_array($bords[$poly[$i]['y']])
+        ) {
+            // Avoid warning
+            array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
         }
+
         if (DEBUG) {
             echo '('.$poly[$i]['x'].';'.$poly[$i]['y'].')   ';
         }
@@ -113,7 +118,10 @@ function poly_compile($poly, $max, $test = false)
         if ($i > 1) {
             if (($old_pente < 0 && $pente > 0)
                 || ($old_pente > 0 && $pente < 0)) {
-                if (is_array($bords[$poly[$i]['y']])) { //avoid warning
+                if (isset($poly[$i]) && isset($poly[$i]['y']) &&
+                    isset($bords[$poly[$i]['y']]) &&
+                    is_array($bords[$poly[$i]['y']])
+                ) {
                     array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
                 }
 
@@ -127,9 +135,6 @@ function poly_compile($poly, $max, $test = false)
         /* detect the direction of the elevation in Y */
         $dy_inc = ($poly[$i]['y'] - $poly[$i - 1]['y']) > 0 ? 1 : -1;
         $x = $poly[$i - 1]['x'];
-//        if (DEBUG) echo "init: ".$poly[$i-1]['y']."  dy_inc: ".$dy_inc.
-//            "   end: ".$poly[$i]['y']."   pente:".$pente;
-
         /* computing points between $poly[$i-1]['y'] and $poly[$i-1]['y'] */
 
         // we iterate w/ $dy in ]$poly[$i-1]['y'],$poly[$i-1]['y'][
@@ -139,13 +144,13 @@ function poly_compile($poly, $max, $test = false)
             $dy += $dy_inc) {
             $x += $pente * $dy_inc;
             array_push($bords[$dy], $x);
-//            if (DEBUG) echo '/('.$x.';'.$dy.')   ';
         }
         $old_pente = $pente;
     }
 
     // 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
         // elevation between $poly[0]['x'] and $poly[1]['x'])
         $rest = $poly[0]['y'] - $poly[1]['y'];
         if ($rest != 0) {
@@ -193,12 +198,11 @@ function poly_compile($poly, $max, $test = false)
         For each pair of point, we color the points in between */
     $n = count($bords);
     for ($i = 0; $i < $n; $i++) {  // Y
-        //error_log(__FILE__.' - Border Num '.$i,0);
         if (is_array($bords[$i])) {
             sort($bords[$i]);
         }
 
-        for ($j = 0; $j < sizeof($bords[$i]); $j += 2) { // bords
+        for ($j = 0; $j < count($bords[$i]); $j += 2) { // bords
             if (!isset($bords[$i][$j + 1])) {
                 continue;
             }

+ 322 - 198
main/inc/lib/message.lib.php

@@ -15,6 +15,10 @@ use ChamiloSession as Session;
  */
 class MessageManager
 {
+    const MESSAGE_TYPE_INBOX = 1;
+    const MESSAGE_TYPE_OUTBOX = 2;
+    const MESSAGE_TYPE_PROMOTED = 3;
+
     /**
      * Get count new messages for the current user from the database.
      *
@@ -53,30 +57,15 @@ class MessageManager
      *
      * @return int
      */
-    public static function getNumberOfMessages($params = [])
+    public static function getNumberOfMessages($params)
     {
-        $messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
-        if (isset($params['message_status']) && !empty($params['message_status'])) {
-            $messageStatus = $params['message_status'];
-        }
-        $messageStatus = array_map('intval', $messageStatus);
-        $messageStatusCondition = implode("','", $messageStatus);
-
         $table = Database::get_main_table(TABLE_MESSAGE);
-        $keyword = isset($params['keyword']) && !empty($params['keyword']) ? $params['keyword'] : '';
-
-        $keywordCondition = '';
-        if (!empty($keyword)) {
-            $keyword = Database::escape_string($keyword);
-            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
-        }
+        $conditions = self::getWhereConditions($params);
 
         $sql = "SELECT COUNT(id) as number_messages
                 FROM $table
                 WHERE 
-                    msg_status IN ('$messageStatusCondition') AND
-                    user_receiver_id = ".api_get_user_id()."
-                    $keywordCondition
+                    $conditions
                 ";
         $result = Database::query($sql);
         $result = Database::fetch_array($result);
@@ -88,6 +77,53 @@ class MessageManager
         return 0;
     }
 
+    /**
+     * @param array $extraParams
+     *
+     * @return string
+     */
+    public static function getWhereConditions($extraParams)
+    {
+        $userId = api_get_user_id();
+
+        $keyword = isset($extraParams['keyword']) && !empty($extraParams['keyword']) ? $extraParams['keyword'] : '';
+        $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
+
+        if (empty($type)) {
+            return '';
+        }
+
+        switch ($type) {
+            case self::MESSAGE_TYPE_INBOX:
+                $statusList = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
+                $userCondition = " user_receiver_id = $userId AND";
+                break;
+            case self::MESSAGE_TYPE_OUTBOX:
+                $statusList = [MESSAGE_STATUS_OUTBOX];
+                $userCondition = " user_sender_id = $userId AND";
+                break;
+            case self::MESSAGE_TYPE_PROMOTED:
+                $statusList = [MESSAGE_STATUS_PROMOTED];
+                $userCondition = " user_receiver_id = $userId AND";
+                break;
+        }
+
+        if (empty($statusList)) {
+            return '';
+        }
+
+        $keywordCondition = '';
+        if (!empty($keyword)) {
+            $keyword = Database::escape_string($keyword);
+            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
+        }
+        $messageStatusCondition = implode("','", $statusList);
+
+        return " $userCondition
+                 msg_status IN ('$messageStatusCondition')
+                 $keywordCondition";
+    }
+
     /**
      * Gets information about some messages, used for the inbox sortable table.
      *
@@ -108,8 +144,6 @@ class MessageManager
     ) {
         $from = (int) $from;
         $numberOfItems = (int) $numberOfItems;
-        $userId = api_get_user_id();
-
         // Forcing this order.
         if (!isset($direction)) {
             $column = 2;
@@ -125,24 +159,29 @@ class MessageManager
             $column = 2;
         }
 
-        $keyword = isset($extraParams['keyword']) && !empty($extraParams['keyword']) ? $extraParams['keyword'] : '';
-        $viewUrl = api_get_path(WEB_CODE_PATH).'messages/view_message.php';
-        if (isset($extraParams['view_url']) && !empty($extraParams['view_url'])) {
-            $viewUrl = $extraParams['view_url'];
+        $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
+
+        if (empty($type)) {
+            return [];
         }
 
-        $keywordCondition = '';
-        if (!empty($keyword)) {
-            $keyword = Database::escape_string($keyword);
-            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
+        $viewUrl = '';
+        switch ($type) {
+            case self::MESSAGE_TYPE_OUTBOX:
+            case self::MESSAGE_TYPE_INBOX:
+                $viewUrl = api_get_path(WEB_CODE_PATH).'messages/view_message.php';
+                break;
+            case self::MESSAGE_TYPE_PROMOTED:
+                $viewUrl = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
+                break;
         }
+        $viewUrl .= '?type='.$type;
+
+        $whereConditions = self::getWhereConditions($extraParams);
 
-        $messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
-        if (isset($extraParams['message_status']) && !empty($extraParams['message_status'])) {
-            $messageStatus = $extraParams['message_status'];
+        if (empty($whereConditions)) {
+            return [];
         }
-        $messageStatus = array_map('intval', $messageStatus);
-        $messageStatusCondition = implode("','", $messageStatus);
 
         $table = Database::get_main_table(TABLE_MESSAGE);
         $sql = "SELECT 
@@ -153,9 +192,7 @@ class MessageManager
                     user_sender_id
                 FROM $table
                 WHERE
-                    user_receiver_id = $userId AND
-                    msg_status IN ('$messageStatusCondition')
-                    $keywordCondition
+                    $whereConditions
                 ORDER BY col$column $direction
                 LIMIT $from, $numberOfItems";
 
@@ -183,7 +220,7 @@ class MessageManager
             $userInfo = api_get_user_info($senderId);
             $message[3] = '';
             if (!empty($senderId) && !empty($userInfo)) {
-                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
+                $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
                 $message[1] .= $userInfo['complete_name_with_username'];
                 if (in_array('reply', $actions)) {
                     $message[3] =
@@ -194,7 +231,7 @@ class MessageManager
                         );
                 }
             } else {
-                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
+                $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
                 $message[1] .= get_lang('UnknownUser');
                 if (in_array('reply', $actions)) {
                     $message[3] =
@@ -815,7 +852,10 @@ class MessageManager
         }
 
         $sql = "SELECT * FROM $table
-                WHERE id = $id AND msg_status <> ".MESSAGE_STATUS_OUTBOX;
+                WHERE 
+                    id = $id AND 
+                    user_receiver_id = $user_receiver_id AND
+                    msg_status <> ".MESSAGE_STATUS_OUTBOX;
         $rs = Database::query($sql);
 
         if (Database::num_rows($rs) > 0) {
@@ -847,16 +887,16 @@ class MessageManager
      */
     public static function delete_message_by_user_sender($user_sender_id, $id)
     {
-        if ($id != strval(intval($id))) {
+        $user_sender_id = (int) $user_sender_id;
+        $id = (int) $id;
+
+        if (empty($id) || empty($user_sender_id)) {
             return false;
         }
 
         $table = Database::get_main_table(TABLE_MESSAGE);
 
-        $id = intval($id);
-        $user_sender_id = intval($user_sender_id);
-
-        $sql = "SELECT * FROM $table WHERE id='$id'";
+        $sql = "SELECT * FROM $table WHERE id = $id AND user_sender_id= $user_sender_id";
         $rs = Database::query($sql);
 
         if (Database::num_rows($rs) > 0) {
@@ -864,8 +904,8 @@ class MessageManager
             self::delete_message_attachment_file($id, $user_sender_id);
             // delete message
             $sql = "UPDATE $table
-                    SET msg_status = ".MESSAGE_STATUS_DELETED."
-                    WHERE user_sender_id='$user_sender_id' AND id='$id'";
+                    SET msg_status = '".MESSAGE_STATUS_DELETED."'
+                    WHERE user_sender_id= $user_sender_id AND id= $id";
             Database::query($sql);
 
             return true;
@@ -1266,30 +1306,34 @@ class MessageManager
     /**
      * display message box in the inbox.
      *
-     * @param int the message id
-     * @param string inbox or outbox strings are available
+     * @param int $messageId
+     * @param int $type
      *
      * @todo replace numbers with letters in the $row array pff...
      *
      * @return string html with the message content
      */
-    public static function showMessageBox($messageId, $source)
+    public static function showMessageBox($messageId, $type)
     {
-        $table = Database::get_main_table(TABLE_MESSAGE);
         $messageId = (int) $messageId;
 
-        if (empty($messageId)) {
+        if (empty($messageId) || empty($type)) {
             return '';
         }
         $currentUserId = api_get_user_id();
 
-        switch ($source) {
-            case 'outbox':
+        $table = Database::get_main_table(TABLE_MESSAGE);
+
+        if (empty($type)) {
+            return '';
+        }
+
+        switch ($type) {
+            case self::MESSAGE_TYPE_OUTBOX:
                 $status = MESSAGE_STATUS_OUTBOX;
                 $userCondition = " user_sender_id = $currentUserId AND ";
-
                 break;
-            case 'inbox':
+            case self::MESSAGE_TYPE_INBOX:
                 $status = MESSAGE_STATUS_NEW;
                 $userCondition = " user_receiver_id = $currentUserId AND ";
 
@@ -1298,17 +1342,21 @@ class MessageManager
                           WHERE id = $messageId ";
                 Database::query($query);
                 break;
-            case 'promoted_messages':
+            case self::MESSAGE_TYPE_PROMOTED:
                 $status = MESSAGE_STATUS_PROMOTED;
                 $userCondition = " user_receiver_id = $currentUserId AND ";
                 break;
         }
 
+        if (empty($userCondition)) {
+            return '';
+        }
+
         $query = "SELECT * FROM $table
-                          WHERE                            
-                            id = $messageId AND 
-                            $userCondition
-                            msg_status = $status";
+                  WHERE                            
+                    id = $messageId AND 
+                    $userCondition
+                    msg_status = $status";
         $result = Database::query($query);
         $row = Database::fetch_array($result, 'ASSOC');
 
@@ -1319,10 +1367,7 @@ class MessageManager
         $user_sender_id = $row['user_sender_id'];
 
         // get file attachments by message id
-        $files_attachments = self::getAttachmentLinkList(
-            $messageId,
-            $source
-        );
+        $files_attachments = self::getAttachmentLinkList($messageId, $type);
 
         $row['content'] = str_replace('</br>', '<br />', $row['content']);
         $title = Security::remove_XSS($row['title'], STUDENT, true);
@@ -1341,7 +1386,7 @@ class MessageManager
             );
         }
 
-        $message_content = Display::page_subheader(str_replace("\\", "", $title));
+        $message_content = Display::page_subheader(str_replace("\\", '', $title));
 
         $receiverUserInfo = [];
         if (!empty($row['user_receiver_id'])) {
@@ -1351,49 +1396,51 @@ class MessageManager
         $message_content .= '<tr>';
         if (api_get_setting('allow_social_tool') === 'true') {
             $message_content .= '<div class="row">';
-            if ($source === 'outbox') {
-                $message_content .= '<div class="col-md-12">';
-                $message_content .= '<ul class="list-message">';
-                $message_content .= '<li>'.$userImage.'</li>';
-                $message_content .= '<li>'.$name.'&nbsp;';
-                if (!empty($receiverUserInfo)) {
-                    $message_content .= api_strtolower(
-                            get_lang('To')
-                        ).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
-                } else {
-                    $message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
-                }
+            $message_content .= '<div class="col-md-12">';
+            $message_content .= '<ul class="list-message">';
 
-                $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
-                $message_content .= '</ul>';
-                $message_content .= '</div>';
+            if (!empty($user_sender_id)) {
+                $message_content .= '<li>'.$userImage.'</li>';
+                $message_content .= '<li>';
+                $message_content .= Display::url(
+                    $name,
+                    api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id
+                );
             } else {
-                $message_content .= '<div class="col-md-12">';
-                $message_content .= '<ul class="list-message">';
-                if (!empty($user_sender_id)) {
-                    $message_content .= '<li>'.$userImage.'</li>';
-                    $message_content .= '<li><a href="'.api_get_path(
-                            WEB_PATH
-                        ).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a>';
-                } else {
-                    $message_content .= '<li>'.$name;
-                }
+                $message_content .= '<li>'.$name;
+            }
 
-                if ($source === 'inbox') {
+            switch ($type) {
+                case self::MESSAGE_TYPE_INBOX:
+                    //$message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
                     $message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
-                }
-                $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
-                $message_content .= '</ul>';
-                $message_content .= '</div>';
+                    break;
+                case self::MESSAGE_TYPE_OUTBOX:
+                    if (!empty($receiverUserInfo)) {
+                        $message_content .= '&nbsp;'.api_strtolower(
+                                get_lang('To')
+                            ).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
+                    }
+                    break;
+                case self::MESSAGE_TYPE_PROMOTED:
+                    break;
             }
+
+            $message_content .= '&nbsp;<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
+            $message_content .= '</ul>';
+            $message_content .= '</div>';
             $message_content .= '</div>';
         } else {
-            if ($source === 'outbox') {
-                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
-                    $receiverUserInfo['complete_name_with_username'].'</b>';
-            } else {
-                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
-                    get_lang('Me').'</b>';
+            switch ($type) {
+                case self::MESSAGE_TYPE_INBOX:
+                    $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
+                        get_lang('Me').'</b>';
+                    break;
+                case self::MESSAGE_TYPE_OUTBOX:
+
+                    $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
+                        $receiverUserInfo['complete_name_with_username'].'</b>';
+                    break;
             }
         }
 
@@ -1411,19 +1458,21 @@ class MessageManager
             $social_link = 'f=social';
         }
 
-        if ($source == 'outbox') {
-            $message_content .= '<a href="outbox.php?'.$social_link.'">'.
-                Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
-        } elseif ($source === 'inbox') {
-            $message_content .= '<a href="inbox.php?'.$social_link.'">'.
-                Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
-            $message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
-                Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
-        }
-
-        if (in_array($source, ['inbox', 'outbox'])) {
-            $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
-                Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
+        switch ($type) {
+            case self::MESSAGE_TYPE_OUTBOX:
+                $message_content .= '<a href="outbox.php?'.$social_link.'">'.
+                    Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
+                $message_content .= '<a href="outbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
+                    Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
+                break;
+            case self::MESSAGE_TYPE_INBOX:
+                $message_content .= '<a href="inbox.php?'.$social_link.'">'.
+                    Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
+                $message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
+                    Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
+                $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
+                    Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
+                break;
         }
 
         $message_content .= '</div></td>
@@ -1624,7 +1673,7 @@ class MessageManager
         $items_page_nr = null;
 
         $user_sender_info = api_get_user_info($main_message['user_sender_id']);
-        $files_attachments = self::getAttachmentLinkList($main_message['id']);
+        $files_attachments = self::getAttachmentLinkList($main_message['id'], 0);
         $name = $user_sender_info['complete_name'];
 
         $topic_page_nr = isset($_GET['topics_page_nr']) ? (int) $_GET['topics_page_nr'] : null;
@@ -1766,7 +1815,7 @@ class MessageManager
                 $links .= '<div class="pull-right">';
                 $html_items = '';
                 $user_sender_info = api_get_user_info($topic['user_sender_id']);
-                $files_attachments = self::getAttachmentLinkList($topic['id']);
+                $files_attachments = self::getAttachmentLinkList($topic['id'], 0);
                 $name = $user_sender_info['complete_name'];
 
                 $links .= '<div class="btn-group btn-group-sm">';
@@ -1997,12 +2046,12 @@ class MessageManager
     /**
      * Get array of links (download) for message attachment files.
      *
-     * @param int    $messageId
-     * @param string $type      message list (inbox/outbox)
+     * @param int $messageId
+     * @param int $type
      *
      * @return array
      */
-    public static function getAttachmentLinkList($messageId, $type = '')
+    public static function getAttachmentLinkList($messageId, $type)
     {
         $files = self::getAttachmentList($messageId);
         // get file attachments by message id
@@ -2020,10 +2069,9 @@ class MessageManager
                 $comment = !empty($comment) ? '&nbsp;-&nbsp;<i>'.$comment.'</i>' : '';
 
                 $attachmentLine = $attachIcon.'&nbsp;'.$link.'&nbsp;('.$size.')'.$comment;
-                if ($row_file['comment'] == 'audio_message') {
+                if ($row_file['comment'] === 'audio_message') {
                     $attachmentLine = '<audio src="'.$archiveURL.$archiveFile.'"/>';
                 }
-
                 $list[] = $attachmentLine;
             }
         }
@@ -2092,23 +2140,72 @@ class MessageManager
     }
 
     /**
-     * @param string $statusList
-     * @param array  $keyword
+     * @param string $type
+     * @param string $keyword
      * @param array  $actions
-     * @param string $viewUrl
      *
      * @return string
      */
-    public static function getMessageGrid($statusList, $keyword, $actions = [], $viewUrl = '')
+    public static function getMessageGrid($type, $keyword, $actions = [])
     {
-        if (empty($statusList)) {
-            return '';
+        $html = '';
+        // display sortable table with messages of the current user
+        $table = new SortableTable(
+            'message_inbox',
+            ['MessageManager', 'getNumberOfMessages'],
+            ['MessageManager', 'getMessageData'],
+            2,
+            20,
+            'DESC'
+        );
+
+        $table->setDataFunctionParams(
+            ['keyword' => $keyword, 'type' => $type, 'actions' => $actions]
+        );
+        $table->set_header(0, '', false, ['style' => 'width:15px;']);
+        $table->set_header(1, get_lang('Messages'), false);
+        $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
+        $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:120px;']);
+
+        if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
+            $parameters['f'] = 'social';
+            $table->set_additional_parameters($parameters);
         }
+
+        $defaultActions = [
+            'delete' => get_lang('DeleteSelectedMessages'),
+            'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
+            'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
+        ];
+
+        if (!in_array('delete', $actions)) {
+            unset($defaultActions['delete']);
+        }
+        if (!in_array('mark_as_unread', $actions)) {
+            unset($defaultActions['mark_as_unread']);
+        }
+        if (!in_array('mark_as_read', $actions)) {
+            unset($defaultActions['mark_as_read']);
+        }
+
+        $table->set_form_actions($defaultActions);
+
+        $html .= $table->return_table();
+
+        return $html;
+    }
+
+    /**
+     * @param string $keyword
+     *
+     * @return string
+     */
+    public static function inboxDisplay($keyword = '')
+    {
         $success = get_lang('SelectedMessagesDeleted');
         $success_read = get_lang('SelectedMessagesRead');
         $success_unread = get_lang('SelectedMessagesUnRead');
         $currentUserId = api_get_user_id();
-        $html = '';
 
         if (isset($_REQUEST['action'])) {
             switch ($_REQUEST['action']) {
@@ -2122,11 +2219,11 @@ class MessageManager
                             );
                         }
                     }
-                    $html .= Display::return_message(
-                        api_xml_http_response_encode($success_unread),
+                    Display::addFlash(Display::return_message(
+                        $success_unread,
                         'normal',
                         false
-                    );
+                    ));
                     break;
                 case 'mark_as_read':
                     if (is_array($_POST['id'])) {
@@ -2138,75 +2235,41 @@ class MessageManager
                             );
                         }
                     }
-                    $html .= Display::return_message(
-                        api_xml_http_response_encode($success_read),
+                    Display::addFlash(Display::return_message(
+                        $success_read,
                         'normal',
                         false
-                    );
+                    ));
                     break;
                 case 'delete':
                     foreach ($_POST['id'] as $index => $messageId) {
                         self::delete_message_by_user_receiver($currentUserId, $messageId);
                     }
-                    $html .= Display::return_message(
-                        api_xml_http_response_encode($success),
+                    Display::addFlash(Display::return_message(
+                        $success,
                         'normal',
                         false
-                    );
+                    ));
                     break;
                 case 'deleteone':
-                    self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
-                    $html .= Display::return_message(
-                        api_xml_http_response_encode($success),
-                        'confirmation',
-                        false
-                    );
+                    $result = self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
+                    if ($result) {
+                        Display::addFlash(
+                            Display::return_message(
+                                $success,
+                                'confirmation',
+                                false
+                            )
+                        );
+                    }
                     break;
             }
+            header('Location: '.api_get_self());
+            exit;
         }
 
-        // display sortable table with messages of the current user
-        $table = new SortableTable(
-            'message_inbox',
-            ['MessageManager', 'getNumberOfMessages'],
-            ['MessageManager', 'getMessageData'],
-            2,
-            20,
-            'DESC'
-        );
-
-        $table->setDataFunctionParams(
-            ['keyword' => $keyword, 'message_status' => $statusList, 'actions' => $actions, 'view_url' => $viewUrl]
-        );
-        $table->set_header(0, '', false, ['style' => 'width:15px;']);
-        $table->set_header(1, get_lang('Messages'), false);
-        $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
-        $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:120px;']);
-
-        if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
-            $parameters['f'] = 'social';
-            $table->set_additional_parameters($parameters);
-        }
-
-        $defaultActions = [
-            'delete' => get_lang('DeleteSelectedMessages'),
-            'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
-            'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
-        ];
-
-        if (!in_array('delete', $actions)) {
-            unset($defaultActions['delete']);
-        }
-        if (!in_array('mark_as_unread', $actions)) {
-            unset($defaultActions['mark_as_unread']);
-        }
-        if (!in_array('mark_as_read', $actions)) {
-            unset($defaultActions['mark_as_read']);
-        }
-
-        $table->set_form_actions($defaultActions);
-
-        $html .= $table->return_table();
+        $actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
+        $html = self::getMessageGrid(self::MESSAGE_TYPE_INBOX, $keyword, $actions);
 
         return $html;
     }
@@ -2216,10 +2279,39 @@ class MessageManager
      *
      * @return string
      */
-    public static function inboxDisplay($keyword = '')
+    public static function getPromotedMessagesGrid($keyword)
     {
-        $actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
-        $html = self::getMessageGrid([MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD], $keyword, $actions);
+        $actions = ['delete'];
+        $currentUserId = api_get_user_id();
+
+        $success = get_lang('SelectedMessagesDeleted');
+        if (isset($_REQUEST['action'])) {
+            switch ($_REQUEST['action']) {
+                case 'delete':
+                    foreach ($_POST['id'] as $index => $messageId) {
+                        self::delete_message_by_user_receiver($currentUserId, $messageId);
+                    }
+                    Display::addFlash(Display::return_message(
+                        $success,
+                        'normal',
+                        false
+                    ));
+                    break;
+                case 'deleteone':
+                    self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
+                    Display::addFlash(Display::return_message(
+                        $success,
+                        'confirmation',
+                        false
+                    ));
+                    break;
+            }
+
+            header('Location: '.api_get_self());
+            exit;
+        }
+
+        $html = self::getMessageGrid(self::MESSAGE_TYPE_PROMOTED, $keyword, $actions);
 
         return $html;
     }
@@ -2229,12 +2321,40 @@ class MessageManager
      *
      * @return string
      */
-    public static function getPromotedMessagesGrid($keyword = '')
+    public static function outBoxDisplay($keyword)
     {
-        //$actions = ['edit', 'delete'];
         $actions = ['delete'];
-        $url = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
-        $html = self::getMessageGrid([MESSAGE_STATUS_PROMOTED], $keyword, $actions, $url);
+
+        $success = get_lang('SelectedMessagesDeleted');
+        $currentUserId = api_get_user_id();
+        if (isset($_REQUEST['action'])) {
+            switch ($_REQUEST['action']) {
+                case 'delete':
+                    foreach ($_POST['id'] as $index => $messageId) {
+                        self::delete_message_by_user_sender($currentUserId, $messageId);
+                    }
+                    Display::addFlash(Display::return_message(
+                        $success,
+                        'normal',
+                        false
+                    ));
+
+                    break;
+                case 'deleteone':
+                    self::delete_message_by_user_sender($currentUserId, $_GET['id']);
+                    Display::addFlash(Display::return_message(
+                        $success,
+                        'confirmation',
+                        false
+                    ));
+                    break;
+            }
+
+            header('Location: '.api_get_self());
+            exit;
+        }
+
+        $html = self::getMessageGrid(self::MESSAGE_TYPE_OUTBOX, $keyword, $actions);
 
         return $html;
     }
@@ -2277,13 +2397,13 @@ class MessageManager
         $table = new SortableTable(
             'message_outbox',
             ['MessageManager', 'getNumberOfMessages'],
-            ['MessageManager', 'get_message_data_sent'],
+            ['MessageManager', 'getMessageData'],
             2,
             20,
             'DESC'
         );
         $table->setDataFunctionParams(
-            ['keyword' => $keyword, 'message_status' => [MESSAGE_STATUS_OUTBOX]]
+            ['keyword' => $keyword, 'type' => self::MESSAGE_TYPE_OUTBOX]
         );
 
         $table->set_header(0, '', false, ['style' => 'width:15px;']);
@@ -2746,13 +2866,15 @@ class MessageManager
 
         $countLikes = self::countLikesAndDislikes($messageId, $userId);
 
+        $class = $countLikes['user_liked'] ? 'btn-primary' : 'btn-default';
+
         $btnLike = Display::button(
             'like',
             Display::returnFontAwesomeIcon('thumbs-up', '', true)
                 .PHP_EOL.'<span>'.$countLikes['likes'].'</span>',
             [
                 'title' => get_lang('VoteLike'),
-                'class' => 'btn btn-default social-like '.($countLikes['user_liked'] ? 'disabled' : ''),
+                'class' => 'btn  social-like '.$class,
                 'data-status' => 'like',
                 'data-message' => $messageId,
                 'data-group' => $groupId,
@@ -2761,13 +2883,15 @@ class MessageManager
 
         $btnDislike = '';
         if (api_get_configuration_value('disable_dislike_option') === false) {
+            $disabled = $countLikes['user_disliked'] ? 'btn-danger' : 'btn-default';
+
             $btnDislike = Display::button(
                 'like',
                 Display::returnFontAwesomeIcon('thumbs-down', '', true)
                 .PHP_EOL.'<span>'.$countLikes['dislikes'].'</span>',
                 [
                     'title' => get_lang('VoteDislike'),
-                    'class' => 'btn btn-default social-like '.($countLikes['user_disliked'] ? 'disabled' : ''),
+                    'class' => 'btn social-like '.$disabled,
                     'data-status' => 'dislike',
                     'data-message' => $messageId,
                     'data-group' => $groupId,
@@ -2797,11 +2921,11 @@ class MessageManager
         $sql = "SELECT COUNT(id) as count 
                 FROM $table
                 WHERE
-                    user_receiver_id=".$userId." AND
+                    user_receiver_id = $userId AND
                     msg_status = ".MESSAGE_STATUS_UNREAD;
         $result = Database::query($sql);
         $row = Database::fetch_assoc($result);
 
-        return $row['count'];
+        return (int) $row['count'];
     }
 }

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

@@ -147,7 +147,7 @@ class NotebookManager
      */
     public static function update_note($values)
     {
-        if (!is_array($values) or empty($values['note_title'])) {
+        if (!is_array($values) || empty($values['note_title'])) {
             return false;
         }
 

+ 10 - 2
main/inc/lib/notification.lib.php

@@ -491,9 +491,11 @@ class Notification extends Model
             return false;
         }
 
-        $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
         $content = strip_tags($content);
-        $content = html_entity_decode($content, ENT_QUOTES);
+        $content = explode("\n", $content);
+        $content = array_map('trim', $content);
+        $content = array_filter($content);
+        $content = implode(PHP_EOL, $content);
 
         $gcmRegistrationIds = [];
         foreach ($userIds as $userId) {
@@ -525,6 +527,12 @@ class Notification extends Model
                 'title' => $title,
                 'message' => $content,
             ],
+            'notification' => [
+                'title' => $title,
+                'body' => $content,
+            ],
+            'collapse_key' => get_lang('Messages'),
+            'sound' => true,
         ]);
 
         $ch = curl_init();

+ 9 - 11
main/inc/lib/social.lib.php

@@ -917,7 +917,7 @@ class SocialManager extends UserManager
         ];
 
         // get count unread message and total invitations
-        $count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
+        $count_unread_message = MessageManager::getCountNewMessagesFromDB(api_get_user_id());
         $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
 
         $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
@@ -1836,14 +1836,14 @@ class SocialManager extends UserManager
         }
 
         $formattedList .= '</div>';
-        $formattedList .= '<div class="mediapost-form">';
+        $formattedList .= '<div class="mediapost-form row">';
         $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
                 <div class="col-sm-9">
                 <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
                 <input type="hidden" name = "messageId" value="'.$messageId.'" />
                 <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
                 </div>
-                <div class="col-sm-3">
+                <div class="col-sm-3 pull-right">
                 <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
                     <em class="fa fa-pencil"></em> '.get_lang('Post').'
                 </a>
@@ -1950,7 +1950,7 @@ class SocialManager extends UserManager
                 }
             }
         } else {
-            $list = MessageManager::getAttachmentLinkList($messageId);
+            $list = MessageManager::getAttachmentLinkList($messageId, 0);
         }
 
         return $list;
@@ -2450,15 +2450,15 @@ class SocialManager extends UserManager
             null,
             [
                 'placeholder' => $socialWallPlaceholder,
-                'cols-size' => [1, 10, 1],
+                'cols-size' => [1, 12, 1],
                 'aria-label' => $socialWallPlaceholder,
             ]
         );
         $form->addHtml('<div class="form-group">');
-        $form->addHtml('<div class="col-sm-4 col-md-offset-1">');
+        $form->addHtml('<div class="col-sm-6">');
         $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
         $form->addHtml('</div>');
-        $form->addHtml('<div class="col-sm-6">');
+        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
         $form->addButtonSend(
             get_lang('Post'),
             'wall_post_button',
@@ -2468,9 +2468,8 @@ class SocialManager extends UserManager
                 'custom' => true,
             ]
         );
+        $form->addHtml('</div></div>');
         $form->addHtml('</div>');
-        $form->addHtml('</div>');
-
         $form->addHidden('url_content', '');
         $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
 
@@ -3310,8 +3309,7 @@ class SocialManager extends UserManager
 
         $postAttachment = self::getPostAttachment($message);
 
-        $html = '';
-        $html .= '<div class="top-mediapost" >';
+        $html = '<div class="top-mediapost" >';
         $html .= '<div class="pull-right btn-group btn-group-sm">';
 
         $html .= MessageManager::getLikesButton(

+ 1 - 1
main/inc/lib/sortable_table.class.php

@@ -707,7 +707,7 @@ class SortableTable extends HTML_Table
         foreach ($param as $key => &$value) {
             $result[] = '<input type="hidden" name="'.$key.'" value="'.$value.'"/>';
         }
-        $result[] = '<select name="'.$this->param_prefix.'per_page" onchange="javascript: this.form.submit();">';
+        $result[] = '<select style="width: auto;" class="form-control" name="'.$this->param_prefix.'per_page" onchange="javascript: this.form.submit();">';
         $list = [10, 20, 50, 100, 500, 1000];
 
         $rowList = api_get_configuration_value('table_row_list');

+ 3 - 0
main/inc/lib/userportal.lib.php

@@ -1004,6 +1004,9 @@ class IndexManager
      */
     public function return_course_block()
     {
+        if (api_get_configuration_value('hide_course_sidebar')) {
+            return '';
+        }
         $isHrm = api_is_drh();
         $show_create_link = false;
         $show_course_link = false;

+ 9 - 27
main/lp/learnpath.class.php

@@ -2249,9 +2249,6 @@ class learnpath
      */
     public function get_previous_index()
     {
-        if ($this->debug > 0) {
-            error_log('In learnpath::get_previous_index()', 0);
-        }
         $index = $this->index;
         if (isset($this->ordered_items[$index - 1])) {
             $index--;
@@ -2263,11 +2260,6 @@ class learnpath
                     return $this->index;
                 }
             }
-        } else {
-            // There is no previous item.
-            if ($this->debug > 2) {
-                error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
-            }
         }
 
         return $index;
@@ -2280,9 +2272,9 @@ class learnpath
      */
     public function get_previous_item_id()
     {
-        $new_index = $this->get_previous_index();
+        $index = $this->get_previous_index();
 
-        return $this->ordered_items[$new_index];
+        return $this->ordered_items[$index];
     }
 
     /**
@@ -6239,10 +6231,9 @@ class learnpath
                 Session::write('pathItem', $arrLP[$i]['path']);
             }
 
+            $oddClass = 'row_even';
             if (($i % 2) == 0) {
                 $oddClass = 'row_odd';
-            } else {
-                $oddClass = 'row_even';
             }
             $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
             $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
@@ -6295,6 +6286,7 @@ class learnpath
             $forumIcon = '';
             $previewIcon = '';
             $pluginCalendarIcon = '';
+            $orderIcons = '';
 
             $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
             $plugin = null;
@@ -6398,7 +6390,6 @@ class learnpath
                 if ($pluginCalendar) {
                     $pluginLink = $pluginUrl.
                         '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
-
                     $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
                     $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
                     if ($itemInfo && $itemInfo['value'] == 1) {
@@ -13483,6 +13474,9 @@ EOD;
     public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
     {
         $_course = api_get_course_info($course_code);
+        if (empty($_course)) {
+            return '';
+        }
         $course_id = $_course['real_id'];
         $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
         $learningPathId = (int) $learningPathId;
@@ -13533,7 +13527,7 @@ EOD;
                 $myrow = Database::fetch_array($result);
                 $output = $myrow['forum_name'];
                 break;
-            case TOOL_THREAD:  //=topics
+            case TOOL_THREAD:
                 $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
                 // Grabbing the title of the post.
                 $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
@@ -13543,26 +13537,17 @@ EOD;
                 break;
             case TOOL_POST:
                 $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
-                //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
                 $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
                 $result = Database::query($sql);
                 $post = Database::fetch_array($result);
                 $output = $post['post_title'];
                 break;
             case 'dir':
-                $title = $row_item['title'];
-                if (!empty($title)) {
-                    $output = $title;
-                } else {
-                    $output = '-';
-                }
-                break;
             case TOOL_DOCUMENT:
                 $title = $row_item['title'];
+                $output = '-';
                 if (!empty($title)) {
                     $output = $title;
-                } else {
-                    $output = '-';
                 }
                 break;
             case 'hotpotatoes':
@@ -13572,8 +13557,6 @@ EOD;
                 $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
                 $last = count($pathname) - 1; // Making a correct name for the link.
                 $filename = $pathname[$last]; // Making a correct name for the link.
-                $ext = explode('.', $filename);
-                $ext = strtolower($ext[sizeof($ext) - 1]);
                 $myrow['path'] = rawurlencode($myrow['path']);
                 $output = $filename;
                 break;
@@ -13598,7 +13581,6 @@ EOD;
 
         while ($parent) {
             $return[] = $parent->get_title();
-
             $parent = $this->getItem($parent->get_parent());
         }
 

+ 6 - 5
main/messages/download.php

@@ -14,6 +14,7 @@ session_cache_limiter('public');
 require_once __DIR__.'/../inc/global.inc.php';
 
 $file_url = isset($_GET['file']) ? $_GET['file'] : '';
+$type = isset($_GET['type']) ? $_GET['type'] : '';
 
 if (empty($file_url)) {
     api_not_allowed();
@@ -52,13 +53,13 @@ $current_uid = api_get_user_id();
 
 // get message user id for inbox/outbox
 $message_uid = '';
-$message_type = ['inbox', 'outbox'];
-if (in_array($_GET['type'], $message_type)) {
-    if ($_GET['type'] == 'inbox') {
+switch ($type) {
+    case MessageManager::MESSAGE_TYPE_INBOX:
         $message_uid = $row_users['user_receiver_id'];
-    } else {
+        break;
+    case MessageManager::MESSAGE_TYPE_OUTBOX:
         $message_uid = $row_users['user_sender_id'];
-    }
+        break;
 }
 
 // allow to the correct user for download this file

+ 1 - 83
main/messages/inbox.php

@@ -23,74 +23,6 @@ Event::registerLog($logInfo);
 $allowSocial = api_get_setting('allow_social_tool') == 'true';
 $allowMessage = api_get_setting('allow_message_tool') == 'true';
 
-if (isset($_GET['messages_page_nr'])) {
-    if ($allowSocial && $allowMessage) {
-        header('Location:inbox.php');
-        exit;
-    }
-}
-
-$nameTools = get_lang('Messages');
-$show_message = null;
-if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
-    $info_reply = [];
-    $info_delete = [];
-
-    if (isset($_GET['form_reply'])) {
-        //allow to insert messages
-        $info_reply = explode(base64_encode('&%ff..x'), $_GET['form_reply']);
-        $count_reply = count($info_reply);
-        $button_sent = urldecode($info_reply[4]);
-    }
-
-    if (isset($_GET['form_delete'])) {
-        //allow to delete messages
-        $info_delete = explode(',', $_GET['form_delete']);
-        $count_delete = (count($info_delete) - 1);
-    }
-
-    if (isset($button_sent)) {
-        $title = urldecode($info_reply[0]);
-        $content = str_replace("\\", '', urldecode($info_reply[1]));
-
-        $user_reply = $info_reply[2];
-        $user_email_base = str_replace(')', '(', $info_reply[5]);
-        $user_email_prepare = explode('(', $user_email_base);
-        if (count($user_email_prepare) == 1) {
-            $user_email = trim($user_email_prepare[0]);
-        } elseif (count($user_email_prepare) == 3) {
-            $user_email = trim($user_email_prepare[1]);
-        }
-        $user_id_by_email = MessageManager::get_user_id_by_email($user_email);
-
-        if ($info_reply[6] == 'save_form') {
-            $user_id_by_email = $info_reply[2];
-        }
-        if (isset($user_reply) && !is_null($user_id_by_email) && strlen($info_reply[0]) > 0) {
-            MessageManager::send_message($user_id_by_email, $title, $content);
-            $show_message .= MessageManager::return_message($user_id_by_email, 'confirmation');
-            $social_right_content .= MessageManager::inboxDisplay();
-            exit;
-        } elseif (is_null($user_id_by_email)) {
-            $message_box = get_lang('ErrorSendingMessage');
-            $show_message .= Display::return_message(api_xml_http_response_encode($message_box), 'error');
-            $social_right_content .= MessageManager::inboxDisplay();
-            exit;
-        }
-    } elseif (trim($info_delete[0]) == 'delete') {
-        for ($i = 1; $i <= $count_delete; $i++) {
-            MessageManager::delete_message_by_user_receiver(
-                api_get_user_id(),
-                $info_delete[$i]
-            );
-        }
-        $message_box = get_lang('SelectedMessagesDeleted');
-        $show_message .= Display::return_message(api_xml_http_response_encode($message_box));
-        $social_right_content .= MessageManager::inboxDisplay();
-        exit;
-    }
-}
-
 if ($allowSocial) {
     $this_section = SECTION_SOCIAL;
     $interbreadcrumb[] = [
@@ -147,21 +79,7 @@ if ($allowSocial) {
     $social_right_content .= Display::toolbarAction('toolbar', [$actionsLeft, $actionsRight]);
 }
 
-if (!isset($_GET['del_msg'])) {
-    $social_right_content .= MessageManager::inboxDisplay($keyword);
-} else {
-    $num_msg = (int) $_POST['total'];
-    for ($i = 0; $i < $num_msg; $i++) {
-        if ($_POST[$i]) {
-            // The user_id was necessary to delete a message??
-            $show_message .= MessageManager::delete_message_by_user_receiver(
-                api_get_user_id(),
-                $_POST['_'.$i]
-            );
-        }
-    }
-    $social_right_content .= MessageManager::inboxDisplay();
-}
+$social_right_content .= MessageManager::inboxDisplay($keyword);
 
 $tpl = new Template(null);
 

+ 1 - 1
main/messages/new_message.php

@@ -197,7 +197,7 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
     if (isset($_GET['forward_id'])) {
         $forwardId = (int) $_GET['forward_id'];
         $message_reply_info = MessageManager::get_message_by_id($forwardId);
-        $attachments = MessageManager::getAttachmentLinkList($forwardId);
+        $attachments = MessageManager::getAttachmentLinkList($forwardId, MessageManager::MESSAGE_TYPE_INBOX);
         if (!empty($attachments)) {
             $fileListToString = !empty($attachments) ? implode('<br />', $attachments) : '';
             $form->addLabel('', $fileListToString);

+ 2 - 31
main/messages/outbox.php

@@ -55,11 +55,6 @@ if ($allowMessage) {
         Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
 }
 
-$action = null;
-if (isset($_REQUEST['action'])) {
-    $action = $_REQUEST['action'];
-}
-
 $keyword = '';
 $social_right_content = '';
 if ($allowSocial) {
@@ -79,32 +74,8 @@ if ($allowSocial) {
         [$actionsLeft, $actionsRight]
     );
 }
-//MAIN CONTENT
-if ($action == 'delete') {
-    $delete_list_id = [];
-    if (isset($_POST['out'])) {
-        $delete_list_id = $_POST['out'];
-    }
-    if (isset($_POST['id'])) {
-        $delete_list_id = $_POST['id'];
-    }
-    for ($i = 0; $i < count($delete_list_id); $i++) {
-        MessageManager::delete_message_by_user_sender(
-            api_get_user_id(),
-            $delete_list_id[$i]
-        );
-    }
-    $delete_list_id = [];
-    $social_right_content .= MessageManager::outbox_display($keyword);
-} elseif ($action == 'deleteone') {
-    $delete_list_id = [];
-    $id = Security::remove_XSS($_GET['id']);
-    MessageManager::delete_message_by_user_sender(api_get_user_id(), $id);
-    $delete_list_id = [];
-    $social_right_content .= MessageManager::outbox_display($keyword);
-} else {
-    $social_right_content .= MessageManager::outbox_display($keyword);
-}
+
+$social_right_content .= MessageManager::outBoxDisplay($keyword);
 
 $tpl = new Template(get_lang('Outbox'));
 // Block Social Avatar

+ 16 - 14
main/messages/view_message.php

@@ -8,12 +8,18 @@ $cidReset = true;
 require_once __DIR__.'/../inc/global.inc.php';
 api_block_anonymous_users();
 
-if (api_get_setting('allow_message_tool') != 'true') {
+$allowSocial = api_get_setting('allow_social_tool') === 'true';
+$allowMessage = api_get_setting('allow_message_tool') === 'true';
+
+if (!$allowMessage) {
     api_not_allowed(true);
 }
 
-$allowSocial = api_get_setting('allow_social_tool') === 'true';
-$allowMessage = api_get_setting('allow_message_tool') === 'true';
+$messageId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
+
+if (empty($messageId)) {
+    api_not_allowed(true);
+}
 
 if ($allowSocial) {
     $this_section = SECTION_SOCIAL;
@@ -25,7 +31,7 @@ if ($allowSocial) {
 $interbreadcrumb[] = ['url' => 'inbox.php', 'name' => get_lang('Messages')];
 
 $social_right_content = '<div class="actions">';
-if (api_get_setting('allow_message_tool') === 'true') {
+if ($allowMessage) {
     $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
         Display::return_icon('new-message.png', get_lang('ComposeMessage')).'</a>';
     $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
@@ -34,22 +40,18 @@ if (api_get_setting('allow_message_tool') === 'true') {
         Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
 }
 $social_right_content .= '</div>';
+$type = isset($_GET['type']) ? (int) $_GET['type'] : MessageManager::MESSAGE_TYPE_INBOX;
 
-if (empty($_GET['id'])) {
-    $messageId = $_GET['id_send'];
-    $source = 'outbox';
+$show_menu = 'messages_inbox';
+if ($type === MessageManager::MESSAGE_TYPE_OUTBOX) {
     $show_menu = 'messages_outbox';
-} else {
-    $messageId = $_GET['id'];
-    $source = 'inbox';
-    $show_menu = 'messages_inbox';
 }
 
 $message = '';
-
 $logInfo = [
     'tool' => 'Messages',
-    'action' => $source,
+    'tool_id' => $messageId,
+    'action' => 'view-message',
     'action_details' => 'view-message',
 ];
 Event::registerLog($logInfo);
@@ -60,7 +62,7 @@ if (api_get_setting('allow_social_tool') === 'true') {
     $social_menu_block = SocialManager::show_social_menu($show_menu);
 }
 // MAIN CONTENT
-$message .= MessageManager::showMessageBox($messageId, $source);
+$message .= MessageManager::showMessageBox($messageId, $type);
 
 if (!empty($message)) {
     $social_right_content .= $message;

+ 1 - 1
main/mySpace/access_details_session.php

@@ -244,7 +244,7 @@ if ($form->validate()) {
         }
     }
 
-    $table = new HTML_Table(['class' => 'data_table']);
+    $table = new HTML_Table(['class' => 'data_table_pdf']);
     $headers = [
         get_lang('MinStartDate'),
         get_lang('MaxEndDate'),

+ 0 - 2
main/social/home.php

@@ -27,8 +27,6 @@ if (api_get_setting('allow_social_tool') !== 'true') {
     exit;
 }
 
-$userGroup = new UserGroup();
-
 //fast upload image
 if (api_get_setting('profile', 'picture') == 'true') {
     $form = new FormValidator('profile', 'post', 'home.php', null, []);

+ 1 - 41
main/social/promoted_messages.php

@@ -17,31 +17,6 @@ $logInfo = [
 ];
 Event::registerLog($logInfo);
 
-$nameTools = get_lang('Messages');
-$show_message = null;
-if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
-    $info_reply = [];
-    $info_delete = [];
-    if (isset($_GET['form_delete'])) {
-        //allow to delete messages
-        $info_delete = explode(',', $_GET['form_delete']);
-        $count_delete = (count($info_delete) - 1);
-    }
-
-    if (trim($info_delete[0]) === 'delete') {
-        for ($i = 1; $i <= $count_delete; $i++) {
-            MessageManager::delete_message_by_user_receiver(
-                api_get_user_id(),
-                $info_delete[$i]
-            );
-        }
-        $message_box = get_lang('SelectedMessagesDeleted');
-        $show_message .= Display::return_message(api_xml_http_response_encode($message_box));
-        $social_right_content .= MessageManager::inboxDisplay();
-        exit;
-    }
-}
-
 $this_section = SECTION_SOCIAL;
 $interbreadcrumb[] = [
     'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
@@ -68,22 +43,7 @@ if ($form->validate()) {
 }
 $actionsRight = $form->returnForm();
 $social_right_content .= Display::toolbarAction('toolbar', [$actionsLeft, $actionsRight]);
-
-if (!isset($_GET['del_msg'])) {
-    $social_right_content .= MessageManager::getPromotedMessagesGrid($keyword);
-} else {
-    $num_msg = (int) $_POST['total'];
-    for ($i = 0; $i < $num_msg; $i++) {
-        if ($_POST[$i]) {
-            // The user_id was necessary to delete a message??
-            $show_message .= MessageManager::delete_message_by_user_receiver(
-                api_get_user_id(),
-                $_POST['_'.$i]
-            );
-        }
-    }
-    $social_right_content .= MessageManager::getPromotedMessagesGrid();
-}
+$social_right_content .= MessageManager::getPromotedMessagesGrid($keyword);
 
 $tpl = new Template(null);
 // Block Social Avatar

+ 5 - 17
main/social/view_promoted_message.php

@@ -1,9 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
 
-/**
- * @package chamilo.messages
- */
 $cidReset = true;
 require_once __DIR__.'/../inc/global.inc.php';
 api_block_anonymous_users();
@@ -17,26 +14,17 @@ $interbreadcrumb[] = ['url' => api_get_path(WEB_PATH).'main/social/home.php', 'n
 $interbreadcrumb[] = ['url' => 'promoted_messages.php', 'name' => get_lang('PromotedMessages')];
 
 $social_right_content = '';
-if (empty($_GET['id'])) {
-    $messageId = $_GET['id_send'];
-    $source = 'outbox';
-    $show_menu = 'messages_outbox';
-} else {
-    $messageId = $_GET['id'];
-    $source = 'inbox';
-    $show_menu = 'messages_inbox';
-}
+$messageId = $_GET['id'];
 
 $message = '';
-
 $logInfo = [
     'tool' => 'Messages',
-    'action' => $source,
+    'action' => 'promoted_messages',
     'action_details' => 'view-message',
 ];
 Event::registerLog($logInfo);
-$social_menu_block = SocialManager::show_social_menu($show_menu);
-$message .= MessageManager::showMessageBox($messageId, 'promoted_messages');
+$social_menu_block = SocialManager::show_social_menu('inbox');
+$message .= MessageManager::showMessageBox($messageId, MessageManager::MESSAGE_TYPE_PROMOTED);
 
 if (!empty($message)) {
     $social_right_content .= $message;
@@ -45,7 +33,7 @@ if (!empty($message)) {
 }
 $tpl = new Template(get_lang('View'));
 // Block Social Avatar
-SocialManager::setSocialUserBlock($tpl, api_get_user_id(), $show_menu);
+SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'promoted_messages');
 
 $tpl->assign('social_menu_block', $social_menu_block);
 $tpl->assign('social_right_content', $social_right_content);

+ 10 - 10
main/user/subscribe_user.php

@@ -31,7 +31,7 @@ if (!api_is_allowed_to_edit()) {
 }
 
 $tool_name = get_lang('SubscribeUserToCourse');
-$type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : STUDENT;
+$type = isset($_REQUEST['type']) ? (int) $_REQUEST['type'] : STUDENT;
 $keyword = isset($_REQUEST['keyword']) ? Security::remove_XSS($_REQUEST['keyword']) : null;
 
 $courseInfo = api_get_course_info();
@@ -501,7 +501,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
                         field_values.field_id = '".intval($field_identification[0])."' AND
                         field_values.value = '".Database::escape_string($field_identification[1])."'";
             } else {
-                $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." ";
+                $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." ";
             }
 
             // adding a teacher NOT trough a session on a portal with multiple URLs
@@ -529,7 +529,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
                                 field_values.field_id = '".intval($field_identification[0])."' AND
                                 field_values.value = '".Database::escape_string($field_identification[1])."'";
                     } else {
-                        $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." AND access_url_id= $url_access_id ";
+                        $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." AND access_url_id= $url_access_id ";
                     }
                 }
             }
@@ -542,8 +542,8 @@ function get_user_data($from, $number_of_items, $column, $direction)
                     LEFT JOIN $tbl_session_rel_course_user cu
                     ON
                         u.user_id = cu.user_id AND
-                        c_id ='".$courseId."' AND
-                        session_id ='".$sessionId."' ";
+                        c_id = $courseId AND
+                        session_id = $sessionId ";
 
             if (api_is_multiple_url_enabled()) {
                 $sql .= " INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) ";
@@ -566,7 +566,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
             } else {
                 $sql .= "WHERE
                             cu.user_id IS NULL AND
-                            u.status<>".DRH." AND
+                            u.status <> ".DRH." AND
                             (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
             }
             if (api_is_multiple_url_enabled()) {
@@ -578,7 +578,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
                     LEFT JOIN $course_user_table cu
                     ON
                         u.user_id = cu.user_id AND
-                        c_id ='".$courseId."'";
+                        c_id = $courseId ";
 
             // applying the filter of the additional user profile fields
             if (isset($_GET['subscribe_user_filter_value']) && !empty($_GET['subscribe_user_filter_value'])) {
@@ -588,11 +588,11 @@ function get_user_data($from, $number_of_items, $column, $direction)
                         ON field_values.item_id = u.user_id
                     WHERE
                         cu.user_id IS NULL AND
-                        u.status<>".DRH." AND
+                        u.status <> ".DRH." AND
                         field_values.field_id = '".intval($field_identification[0])."' AND
                         field_values.value = '".Database::escape_string($field_identification[1])."'";
             } else {
-                $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." ";
+                $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." ";
             }
 
             //showing only the courses of the current Chamilo access_url_id
@@ -622,7 +622,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
                                 access_url_id = $url_access_id
                             ";
                     } else {
-                        $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." AND access_url_id= $url_access_id ";
+                        $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." AND access_url_id = $url_access_id ";
                     }
                 }
             }

+ 14 - 16
main/user/user.php

@@ -28,8 +28,6 @@ if (!api_is_platform_admin(true)) {
     }
 }
 
-/* Constants and variables */
-$course_code = api_get_course_id();
 $sessionId = api_get_session_id();
 $is_western_name_order = api_is_western_name_order();
 $sort_by_first_name = api_sort_by_first_name();
@@ -38,7 +36,7 @@ $user_id = api_get_user_id();
 $_user = api_get_user_info();
 $courseCode = $course_info['code'];
 $courseId = $course_info['real_id'];
-$type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : STUDENT;
+$type = isset($_REQUEST['type']) ? (int) $_REQUEST['type'] : STUDENT;
 $canEditUsers = api_get_setting('allow_user_course_subscription_by_course_admin') == 'true' || api_is_platform_admin();
 
 // Can't auto unregister from a session
@@ -109,7 +107,6 @@ if (isset($_GET['action'])) {
             if (!$canRead) {
                 api_not_allowed();
             }
-            $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
             $table_users = Database::get_main_table(TABLE_MAIN_USER);
             $is_western_name_order = api_is_western_name_order();
 
@@ -353,7 +350,7 @@ if (isset($_GET['action'])) {
                             $user[$key] = $extra_value;
                         }
                     }
-                    if ($_GET['format'] == 'pdf') {
+                    if ($_GET['format'] === 'pdf') {
                         $user_info = api_get_user_info($user['user_id']);
                         $user_image = '<img src="'.$user_info['avatar'].'" width ="'.$user_image_pdf_size.'px" />';
 
@@ -426,20 +423,20 @@ if (api_is_allowed_to_edit(null, true)) {
         if (isset($_GET['user_id']) && is_numeric($_GET['user_id']) &&
             ($_GET['user_id'] != $_user['user_id'] || api_is_platform_admin())
         ) {
-            $user_id = intval($_GET['user_id']);
+            $user_id = (int) $_GET['user_id'];
             $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
             $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
             $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 
-            $sql = 'SELECT user.user_id
-					FROM '.$tbl_user.' user
-					INNER JOIN '.$tbl_session_rel_user.' reluser
-					ON user.user_id = reluser.user_id AND reluser.relation_type<>'.SESSION_RELATION_TYPE_RRHH.'
-					INNER JOIN '.$tbl_session_rel_course.' rel_course
+            $sql = "SELECT user.user_id
+					FROM $tbl_user user
+					INNER JOIN $tbl_session_rel_user reluser
+					ON user.user_id = reluser.user_id AND reluser.relation_type <> ".SESSION_RELATION_TYPE_RRHH."
+					INNER JOIN $tbl_session_rel_course rel_course
 					ON rel_course.session_id = reluser.session_id
 					WHERE
-					    user.user_id = "'.$user_id.'" AND
-					    rel_course.c_id = "'.$courseId.'"';
+					    user.user_id = $user_id AND
+					    rel_course.c_id = $courseId ";
 
             $result = Database::query($sql);
             $row = Database::fetch_array($result, 'ASSOC');
@@ -558,7 +555,7 @@ if (api_is_allowed_to_edit(null, true)) {
 }
 
 /*	Header */
-if (isset($origin) && $origin == 'learnpath') {
+if (isset($origin) && $origin === 'learnpath') {
     Display::display_reduced_header();
 } else {
     if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
@@ -775,17 +772,18 @@ function get_user_data($from, $number_of_items, $column, $direction)
 {
     global $is_western_name_order;
     global $extraFields;
-    $canEditUsers = api_get_setting('allow_user_course_subscription_by_course_admin') == 'true' || api_is_platform_admin();
     $type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : STUDENT;
     $course_info = api_get_course_info();
     $sessionId = api_get_session_id();
     $course_code = $course_info['code'];
     $a_users = [];
     $limit = null;
+    $from = (int) $from;
+    $number_of_items = (int) $number_of_items;
 
     // limit
     if (!isset($_GET['keyword']) || empty($_GET['keyword'])) {
-        $limit = 'LIMIT '.intval($from).','.intval($number_of_items);
+        $limit = 'LIMIT '.$from.','.$number_of_items;
     }
 
     if (!in_array($direction, ['ASC', 'DESC'])) {