Browse Source

WIP add "promoted messages" for admin see BT#15933

Julio Montoya 5 years ago
parent
commit
a96e975819

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

@@ -20,12 +20,12 @@ switch ($action) {
 
         // Setting notifications
         $count_unread_message = 0;
-        if (api_get_setting('allow_message_tool') == 'true') {
+        if (api_get_setting('allow_message_tool') === 'true') {
             // get count unread message and total invitations
-            $count_unread_message = MessageManager::getNumberOfMessages(true);
+            $count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
         }
 
-        if (api_get_setting('allow_social_tool') == 'true') {
+        if (api_get_setting('allow_social_tool') === 'true') {
             $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(
                 $userId
             );

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

@@ -588,6 +588,7 @@ define('MESSAGE_STATUS_WALL_DELETE', '9');
 define('MESSAGE_STATUS_WALL_POST', '10');
 define('MESSAGE_STATUS_CONVERSATION', '11');
 define('MESSAGE_STATUS_FORUM', '12');
+define('MESSAGE_STATUS_PROMOTED', '13');
 
 // Images
 define('IMAGE_WALL_SMALL_SIZE', 200);

+ 220 - 149
main/inc/lib/message.lib.php

@@ -49,20 +49,22 @@ class MessageManager
     /**
      * Gets the total number of messages, used for the inbox sortable table.
      *
-     * @param bool $unread
+     * @param array $params
      *
      * @return int
      */
-    public static function getNumberOfMessages($unread = false)
+    public static function getNumberOfMessages($params = [])
     {
-        $table = Database::get_main_table(TABLE_MESSAGE);
-        if ($unread) {
-            $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
-        } else {
-            $condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
+        $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']) ? $params['keyword'] : '';
 
-        $keyword = Session::read('message_search_keyword');
         $keywordCondition = '';
         if (!empty($keyword)) {
             $keyword = Database::escape_string($keyword);
@@ -71,8 +73,9 @@ class MessageManager
 
         $sql = "SELECT COUNT(id) as number_messages
                 FROM $table
-                WHERE $condition_msg_status AND
-                    user_receiver_id=".api_get_user_id()."
+                WHERE 
+                    msg_status IN ('$messageStatusCondition') AND
+                    user_receiver_id = ".api_get_user_id()."
                     $keywordCondition
                 ";
         $result = Database::query($sql);
@@ -89,23 +92,23 @@ class MessageManager
      * Gets information about some messages, used for the inbox sortable table.
      *
      * @param int    $from
-     * @param int    $number_of_items
+     * @param int    $numberOfItems
      * @param string $column
      * @param string $direction
-     * @param int    $userId
+     * @param array  $extraParams
      *
      * @return array
      */
-    public static function get_message_data(
+    public static function getMessageData(
         $from,
-        $number_of_items,
+        $numberOfItems,
         $column,
         $direction,
-        $userId = 0
+        $extraParams = []
     ) {
         $from = (int) $from;
-        $number_of_items = (int) $number_of_items;
-        $userId = empty($userId) ? api_get_user_id() : (int) $userId;
+        $numberOfItems = (int) $numberOfItems;
+        $userId = api_get_user_id();
 
         // Forcing this order.
         if (!isset($direction)) {
@@ -122,13 +125,22 @@ class MessageManager
             $column = 2;
         }
 
-        $keyword = Session::read('message_search_keyword');
+        $keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
+        $viewUrl = isset($extraParams['view_url']) ? $extraParams['view_url'] : api_get_path(WEB_CODE_PATH).'message/view_message.php';
+
         $keywordCondition = '';
         if (!empty($keyword)) {
             $keyword = Database::escape_string($keyword);
             $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
         }
 
+        $messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
+        if (isset($extraParams['message_status']) && !empty($extraParams['message_status'])) {
+            $messageStatus = $extraParams['message_status'];
+        }
+        $messageStatus = array_map('intval', $messageStatus);
+        $messageStatusCondition = implode("','", $messageStatus);
+
         $table = Database::get_main_table(TABLE_MESSAGE);
         $sql = "SELECT 
                     id as col0, 
@@ -138,15 +150,18 @@ class MessageManager
                     user_sender_id
                 FROM $table
                 WHERE
-                    user_receiver_id=".$userId." AND
-                    msg_status IN (".MESSAGE_STATUS_NEW.", ".MESSAGE_STATUS_UNREAD.")
+                    user_receiver_id = $userId AND
+                    msg_status IN ('$messageStatusCondition')
                     $keywordCondition
                 ORDER BY col$column $direction
-                LIMIT $from, $number_of_items";
+                LIMIT $from, $numberOfItems";
 
         $result = Database::query($sql);
         $messageList = [];
         $newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
+
+        $actions = $extraParams['actions'];
+        $url = api_get_self();
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             $messageId = $row['col0'];
             $title = $row['col1'];
@@ -163,41 +178,65 @@ class MessageManager
             }
 
             $userInfo = api_get_user_info($senderId);
+            $message[3] = '';
             if (!empty($senderId) && !empty($userInfo)) {
-                $message[1] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a><br />';
+                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
                 $message[1] .= $userInfo['complete_name_with_username'];
-                $message[3] =
-                    Display::url(
-                        Display::returnFontAwesomeIcon('reply', 2),
-                        $newMessageLink.'?re_id='.$messageId,
-                        ['title' => get_lang('ReplyToMessage')]
-                    );
+                if (in_array('reply', $actions)) {
+                    $message[3] =
+                        Display::url(
+                            Display::returnFontAwesomeIcon('reply', 2),
+                            $newMessageLink.'?re_id='.$messageId,
+                            ['title' => get_lang('ReplyToMessage')]
+                        );
+                }
             } else {
-                $message[1] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a><br />';
+                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
                 $message[1] .= get_lang('UnknownUser');
-                $message[3] =
-                    Display::url(
-                        Display::returnFontAwesomeIcon('reply', 2),
-                        '#',
-                        ['title' => get_lang('ReplyToMessage')]
-                    );
+                if (in_array('reply', $actions)) {
+                    $message[3] =
+                        Display::url(
+                            Display::returnFontAwesomeIcon('reply', 2),
+                            '#',
+                            ['title' => get_lang('ReplyToMessage')]
+                        );
+                }
             }
 
             $message[0] = $messageId;
             $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
-            $message[3] .=
-                '&nbsp;&nbsp;'.
-                Display::url(
-                    Display::returnFontAwesomeIcon('share', 2),
-                    $newMessageLink.'?forward_id='.$messageId,
-                    ['title' => get_lang('ForwardMessage')]
-                ).
-                '&nbsp;&nbsp;<a title="'.addslashes(
+
+            // Actions
+            if (in_array('edit', $actions)) {
+                $message[3] .=
+                    '&nbsp;&nbsp;'.
+                    Display::url(
+                        Display::returnFontAwesomeIcon('pencil', 2),
+                        $newMessageLink.'?action=edit&id='.$messageId,
+                        ['title' => get_lang('ForwardMessage')]
+                    );
+            }
+
+            // Actions
+            if (in_array('forward', $actions)) {
+                $message[3] .=
+                    '&nbsp;&nbsp;'.
+                    Display::url(
+                        Display::returnFontAwesomeIcon('share', 2),
+                        $newMessageLink.'?forward_id='.$messageId,
+                        ['title' => get_lang('ForwardMessage')]
+                    );
+            }
+
+            if (in_array('delete', $actions)) {
+                $message[3] .= '&nbsp;&nbsp;<a title="'.addslashes(
                     get_lang('DeleteMessage')
                 ).'" onclick="javascript:if(!confirm('."'".addslashes(
                     api_htmlentities(get_lang('ConfirmDeleteMessage'))
-                )."'".')) return false;" href="inbox.php?action=deleteone&id='.$messageId.'">'.
+                )."'".')) return false;" href="'.$url.'?action=deleteone&id='.$messageId.'">'.
                 Display::returnFontAwesomeIcon('trash', 2).'</a>';
+            }
+
             foreach ($message as $key => $value) {
                 $message[$key] = api_xml_http_response_encode($value);
             }
@@ -388,7 +427,8 @@ class MessageManager
         $forwardId = 0,
         $smsParameters = [],
         $checkCurrentAudioId = false,
-        $forceTitleWhenSendingEmail = false
+        $forceTitleWhenSendingEmail = false,
+        $status = 0
     ) {
         $table = Database::get_main_table(TABLE_MESSAGE);
         $group_id = (int) $group_id;
@@ -397,6 +437,8 @@ class MessageManager
         $editMessageId = (int) $editMessageId;
         $topic_id = (int) $topic_id;
 
+        $status = empty($status) ? MESSAGE_STATUS_UNREAD : (int) $status;
+
         if (!empty($receiver_user_id)) {
             $receiverUserInfo = api_get_user_info($receiver_user_id);
 
@@ -490,7 +532,7 @@ class MessageManager
                 $params = [
                     'user_sender_id' => $user_sender_id,
                     'user_receiver_id' => $receiver_user_id,
-                    'msg_status' => MESSAGE_STATUS_UNREAD,
+                    'msg_status' => $status,
                     'send_date' => $now,
                     'title' => $subject,
                     'content' => $content,
@@ -537,8 +579,8 @@ class MessageManager
                 }
             }
 
-            if (empty($group_id)) {
-                // message in outbox for user friend or group
+            // Save message in the outbox for user friend or group.
+            if (empty($group_id) && $status == MESSAGE_STATUS_UNREAD) {
                 $params = [
                     'user_sender_id' => $user_sender_id,
                     'user_receiver_id' => $receiver_user_id,
@@ -762,30 +804,32 @@ class MessageManager
     public static function delete_message_by_user_receiver($user_receiver_id, $id)
     {
         $table = Database::get_main_table(TABLE_MESSAGE);
-        if ($id != strval(intval($id))) {
-            return false;
-        }
         $id = (int) $id;
         $user_receiver_id = (int) $user_receiver_id;
+
+        if (empty($id) || empty($user_receiver_id)) {
+            return false;
+        }
+
         $sql = "SELECT * FROM $table
-                WHERE id = ".$id." AND msg_status <>".MESSAGE_STATUS_OUTBOX;
+                WHERE id = $id AND msg_status <> ".MESSAGE_STATUS_OUTBOX;
         $rs = Database::query($sql);
 
         if (Database::num_rows($rs) > 0) {
-            // delete attachment file
+            // Delete attachment file.
             self::delete_message_attachment_file($id, $user_receiver_id);
-            // delete message
+            // Soft delete message.
             $query = "UPDATE $table 
                       SET msg_status = ".MESSAGE_STATUS_DELETED."
-                      WHERE 
-                        user_receiver_id=".$user_receiver_id." AND 
-                        id = ".$id;
+                      WHERE
+                        id = $id AND 
+                        user_receiver_id = $user_receiver_id ";
             Database::query($query);
 
             return true;
-        } else {
-            return false;
         }
+
+        return false;
     }
 
     /**
@@ -816,7 +860,7 @@ class MessageManager
             // delete attachment file
             self::delete_message_attachment_file($id, $user_sender_id);
             // delete message
-            $sql = "UPDATE $table 
+            $sql = "UPDATE $table
                     SET msg_status = ".MESSAGE_STATUS_DELETED."
                     WHERE user_sender_id='$user_sender_id' AND id='$id'";
             Database::query($sql);
@@ -932,12 +976,12 @@ class MessageManager
         $message_uid = (int) $message_uid;
         $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 
-        $sql = "SELECT * FROM $table_message_attach 
+        $sql = "SELECT * FROM $table_message_attach
                 WHERE message_id = '$message_id'";
         $rs = Database::query($sql);
         while ($row = Database::fetch_array($rs)) {
             $path = $row['path'];
-            $attach_id = $row['id'];
+            $attach_id = (int) $row['id'];
             $new_path = $path.'_DELETED_'.$attach_id;
 
             if (!empty($group_id)) {
@@ -957,8 +1001,9 @@ class MessageManager
             $path_message_attach = $path_user_info['dir'].'message_attachments/';
             if (is_file($path_message_attach.$path)) {
                 if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
-                    $sql = "UPDATE $table_message_attach set path='$new_path'
-                            WHERE id ='$attach_id'";
+                    $sql = "UPDATE $table_message_attach 
+                            SET path = '$new_path'
+                            WHERE id = $attach_id ";
                     Database::query($sql);
                 }
             }
@@ -1000,12 +1045,13 @@ class MessageManager
      */
     public static function get_messages_by_group($group_id)
     {
-        if ($group_id != strval(intval($group_id))) {
+        $group_id = (int) $group_id;
+
+        if (empty($group_id)) {
             return false;
         }
 
         $table = Database::get_main_table(TABLE_MESSAGE);
-        $group_id = intval($group_id);
         $sql = "SELECT * FROM $table
                 WHERE
                     group_id= $group_id AND
@@ -1032,11 +1078,13 @@ class MessageManager
      */
     public static function get_messages_by_group_by_message($group_id, $message_id)
     {
-        if ($group_id != strval(intval($group_id))) {
+        $group_id = (int) $group_id;
+
+        if (empty($group_id)) {
             return false;
         }
+
         $table = Database::get_main_table(TABLE_MESSAGE);
-        $group_id = intval($group_id);
         $sql = "SELECT * FROM $table
                 WHERE
                     group_id = $group_id AND
@@ -1094,7 +1142,7 @@ class MessageManager
         $sql = "SELECT * FROM $table
                 WHERE
                     parent_id='$parentId' AND
-                    msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")                    
+                    msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
                     $condition_group_id
                 ORDER BY send_date DESC $condition_limit ";
         $rs = Database::query($sql);
@@ -1120,12 +1168,13 @@ class MessageManager
      */
     public static function get_message_data_sent(
         $from,
-        $number_of_items,
+        $numberOfItems,
         $column,
-        $direction
+        $direction,
+        $extraParams = []
     ) {
         $from = (int) $from;
-        $number_of_items = (int) $number_of_items;
+        $numberOfItems = (int) $numberOfItems;
         if (!isset($direction)) {
             $column = 2;
             $direction = 'DESC';
@@ -1141,7 +1190,7 @@ class MessageManager
         }
         $table = Database::get_main_table(TABLE_MESSAGE);
         $request = api_is_xml_http_request();
-        $keyword = Session::read('message_sent_search_keyword');
+        $keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
         $keywordCondition = '';
         if (!empty($keyword)) {
             $keyword = Database::escape_string($keyword);
@@ -1149,10 +1198,10 @@ class MessageManager
         }
 
         $sql = "SELECT
-                    id as col0, 
-                    title as col1, 
-                    send_date as col2, 
-                    user_receiver_id, 
+                    id as col0,
+                    title as col1,
+                    send_date as col2,
+                    user_receiver_id,
                     msg_status,
                     user_sender_id
                 FROM $table
@@ -1161,7 +1210,7 @@ class MessageManager
                     msg_status = ".MESSAGE_STATUS_OUTBOX."
                     $keywordCondition
                 ORDER BY col$column $direction
-                LIMIT $from, $number_of_items";
+                LIMIT $from, $numberOfItems";
         $result = Database::query($sql);
 
         $message_list = [];
@@ -1211,38 +1260,6 @@ class MessageManager
         return $message_list;
     }
 
-    /**
-     * Gets information about number messages sent.
-     *
-     * @author Isaac FLores Paz <isaac.flores@dokeos.com>
-     *
-     * @param void
-     *
-     * @return int
-     */
-    public static function getNumberOfMessagesSent()
-    {
-        $table = Database::get_main_table(TABLE_MESSAGE);
-        $keyword = Session::read('message_sent_search_keyword');
-        $keywordCondition = '';
-        if (!empty($keyword)) {
-            $keyword = Database::escape_string($keyword);
-            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
-        }
-
-        $sql = "SELECT COUNT(id) as number_messages 
-                FROM $table
-                WHERE
-                  msg_status = ".MESSAGE_STATUS_OUTBOX." AND
-                  user_sender_id = ".api_get_user_id()."
-                  $keywordCondition
-                ";
-        $result = Database::query($sql);
-        $result = Database::fetch_array($result);
-
-        return $result['number_messages'];
-    }
-
     /**
      * display message box in the inbox.
      *
@@ -1259,7 +1276,7 @@ class MessageManager
         $messageId = (int) $messageId;
         $currentUserId = api_get_user_id();
 
-        if ($source == 'outbox') {
+        if ($source === 'outbox') {
             if (isset($messageId) && is_numeric($messageId)) {
                 $query = "SELECT * FROM $table
                           WHERE
@@ -1326,7 +1343,7 @@ class MessageManager
         $message_content .= '<tr>';
         if (api_get_setting('allow_social_tool') === 'true') {
             $message_content .= '<div class="row">';
-            if ($source == 'outbox') {
+            if ($source === 'outbox') {
                 $message_content .= '<div class="col-md-12">';
                 $message_content .= '<ul class="list-message">';
                 $message_content .= '<li>'.$userImage.'</li>';
@@ -1354,14 +1371,16 @@ class MessageManager
                     $message_content .= '<li>'.$name;
                 }
 
-                $message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
+                if ($source === 'inbox') {
+                    $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>';
             }
             $message_content .= '</div>';
         } else {
-            if ($source == 'outbox') {
+            if ($source === 'outbox') {
                 $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
                     $receiverUserInfo['complete_name_with_username'].'</b>';
             } else {
@@ -1370,7 +1389,7 @@ class MessageManager
             }
         }
 
-        $message_content .= '		        
+        $message_content .= '
 		        <hr style="color:#ddd" />
 		        <table width="100%">
 		            <tr>
@@ -1383,17 +1402,21 @@ class MessageManager
         if (isset($_GET['f']) && $_GET['f'] == 'social') {
             $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';
-        } else {
+        } 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';
         }
-        $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
-            Display::return_icon('delete.png', get_lang('DeleteMessage')).'</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';
+        }
 
         $message_content .= '</div></td>
 		      <td width=10></td>
@@ -1413,7 +1436,7 @@ class MessageManager
     public static function get_user_id_by_email($user_email)
     {
         $table = Database::get_main_table(TABLE_MAIN_USER);
-        $sql = 'SELECT user_id 
+        $sql = 'SELECT user_id
                 FROM '.$table.'
                 WHERE email="'.Database::escape_string($user_email).'";';
         $rs = Database::query($sql);
@@ -2061,27 +2084,32 @@ class MessageManager
     }
 
     /**
-     * @param string $keyword
+     * @param string $statusList
+     * @param array  $keyword
+     * @param array  $actions
+     * @param string $viewUrl
      *
      * @return string
      */
-    public static function inbox_display($keyword = '')
+    public static function getMessageGrid($statusList, $keyword, $actions = [], $viewUrl = '')
     {
+        if (empty($statusList)) {
+            return '';
+        }
         $success = get_lang('SelectedMessagesDeleted');
         $success_read = get_lang('SelectedMessagesRead');
         $success_unread = get_lang('SelectedMessagesUnRead');
+        $currentUserId = api_get_user_id();
         $html = '';
 
-        Session::write('message_search_keyword', $keyword);
-
         if (isset($_REQUEST['action'])) {
             switch ($_REQUEST['action']) {
                 case 'mark_as_unread':
                     if (is_array($_POST['id'])) {
-                        foreach ($_POST['id'] as $index => $message_id) {
+                        foreach ($_POST['id'] as $index => $messageId) {
                             self::update_message_status(
-                                api_get_user_id(),
-                                $message_id,
+                                $currentUserId,
+                                $messageId,
                                 MESSAGE_STATUS_UNREAD
                             );
                         }
@@ -2094,10 +2122,10 @@ class MessageManager
                     break;
                 case 'mark_as_read':
                     if (is_array($_POST['id'])) {
-                        foreach ($_POST['id'] as $index => $message_id) {
+                        foreach ($_POST['id'] as $index => $messageId) {
                             self::update_message_status(
-                                api_get_user_id(),
-                                $message_id,
+                                $currentUserId,
+                                $messageId,
                                 MESSAGE_STATUS_NEW
                             );
                         }
@@ -2109,8 +2137,8 @@ class MessageManager
                     );
                     break;
                 case 'delete':
-                    foreach ($_POST['id'] as $index => $message_id) {
-                        self::delete_message_by_user_receiver(api_get_user_id(), $message_id);
+                    foreach ($_POST['id'] as $index => $messageId) {
+                        self::delete_message_by_user_receiver($currentUserId, $messageId);
                     }
                     $html .= Display::return_message(
                         api_xml_http_response_encode($success),
@@ -2119,7 +2147,7 @@ class MessageManager
                     );
                     break;
                 case 'deleteone':
-                    self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
+                    self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
                     $html .= Display::return_message(
                         api_xml_http_response_encode($success),
                         'confirmation',
@@ -2133,30 +2161,72 @@ class MessageManager
         $table = new SortableTable(
             'message_inbox',
             ['MessageManager', 'getNumberOfMessages'],
-            ['MessageManager', 'get_message_data'],
+            ['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') {
+        if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
             $parameters['f'] = 'social';
             $table->set_additional_parameters($parameters);
         }
-        $table->set_form_actions(
-            [
-                'delete' => get_lang('DeleteSelectedMessages'),
-                'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
-                'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
-            ]
-        );
+
+        $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();
 
-        Session::erase('message_search_keyword');
+        return $html;
+    }
+
+    /**
+     * @param string $keyword
+     *
+     * @return string
+     */
+    public static function inboxDisplay($keyword = '')
+    {
+        $actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
+        $html = self::getMessageGrid([MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD], $keyword, $actions);
+
+        return $html;
+    }
+
+    /**
+     * @param string $keyword
+     *
+     * @return string
+     */
+    public static function getPromotedMessagesGrid($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);
 
         return $html;
     }
@@ -2176,12 +2246,12 @@ class MessageManager
         if (isset($_REQUEST['action'])) {
             switch ($_REQUEST['action']) {
                 case 'delete':
-                    $number_of_selected_messages = count($_POST['id']);
-                    if ($number_of_selected_messages != 0) {
-                        foreach ($_POST['id'] as $index => $message_id) {
+                    $count = count($_POST['id']);
+                    if ($count != 0) {
+                        foreach ($_POST['id'] as $index => $messageId) {
                             self::delete_message_by_user_receiver(
                                 api_get_user_id(),
-                                $message_id
+                                $messageId
                             );
                         }
                     }
@@ -2198,12 +2268,15 @@ class MessageManager
         // display sortable table with messages of the current user
         $table = new SortableTable(
             'message_outbox',
-            ['MessageManager', 'getNumberOfMessagesSent'],
+            ['MessageManager', 'getNumberOfMessages'],
             ['MessageManager', 'get_message_data_sent'],
             2,
             20,
             'DESC'
         );
+        $table->setDataFunctionParams(
+            ['keyword' => $keyword, 'message_status' => [MESSAGE_STATUS_OUTBOX]]
+        );
 
         $table->set_header(0, '', false, ['style' => 'width:15px;']);
         $table->set_header(1, get_lang('Messages'), false);
@@ -2213,8 +2286,6 @@ class MessageManager
         $table->set_form_actions(['delete' => get_lang('DeleteSelectedMessages')]);
         $html .= $table->return_table();
 
-        Session::erase('message_sent_search_keyword');
-
         return $html;
     }
 

+ 37 - 44
main/inc/lib/social.lib.php

@@ -1,6 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 
+use Chamilo\CourseBundle\Entity\CForumPost;
+use Chamilo\CourseBundle\Entity\CForumThread;
 use ChamiloSession as Session;
 use Zend\Feed\Reader\Entry\Rss;
 use Zend\Feed\Reader\Reader;
@@ -561,25 +563,6 @@ class SocialManager extends UserManager
         return true;
     }
 
-    /**
-     * Allow attaching to group.
-     *
-     * @author Isaac Flores Paz
-     *
-     * @param int $id_friend_qualify User to qualify
-     * @param int $type_qualify      Kind of rating
-     *
-     * @deprecated 2017-03
-     */
-    public static function qualify_friend($id_friend_qualify, $type_qualify)
-    {
-        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
-        $user_id = api_get_user_id();
-        $sql = 'UPDATE '.$table.' SET relation_type='.((int) $type_qualify).'
-                WHERE user_id = '.$user_id.' AND friend_user_id='.(int) $id_friend_qualify;
-        Database::query($sql);
-    }
-
     /**
      * Get user's feeds.
      *
@@ -934,7 +917,7 @@ class SocialManager extends UserManager
         ];
 
         // get count unread message and total invitations
-        $count_unread_message = MessageManager::getNumberOfMessages(true);
+        $count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
         $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());
@@ -981,7 +964,7 @@ class SocialManager extends UserManager
                         '.$homeIcon.' '.get_lang('Home').'
                     </a>
                 </li>';
-            $active = $show == 'messages' ? 'active' : null;
+            $active = $show === 'messages' ? 'active' : null;
             $links .= '
                 <li class="messages-icon '.$active.'">
                     <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
@@ -990,7 +973,7 @@ class SocialManager extends UserManager
                 </li>';
 
             // Invitations
-            $active = $show == 'invitations' ? 'active' : null;
+            $active = $show === 'invitations' ? 'active' : null;
             $links .= '
                 <li class="invitations-icon '.$active.'">
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
@@ -999,14 +982,14 @@ class SocialManager extends UserManager
                 </li>';
 
             // Shared profile and groups
-            $active = $show == 'shared_profile' ? 'active' : null;
+            $active = $show === 'shared_profile' ? 'active' : null;
             $links .= '
                 <li class="shared-profile-icon'.$active.'">
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
                         '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
                     </a>
                 </li>';
-            $active = $show == 'friends' ? 'active' : null;
+            $active = $show === 'friends' ? 'active' : null;
             $links .= '
                 <li class="friends-icon '.$active.'">
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
@@ -1022,7 +1005,7 @@ class SocialManager extends UserManager
                 </li>';
 
             // Search users
-            $active = $show == 'search' ? 'active' : null;
+            $active = $show === 'search' ? 'active' : null;
             $links .= '
                 <li class="search-icon '.$active.'">
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
@@ -1031,7 +1014,7 @@ class SocialManager extends UserManager
                 </li>';
 
             // My files
-            $active = $show == 'myfiles' ? 'active' : null;
+            $active = $show === 'myfiles' ? 'active' : null;
 
             $myFiles = '
                 <li class="myfiles-icon '.$active.'">
@@ -1046,7 +1029,7 @@ class SocialManager extends UserManager
             $links .= $myFiles;
             if (api_get_configuration_value('allow_portfolio_tool')) {
                 $links .= '
-                    <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
+                    <li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
                         <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
                             '.$portfolioIcon.' '.get_lang('Portfolio').'
                         </a>
@@ -1055,7 +1038,7 @@ class SocialManager extends UserManager
             }
 
             if (!api_get_configuration_value('disable_gdpr')) {
-                $active = $show == 'personal-data' ? 'active' : null;
+                $active = $show === 'personal-data' ? 'active' : null;
                 $personalData = '
                     <li class="personal-data-icon '.$active.'">
                         <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
@@ -1063,10 +1046,19 @@ class SocialManager extends UserManager
                         </a>
                     </li>';
                 $links .= $personalData;
-
-                $links .= '</ul>';
             }
 
+            if (api_is_platform_admin()) {
+                $active = $show === 'promoted_messages' ? 'active' : null;
+                $personalData = '
+                    <li class="personal-data-icon '.$active.'">
+                        <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
+                            '.$personalDataIcon.' '.get_lang('PromotedMessages').'
+                        </a>
+                    </li>';
+                $links .= $personalData;
+            }
+            $links .= '</ul>';
             $html .= Display::panelCollapse(
                 get_lang('SocialNetwork'),
                 $links,
@@ -1077,7 +1069,7 @@ class SocialManager extends UserManager
             );
         }
 
-        if (in_array($show, $show_groups) && !empty($group_id)) {
+        if (!empty($group_id) && in_array($show, $show_groups)) {
             $html .= $usergroup->show_group_column_information(
                 $group_id,
                 api_get_user_id(),
@@ -1206,10 +1198,10 @@ class SocialManager extends UserManager
             }
 
             // Check if I already sent an invitation message
-            $invitation_sent_list = self::get_list_invitation_sent_by_user_id(api_get_user_id());
+            $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
 
-            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
-                count($invitation_sent_list[$user_id]) > 0
+            if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
+                count($invitationSentList[$user_id]) > 0
             ) {
                 $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
                     Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
@@ -1647,7 +1639,6 @@ class SocialManager extends UserManager
         $userId = (int) $userId;
         $start = (int) $start;
         $length = (int) $length;
-        $startDate = Database::escape_string($startDate);
 
         $select = " SELECT
                     id,
@@ -1668,20 +1659,23 @@ class SocialManager extends UserManager
         }
 
         $sql = "$select                    
-                    FROM $tblMessage tm
+                    FROM $tblMessage m
                 WHERE
                     msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
 
-        // My own posts
+        // Get my own posts
         $userReceiverCondition = ' (
             user_receiver_id = '.$userId.' AND 
             msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
             parent_id = '.$parentId.'
         )';
 
-        // User condition
         $sql .= $userReceiverCondition;
 
+        $sql .= ' OR (
+            msg_status IN ('.MESSAGE_STATUS_PROMOTED.')             
+        ) ';
+
         // Get my group posts
         $groupCondition = '';
         if (!empty($groupId)) {
@@ -1696,8 +1690,8 @@ class SocialManager extends UserManager
             $groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
         }
 
-        $friendCondition = '';
         // Get my friend posts
+        $friendCondition = '';
         if (!empty($friendId)) {
             if (is_array($friendId)) {
                 $friendId = array_map('intval', $friendId);
@@ -1730,7 +1724,7 @@ class SocialManager extends UserManager
                                 forum_id,
                                 thread_id,
                                 c_id                            
-        ";
+                            ";
             }
 
             $threadList = array_map('intval', $threadList);
@@ -1762,7 +1756,6 @@ class SocialManager extends UserManager
             $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
             $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
             $groups = [];
-            $forums = [];
             $userGroup = new UserGroup();
             $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
             while ($row = Database::fetch_array($res, 'ASSOC')) {
@@ -1778,14 +1771,14 @@ class SocialManager extends UserManager
                     }
                 }
 
-                // forums
+                // Forums
                 $row['post_title'] = '';
                 $row['forum_title'] = '';
                 $row['thread_url'] = '';
                 if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
-                    /** @var \Chamilo\CourseBundle\Entity\CForumPost $post */
+                    /** @var CForumPost $post */
                     $post = $repo->find($row['id']);
-                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
+                    /** @var CForumThread $thread */
                     $thread = $repoThread->find($row['thread_id']);
                     if ($post && $thread) {
                         $courseInfo = api_get_course_info_by_id($post->getCId());

+ 31 - 7
main/inc/lib/sortable_table.class.php

@@ -96,10 +96,10 @@ class SortableTable extends HTML_Table
     public $table_id = null;
     public $headers = [];
     /**
-     * @var array
-     *            Columns to hide
+     * @var array Columns to hide
      */
     private $columnsToHide = [];
+    private $dataFunctionParams;
 
     /**
      * Create a new SortableTable.
@@ -204,6 +204,27 @@ class SortableTable extends HTML_Table
         $this->td_attributes = [];
         $this->th_attributes = [];
         $this->other_tables = [];
+        $this->dataFunctionParams = [];
+    }
+
+    /**
+     * @return array
+     */
+    public function getDataFunctionParams()
+    {
+        return $this->dataFunctionParams;
+    }
+
+    /**
+     * @param array $dataFunctionParams
+     *
+     * @return $this
+     */
+    public function setDataFunctionParams($dataFunctionParams)
+    {
+        $this->dataFunctionParams = $dataFunctionParams;
+
+        return $this;
     }
 
     /**
@@ -739,7 +760,6 @@ class SortableTable extends HTML_Table
     public function processHeaders()
     {
         $counter = 0;
-
         foreach ($this->headers as $column => $columnInfo) {
             $label = $columnInfo['label'];
             $sortable = $columnInfo['sortable'];
@@ -987,7 +1007,10 @@ class SortableTable extends HTML_Table
     public function get_total_number_of_items()
     {
         if ($this->total_number_of_items == -1 && !is_null($this->get_total_number_function)) {
-            $this->total_number_of_items = call_user_func($this->get_total_number_function);
+            $this->total_number_of_items = call_user_func(
+                $this->get_total_number_function,
+                $this->getDataFunctionParams()
+            );
         }
 
         return $this->total_number_of_items;
@@ -1024,13 +1047,14 @@ class SortableTable extends HTML_Table
         $sort = null
     ) {
         $data = [];
-        if (!is_null($this->get_data_function)) {
+        if ($this->get_data_function !== null) {
             $data = call_user_func(
                 $this->get_data_function,
                 $from,
                 $this->per_page,
                 $this->column,
-                $this->direction
+                $this->direction,
+                $this->dataFunctionParams
             );
         }
 
@@ -1096,7 +1120,7 @@ class SortableTableFromArray extends SortableTable
             $content = TableSort::sort_table(
                 $this->table_data,
                 $this->column,
-                $this->direction == 'ASC' ? SORT_ASC : SORT_DESC
+                $this->direction === 'ASC' ? SORT_ASC : SORT_DESC
             );
         } else {
             $content = $this->table_data;

+ 7 - 8
main/messages/inbox.php

@@ -51,7 +51,7 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
 
     if (isset($button_sent)) {
         $title = urldecode($info_reply[0]);
-        $content = str_replace("\\", "", urldecode($info_reply[1]));
+        $content = str_replace("\\", '', urldecode($info_reply[1]));
 
         $user_reply = $info_reply[2];
         $user_email_base = str_replace(')', '(', $info_reply[5]);
@@ -69,12 +69,12 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
         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::inbox_display();
+            $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::inbox_display();
+            $social_right_content .= MessageManager::inboxDisplay();
             exit;
         }
     } elseif (trim($info_delete[0]) == 'delete') {
@@ -86,7 +86,7 @@ if (isset($_GET['form_reply']) || isset($_GET['form_delete'])) {
         }
         $message_box = get_lang('SelectedMessagesDeleted');
         $show_message .= Display::return_message(api_xml_http_response_encode($message_box));
-        $social_right_content .= MessageManager::inbox_display();
+        $social_right_content .= MessageManager::inboxDisplay();
         exit;
     }
 }
@@ -112,7 +112,6 @@ $interbreadcrumb[] = [
 $interbreadcrumb[] = ['url' => '#', 'name' => get_lang('Inbox')];
 
 $actions = '';
-
 // Comes from normal profile
 if ($allowSocial === false && $allowMessage) {
     $actions .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
@@ -149,7 +148,7 @@ if ($allowSocial) {
 }
 
 if (!isset($_GET['del_msg'])) {
-    $social_right_content .= MessageManager::inbox_display($keyword);
+    $social_right_content .= MessageManager::inboxDisplay($keyword);
 } else {
     $num_msg = (int) $_POST['total'];
     for ($i = 0; $i < $num_msg; $i++) {
@@ -161,7 +160,7 @@ if (!isset($_GET['del_msg'])) {
             );
         }
     }
-    $social_right_content .= MessageManager::inbox_display();
+    $social_right_content .= MessageManager::inboxDisplay();
 }
 
 $tpl = new Template(null);
@@ -171,7 +170,7 @@ if ($actions) {
 }
 // Block Social Avatar
 SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
-if (api_get_setting('allow_social_tool') == 'true') {
+if ($allowSocial) {
     $tpl->assign('social_menu_block', $social_menu_block);
     $tpl->assign('social_right_content', $social_right_content);
     $social_layout = $tpl->get_template('social/inbox.tpl');

+ 11 - 14
main/messages/new_message.php

@@ -24,14 +24,12 @@ if (api_get_setting('allow_message_tool') !== 'true') {
 
 $logInfo = [
     'tool' => 'Messages',
-    'tool_id' => 0,
-    'tool_id_detail' => 0,
     'action' => 'new_message',
     'action_details' => isset($_GET['re_id']) ? 're_id' : '',
 ];
 Event::registerLog($logInfo);
 
-$allowSocial = api_get_setting('allow_social_tool') == 'true';
+$allowSocial = api_get_setting('allow_social_tool') === 'true';
 $nameTools = api_xml_http_response_encode(get_lang('Messages'));
 
 $htmlHeadXtra[] = '<script>
@@ -59,7 +57,6 @@ function add_image_form() {
 }
 </script>';
 $nameTools = get_lang('ComposeMessage');
-
 $tpl = new Template(get_lang('ComposeMessage'));
 
 /**
@@ -315,7 +312,7 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
             }
         }
         Security::clear_token();
-        header('Location: '.api_get_path(WEB_PATH).'main/messages/inbox.php');
+        header('Location: '.api_get_path(WEB_CODE_PATH).'messages/inbox.php');
         exit;
     } else {
         $token = Security::get_token();
@@ -330,19 +327,19 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
 if ($allowSocial) {
     $this_section = SECTION_SOCIAL;
     $interbreadcrumb[] = [
-        'url' => api_get_path(WEB_PATH).'main/social/home.php',
+        'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
         'name' => get_lang('SocialNetwork'),
     ];
 } else {
     $this_section = SECTION_MYPROFILE;
     $interbreadcrumb[] = [
-        'url' => api_get_path(WEB_PATH).'main/auth/profile.php',
+        'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
         'name' => get_lang('Profile'),
     ];
 }
 
 $interbreadcrumb[] = [
-    'url' => api_get_path(WEB_PATH).'main/messages/inbox.php',
+    'url' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
     'name' => get_lang('Messages'),
 ];
 
@@ -350,9 +347,9 @@ $group_id = isset($_REQUEST['group_id']) ? (int) $_REQUEST['group_id'] : 0;
 $social_right_content = null;
 if ($group_id != 0) {
     $social_right_content .= '<div class=actions>';
-    $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/social/group_view.php?id='.$group_id.'">'.
+    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'social/group_view.php?id='.$group_id.'">'.
         Display::return_icon('back.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
-    $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php?group_id='.$group_id.'">'.
+    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php?group_id='.$group_id.'">'.
         Display::return_icon('message_new.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
     $social_right_content .= '</div>';
 } else {
@@ -360,11 +357,11 @@ if ($group_id != 0) {
     } else {
         $social_right_content .= '<div class=actions>';
         if (api_get_setting('allow_message_tool') === 'true') {
-            $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
+            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php">'.
                 Display::return_icon('message_new.png', get_lang('ComposeMessage')).'</a>';
-            $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
+            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
                 Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
-            $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
+            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/outbox.php">'.
                 Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
         }
         $social_right_content .= '</div>';
@@ -379,7 +376,7 @@ if ($allowSocial) {
     $social_right_content .= '<div class="row">';
     $social_right_content .= '<div class="col-md-12">';
     $social_right_content .= '<div class="actions">';
-    $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
+    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
         Display::return_icon('back.png', get_lang('Back'), [], 32).'</a>';
     $social_right_content .= '</div>';
     $social_right_content .= '</div>';

+ 1 - 1
main/social/download.php

@@ -41,7 +41,7 @@ if (!empty($messageInfo['group_id'])) {
 }
 
 // Only process wall messages
-if (!in_array($messageInfo['msg_status'], [MESSAGE_STATUS_WALL, MESSAGE_STATUS_WALL_POST])) {
+if (!in_array($messageInfo['msg_status'], [MESSAGE_STATUS_WALL, MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
     api_not_allowed();
 }
 

+ 4 - 5
main/social/home.php

@@ -84,14 +84,13 @@ if (!empty($threadList)) {
     $threadIdList = array_column($threadList, 'id');
 }
 
-// Social Post Wall
 $posts = SocialManager::getMyWallMessages($user_id, 0, 10, $threadIdList);
 $countPost = $posts['count'];
 $posts = $posts['posts'];
 SocialManager::getScrollJs($countPost, $htmlHeadXtra);
 
 // Block Menu
-$social_menu_block = SocialManager::show_social_menu('home');
+$menu = SocialManager::show_social_menu('home');
 
 $social_search_block = Display::panel(
     UserManager::get_search_form(''),
@@ -140,9 +139,9 @@ $htmlHeadXtra[] = SocialManager::getScriptToGetOpenGraph();
 
 $tpl = new Template(get_lang('SocialNetwork'));
 SocialManager::setSocialUserBlock($tpl, $user_id, 'home');
-$tpl->assign('social_wall_block', $wallSocialAddPost);
-$tpl->assign('social_post_wall_block', $posts);
-$tpl->assign('social_menu_block', $social_menu_block);
+$tpl->assign('add_post_form', $wallSocialAddPost);
+$tpl->assign('posts', $posts);
+$tpl->assign('social_menu_block', $menu);
 $tpl->assign('social_auto_extend_link', $socialAutoExtendLink);
 $tpl->assign('search_friends_form', $formSearch->returnForm());
 $tpl->assign('social_friend_block', $friend_html);

+ 266 - 0
main/social/new_promoted_message.php

@@ -0,0 +1,266 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+$cidReset = true;
+require_once __DIR__.'/../inc/global.inc.php';
+
+api_protect_admin_script();
+
+if (api_get_setting('allow_social_tool') !== 'true') {
+    api_not_allowed(true);
+}
+
+$logInfo = [
+    'tool' => 'Messages',
+    'action' => 'add_new_promoted_message',
+];
+Event::registerLog($logInfo);
+
+$allowSocial = api_get_setting('allow_social_tool') === 'true';
+$nameTools = api_xml_http_response_encode(get_lang('Messages'));
+
+$htmlHeadXtra[] = '<script>
+var counter_image = 1;
+function add_image_form() {
+    // Multiple filepaths for image form
+    var filepaths = document.getElementById("file_uploads");
+    if (document.getElementById("filepath_"+counter_image)) {
+        counter_image = counter_image + 1;
+    }  else {
+        counter_image = counter_image;
+    }
+    var elem1 = document.createElement("div");
+    elem1.setAttribute("id","filepath_"+counter_image);
+    filepaths.appendChild(elem1);
+    id_elem1 = "filepath_"+counter_image;
+    id_elem1 = "\'"+id_elem1+"\'";
+    document.getElementById("filepath_"+counter_image).innerHTML = "<div class=\"form-group\" ><label class=\"col-sm-4\">'.get_lang('FilesAttachment').'</label><input class=\"col-sm-8\" type=\"file\" name=\"attach_"+counter_image+"\" /></div><div class=\"form-group\" ><label class=\"col-sm-4\">'.get_lang('Description').'</label><div class=\"col-sm-8\"><input style=\"width:100%\" type=\"text\" name=\"legend[]\" /></div></div>";
+    if (filepaths.childNodes.length == 6) {
+        var link_attach = document.getElementById("link-more-attach");
+        if (link_attach) {
+            link_attach.innerHTML="";
+        }
+    }
+}
+</script>';
+$nameTools = get_lang('ComposeMessage');
+$tpl = new Template(get_lang('ComposeMessage'));
+
+/**
+ * Shows the compose area + a list of users to select from.
+ */
+function show_compose_to_any($tpl)
+{
+    $default['user_list'] = 0;
+    $html = manageForm($default, null, null, $tpl);
+
+    return $html;
+}
+
+function show_compose_reply_to_message($message_id, $receiver_id, $tpl)
+{
+    $table = Database::get_main_table(TABLE_MESSAGE);
+    $receiver_id = (int) $receiver_id;
+    $message_id = (int) $message_id;
+
+    $query = "SELECT user_sender_id
+              FROM $table
+              WHERE user_receiver_id = ".$receiver_id." AND id = ".$message_id;
+    $result = Database::query($query);
+    $row = Database::fetch_array($result, 'ASSOC');
+    $userInfo = api_get_user_info($row['user_sender_id']);
+    if (empty($row['user_sender_id']) || empty($userInfo)) {
+        $html = get_lang('InvalidMessageId');
+
+        return $html;
+    }
+
+    $default['users'] = [$row['user_sender_id']];
+    $html = manageForm($default, null, $userInfo['complete_name_with_username'], $tpl);
+
+    return $html;
+}
+
+function show_compose_to_user($receiver_id, $tpl)
+{
+    $userInfo = api_get_user_info($receiver_id);
+    $html = get_lang('To').':&nbsp;<strong>'.$userInfo['complete_name'].'</strong>';
+    $default['title'] = api_xml_http_response_encode(get_lang('EnterTitle'));
+    $default['users'] = [$receiver_id];
+    $html .= manageForm($default, null, '', $tpl);
+
+    return $html;
+}
+
+/**
+ * @param          $default
+ * @param null     $select_from_user_list
+ * @param string   $sent_to
+ * @param Template $tpl
+ *
+ * @return string
+ */
+function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl = null)
+{
+    $form = new FormValidator(
+        'compose_message',
+        null,
+        api_get_self(),
+        null,
+        ['enctype' => 'multipart/form-data']
+    );
+
+    $form->addText('title', get_lang('Subject'));
+    $form->addHtmlEditor(
+        'content',
+        get_lang('Message'),
+        false,
+        false,
+        ['ToolbarSet' => 'Messages', 'Width' => '100%', 'Height' => '250', 'style' => true]
+    );
+
+    $form->addLabel(
+        '',
+        '<div id="file_uploads"><div id="filepath_1">
+            <div id="filepaths" class="form-horizontal">
+                <div id="paths-file" class="form-group">
+                <label class="col-sm-4">'.get_lang('FilesAttachment').'</label>
+                <input class="col-sm-8" type="file" name="attach_1"/>
+                </div>
+            </div>
+            <div id="paths-description" class="form-group">
+                <label class="col-sm-4">'.get_lang('Description').'</label>
+                <div class="col-sm-8">
+                <input id="file-descrtiption" class="form-control" type="text" name="legend[]" />
+                </div>
+            </div>
+        </div>
+        </div>'
+    );
+
+    $form->addLabel(
+        '',
+        '<span id="link-more-attach"><a class="btn btn-default" href="javascript://" onclick="return add_image_form()">'.
+        get_lang('AddOneMoreFile').'</a></span>&nbsp;('.
+        sprintf(
+            get_lang('MaximunFileSizeX'),
+            format_file_size(api_get_setting('message_max_upload_filesize'))
+        ).')'
+    );
+
+    $form->addButtonSend(get_lang('SendMessage'), 'compose');
+    $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
+
+    $form->setDefaults($default);
+    $html = '';
+    if ($form->validate()) {
+        $check = true;
+        if ($check) {
+            $file_comments = $_POST['legend'];
+            $title = $default['title'];
+            $content = $default['content'];
+
+            $res = MessageManager::send_message(
+                api_get_user_id(),
+                $title,
+                $content,
+                $_FILES,
+                $file_comments,
+                0,
+                0,
+                0,
+                0,
+                null,
+                false,
+                0,
+                [],
+                true,
+                null,
+                MESSAGE_STATUS_PROMOTED
+            );
+
+            if ($res) {
+                Display::addFlash(Display::return_message(
+                    get_lang('MessageSent'),
+                    'confirmation',
+                    false
+                ));
+            }
+
+            MessageManager::cleanAudioMessage();
+
+        }
+        Security::clear_token();
+        header('Location: '.api_get_path(WEB_PATH).'main/social/promoted_messages.php');
+        exit;
+    } else {
+        $token = Security::get_token();
+        $form->addElement('hidden', 'sec_token');
+        $form->setConstants(['sec_token' => $token]);
+        $html .= $form->returnForm();
+    }
+
+    return $html;
+}
+
+
+$this_section = SECTION_SOCIAL;
+$interbreadcrumb[] = [
+    'url' => api_get_path(WEB_PATH).'main/social/home.php',
+    'name' => get_lang('SocialNetwork'),
+];
+
+
+$interbreadcrumb[] = [
+    'url' => api_get_path(WEB_PATH).'main/messages/inbox.php',
+    'name' => get_lang('Messages'),
+];
+
+$social_right_content = null;
+
+// LEFT COLUMN
+$social_left_content = '';
+
+// Block Social Menu
+$social_menu_block = SocialManager::show_social_menu('messages');
+$social_right_content .= '<div class="row">';
+$social_right_content .= '<div class="col-md-12">';
+$social_right_content .= '<div class="actions">';
+$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
+    Display::return_icon('back.png', get_lang('Back'), [], 32).'</a>';
+$social_right_content .= '</div>';
+$social_right_content .= '</div>';
+$social_right_content .= '<div class="col-md-12">';
+
+
+// MAIN CONTENT
+if (!isset($_POST['compose'])) {
+    if (isset($_GET['re_id'])) {
+        $social_right_content .= show_compose_reply_to_message(
+            $_GET['re_id'],
+            api_get_user_id(),
+            $tpl
+        );
+    } elseif (isset($_GET['send_to_user'])) {
+        $social_right_content .= show_compose_to_user($_GET['send_to_user'], $tpl);
+    } else {
+        $social_right_content .= show_compose_to_any($tpl);
+    }
+} else {
+    $default['title'] = $_POST['title'];
+    $default['content'] = $_POST['content'];
+    $social_right_content .= manageForm($default, null, null, $tpl);
+}
+
+$social_right_content .= '</div>';
+$social_right_content .= '</div>';
+
+
+// Block Social Avatar
+SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
+MessageManager::cleanAudioMessage();
+
+$tpl->assign('social_menu_block', $social_menu_block);
+$tpl->assign('social_right_content', $social_right_content);
+$social_layout = $tpl->get_template('social/inbox.tpl');
+$tpl->display($social_layout);

+ 6 - 6
main/social/profile.php

@@ -156,8 +156,8 @@ if (is_array($personal_course_list)) {
     $course_list_code = array_unique_dimensional($course_list_code);
 }
 
-//Social Block Menu
-$social_menu_block = SocialManager::show_social_menu(
+// Social Block Menu
+$menu = SocialManager::show_social_menu(
     'shared_profile',
     null,
     $user_id,
@@ -173,7 +173,7 @@ $sessionList = SessionManager::getSessionsFollowedByUser(
 
 // My friends
 $friend_html = SocialManager::listMyFriendsBlock($user_id, $link_shared);
-$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
+$addPostForm = SocialManager::getWallForm(api_get_self());
 
 $posts = SocialManager::getWallMessagesByUser($friendId);
 $socialAutoExtendLink = SocialManager::getAutoExtendLink($user_id, $countPost);
@@ -345,9 +345,9 @@ SocialManager::setSocialUserBlock(
 );
 
 $tpl->assign('social_friend_block', $friend_html);
-$tpl->assign('social_menu_block', $social_menu_block);
-$tpl->assign('social_wall_block', $wallSocialAddPost);
-$tpl->assign('social_post_wall_block', $posts);
+$tpl->assign('social_menu_block', $menu);
+$tpl->assign('add_post_form', $addPostForm);
+$tpl->assign('posts', $posts);
 $tpl->assign('social_course_block', $social_course_block);
 $tpl->assign('social_group_info_block', $social_group_info_block);
 $tpl->assign('social_rss_block', $social_rss_block);

+ 95 - 0
main/social/promoted_messages.php

@@ -0,0 +1,95 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+$cidReset = true;
+
+require_once __DIR__.'/../inc/global.inc.php';
+
+api_protect_admin_script();
+
+if (api_get_setting('allow_social_tool') !== 'true') {
+    api_not_allowed(true);
+}
+
+$logInfo = [
+    'tool' => 'Messages',
+    'action' => 'promoted_messages_list',
+];
+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',
+    'name' => get_lang('SocialNetwork'),
+];
+
+$interbreadcrumb[] = [
+    'url' => api_get_path(WEB_CODE_PATH).'social/promoted_messages.php',
+    'name' => get_lang('PromotedMessages'),
+];
+$interbreadcrumb[] = ['url' => '#', 'name' => get_lang('List')];
+$menu = SocialManager::show_social_menu('messages');
+
+// Right content
+$social_right_content = '';
+$keyword = '';
+$actionsLeft = '<a href="'.api_get_path(WEB_CODE_PATH).'social/new_promoted_message.php">'.
+    Display::return_icon('new-message.png', get_lang('ComposeMessage'), [], 32).'</a>';
+
+$form = MessageManager::getSearchForm(api_get_self());
+if ($form->validate()) {
+    $values = $form->getSubmitValues();
+    $keyword = $values['keyword'];
+}
+$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();
+}
+
+$tpl = new Template(null);
+// Block Social Avatar
+SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
+
+$tpl->assign('social_menu_block', $menu);
+$tpl->assign('social_right_content', $social_right_content);
+$social_layout = $tpl->get_template('social/inbox.tpl');
+$tpl->display($social_layout);

+ 65 - 0
main/social/view_promoted_message.php

@@ -0,0 +1,65 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ * @package chamilo.messages
+ */
+$cidReset = true;
+require_once __DIR__.'/../inc/global.inc.php';
+api_block_anonymous_users();
+
+if (api_get_setting('allow_social_tool') != 'true') {
+    api_not_allowed(true);
+}
+
+$this_section = SECTION_SOCIAL;
+$interbreadcrumb[] = ['url' => api_get_path(WEB_PATH).'main/social/home.php', 'name' => get_lang('SocialNetwork')];
+$interbreadcrumb[] = ['url' => 'promoted_messages.php', 'name' => get_lang('PromotedMessages')];
+
+$social_right_content = '';
+/*$social_right_content = '<div class="actions">';
+if (api_get_setting('allow_message_tool') === 'true') {
+    $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">'.
+        Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
+    $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
+        Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
+}
+$social_right_content .= '</div>';*/
+
+if (empty($_GET['id'])) {
+    $messageId = $_GET['id_send'];
+    $source = 'outbox';
+    $show_menu = 'messages_outbox';
+} else {
+    $messageId = $_GET['id'];
+    $source = 'inbox';
+    $show_menu = 'messages_inbox';
+}
+
+$message = '';
+
+$logInfo = [
+    'tool' => 'Messages',
+    'action' => $source,
+    'action_details' => 'view-message',
+];
+Event::registerLog($logInfo);
+
+$social_menu_block = SocialManager::show_social_menu($show_menu);
+$message .= MessageManager::showMessageBox($messageId, 'promoted_messages');
+
+if (!empty($message)) {
+    $social_right_content .= $message;
+} else {
+    api_not_allowed(true);
+}
+$tpl = new Template(get_lang('View'));
+// Block Social Avatar
+SocialManager::setSocialUserBlock($tpl, api_get_user_id(), $show_menu);
+
+$tpl->assign('social_menu_block', $social_menu_block);
+$tpl->assign('social_right_content', $social_right_content);
+$social_layout = $tpl->get_template('social/inbox.tpl');
+$tpl->display($social_layout);

+ 2 - 4
main/template/default/social/home.tpl

@@ -16,10 +16,8 @@
             </div>
         </div>
         <div class="col-md-6">
-            {#{{ social_search_block }}#}
-
             <div id="wallMessages">
-                {{ social_wall_block }}
+                {{ add_post_form }}
                 <div class="spinner"></div>
                 <div class="panel panel-preview panel-default" hidden="true">
                     <div class="panel-heading">
@@ -29,7 +27,7 @@
                         <div class="url_preview"></div>
                     </div>
                 </div>
-                {{ social_post_wall_block }}
+                {{ posts }}
                 {{ social_auto_extend_link }}
             </div>
 

+ 2 - 3
main/template/default/social/profile.tpl

@@ -16,7 +16,7 @@
         </div>
     </div>
     <div id="wallMessages" class="col-md-6">
-        {{ social_wall_block }}
+        {{ add_post_form }}
         <div class="spinner"></div>
         <div class="panel panel-preview panel-default" hidden="true">
             <div class="panel-heading">
@@ -26,12 +26,11 @@
                 <div class="url_preview"></div>
             </div>
         </div>
-        {{ social_post_wall_block }}
+        {{ posts }}
         {{ social_auto_extend_link }}
     </div>
     <div class="col-md-3">
         {{ social_group_info_block }}
-
         <div class="chat-friends">
             <div class="panel-group" id="blocklistFriends" role="tablist" aria-multiselectable="true">
                 <div class="panel panel-default">