Dokeos PHP Cross Reference Learning Management Systems

Source: /main/inc/lib/message.lib.php - 1533 lines - 64794 bytes - Summary - Text - Print

Description: This class provides methods for messages management. Include/require it in your code to use its features.

   1  <?php
   2  /* For licensing terms, see /license.txt */
   3  
   4  /**
   5  *    This class provides methods for messages management.
   6  *    Include/require it in your code to use its features.
   7  *
   8  *    @package dokeos.library
   9  */
  10  
  11  require_once api_get_path(LIBRARY_PATH).'online.inc.php';
  12  require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  13  require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
  14  require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  15  require_once api_get_path(LIBRARY_PATH).'group_portal_manager.lib.php';
  16  require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
  17  
  18  /*
  19   * @todo use constants!
  20   */
  21  define('MESSAGE_STATUS_NEW',                '0');
  22  define('MESSAGE_STATUS_UNREAD',                '1');
  23  //2 ??
  24  define('MESSAGE_STATUS_DELETED',            '3');
  25  define('MESSAGE_STATUS_OUTBOX',                '4');
  26  define('MESSAGE_STATUS_INVITATION_PENDING',    '5');
  27  define('MESSAGE_STATUS_INVITATION_ACCEPTED','6');
  28  define('MESSAGE_STATUS_INVITATION_DENIED',    '7');
  29  
  30  class MessageManager
  31  {
  32  	public static function get_online_user_list($current_user_id) {
  33          $min=30;
  34          global $_configuration;
  35          $userlist = who_is_online($current_user_id,$_configuration['statistics_database'],$min);
  36          foreach($userlist as $row) {
  37              $receiver_id = $row[0];
  38              $online_user_list[$receiver_id] = GetFullUserName($receiver_id).($current_user_id==$receiver_id?("&nbsp;(".get_lang('Myself').")"):(""));
  39          }
  40          return $online_user_list;
  41      }
  42  
  43      /**
  44      * Displays info stating that the message is sent successfully.
  45      */
  46  	public static function display_success_message($uid) {
  47              global $charset;
  48          if ($_SESSION['social_exist']===true) {
  49              $redirect="#remote-tab-2";
  50              if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
  51                  $success=get_lang('MessageSentTo').
  52                  "&nbsp;<b>".
  53                  GetFullUserName($uid).
  54                  "</b>";
  55              }else {
  56                  $success=get_lang('MessageSentTo').
  57                  "&nbsp;<b>".
  58                  GetFullUserName($uid).
  59                  "</b>";
  60              }
  61          } else {
  62                  $success=get_lang('MessageSentTo').
  63                  "&nbsp;<b>".
  64                  GetFullUserName($uid).
  65                  "</b>";
  66          }
  67          echo api_convert_encoding($success, $charset, api_get_system_encoding());
  68      }
  69  
  70      /**
  71      * Displays the wysiwyg html editor.
  72      */
  73  	public static function display_html_editor_area($name, $resp) {
  74          api_disp_html_area($name, get_lang('TypeYourMessage'), '', '', null, array('ToolbarSet' => 'Messages', 'Width' => '95%', 'Height' => '250'));
  75      }
  76  
  77      /**
  78      * Get the new messages for the current user from the database.
  79      */
  80  	public static function get_new_messages() {
  81          $table_message = Database::get_main_table(TABLE_MESSAGE);
  82          if (!api_get_user_id()) {
  83              return false;
  84          }
  85          $i=0;
  86          $query = "SELECT * FROM $table_message WHERE user_receiver_id=".api_get_user_id()." AND msg_status=".MESSAGE_STATUS_UNREAD;
  87          $result = Database::query($query);
  88          $i = Database::num_rows($result);
  89          return $i;
  90      }
  91  
  92      /**
  93      * Get the list of user_ids of users who are online.
  94      */
  95  	public static function users_connected_by_id() {
  96          global $_configuration, $_user;
  97          $minute=30;
  98          $user_connect = who_is_online($_user['user_id'],$_configuration['statistics_database'],$minute);
  99          for ($i=0; $i<count($user_connect); $i++) {
 100              $user_id_list[$i]=$user_connect[$i][0];
 101          }
 102          return $user_id_list;
 103      }
 104  
 105      /**
 106       * Gets the total number of messages, used for the inbox sortable table
 107       */
 108  	public static function get_number_of_messages ($unread = false) {
 109          $table_message = Database::get_main_table(TABLE_MESSAGE);
 110  
 111          $condition_msg_status = '';
 112          if ($unread) {
 113              $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
 114          } else {
 115              $condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
 116          }
 117  
 118          if(api_is_allowed_to_edit()){
 119          $sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE $condition_msg_status";
 120          }
 121          else {
 122          $sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE $condition_msg_status AND user_receiver_id=".api_get_user_id();
 123          }
 124          $sql_result = Database::query($sql_query);
 125          $result = Database::fetch_array($sql_result);
 126          return $result['number_messages'];
 127      }
 128  
 129      /**
 130       * Gets information about some messages, used for the inbox sortable table
 131       * @param int $from
 132       * @param int $number_of_items
 133       * @param string $direction
 134       */
 135  	public static function get_message_data ($from, $number_of_items, $column, $direction) {
 136          global $charset;
 137          $from = intval($from);
 138          $number_of_items = intval($number_of_items);
 139  
 140          //forcing this order
 141          if (!isset($direction)) {
 142              $column = 3;
 143              $direction = 'DESC';
 144          } else {
 145              $column = intval($column);
 146              if (!in_array($direction, array('ASC', 'DESC')))
 147                  $direction = 'ASC';
 148          }
 149  
 150  
 151          $table_message = Database::get_main_table(TABLE_MESSAGE);
 152          $request=api_is_xml_http_request();
 153          if(api_is_allowed_to_edit()){
 154          $sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, msg_status as col4 FROM $table_message " .
 155                       " WHERE user_receiver_id=".api_get_user_id()." AND msg_status IN (0,1)" .
 156                       " ORDER BY col$column $direction LIMIT $from,$number_of_items";
 157          }
 158          else {
 159          $sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, msg_status as col4 FROM $table_message " .
 160                       " WHERE user_receiver_id=".api_get_user_id()." AND msg_status IN (0,1)" .
 161                       " ORDER BY col$column $direction LIMIT $from,$number_of_items";
 162          }
 163  
 164          $sql_result = Database::query($sql_query);
 165          $i = 0;
 166          $message_list = array ();
 167          while ($result = Database::fetch_row($sql_result)) {
 168  
 169              if ($request===true) {
 170                  $message[0] = '<input type="checkbox" value='.$result[0].' name="id[]">';
 171               } else {
 172                  $message[0] = ($result[0]);
 173               }
 174  
 175              $result[2] = Security::remove_XSS($result[2]);
 176              $result[2] = cut($result[2],80,true);
 177  
 178              if ($request===true) {
 179                  $message[1] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[1]).'</a>';
 180                  $message[2] = '<a onclick="get_action_url_and_show_messages(1,'.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
 181                  $message[4] = '<a onclick="reply_to_messages(\'show\','.$result[0].',\'\')" href="javascript:void(0)">'.Display::return_icon('pixel.gif',get_lang('ReplyToMessage'), array('class' => 'actionplaceholdericon actionsmessagereply')).'</a>'.
 182                            '&nbsp;&nbsp;<a onclick="delete_one_message('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('pixel.gif',get_lang('DeleteMessage'), array('class' => 'actionplaceholdericon actionsmessagedelete')).'</a>';
 183              } else {
 184                  if($result[4]==1) {
 185                      $class = 'class = "unread"';
 186                  } else {
 187                      $class = 'class = "read"';
 188                  }
 189  
 190                  $link = '';
 191                  if ($_GET['f']=='social') {
 192                      $link = '&f=social';
 193                  }
 194  
 195                  if (isset($_REQUEST['cidReq'])) {
 196                      $link = '&cidReq='.Security::remove_XSS($_REQUEST['cidReq']);
 197                  }
 198                  if (isset($_REQUEST['id_session'])) {
 199                      $link .= '&id_session='.Security::remove_XSS($_REQUEST['id_session']);
 200                  }
 201                  
 202                  // If request comes from social network or group ID is not defined
 203                  if ($_GET['f']=='social' || !isset($_GET['group_id'])) {
 204                      $message[1] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.GetFullUserName(($result[1])).'</a>';;
 205                      $message[2] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.$result[2].'</a>';
 206                  }
 207                  else {
 208                      $message[1] = '<a '.$class.' href="../group/view_message.php?id='.$result[0].$link.'">'.GetFullUserName(($result[1])).'</a>';;
 209                      $message[2] = '<a '.$class.' href="../group/view_message.php?id='.$result[0].$link.'">'.$result[2].'</a>';
 210                  }
 211                      $message[4] = '<a href="new_message.php?re_id='.$result[0].$link.'">'.Display::return_icon('pixel.gif',get_lang('ReplyToMessage'), array('class' => 'actionplaceholdericon actionsmessagereply')).'</a>'.
 212                            '&nbsp;&nbsp;<a delete_one_message('.$result[0].') href="inbox.php?action=deleteone&id='.$result[0].$link.'">'.Display::return_icon('pixel.gif',get_lang('DeleteMessage'), array('class' => 'actionplaceholdericon actionsmessagedelete')).'</a>';
 213              }
 214              $datetime = explode(" ", $result[3]);
 215              $dateparts = explode("-", $datetime[0]);        
 216              $message_date = $dateparts[2].'-'.$dateparts[1].'-'.$dateparts[0];
 217  
 218              $message[3] = $message_date; //date stays the same
 219              foreach($message as $key => $value) {
 220                  $message[$key] = api_xml_http_response_encode($value);
 221              }
 222              $message_list[] = $message;
 223              $i++;
 224          }
 225          return $message_list;
 226      }
 227  
 228      /**
 229       * Save message for social network
 230       * @param int       receiver user id
 231       * @param string  subject
 232       * @param string  content
 233       * @param array   attachment files array($_FILES) (optional)
 234       * @param array   comments about attachment files (optional)
 235       * @param int     group id (optional)
 236       * @param int     parent id (optional)
 237       * @param int       message id for updating the message (optional)
 238       * @return bool
 239       */
 240  	public static function send_message ($receiver_user_id, $subject, $content, $file_attachments = array(), $file_comments = array(), $group_id = 0, $parent_id = 0, $edit_message_id = 0) {
 241          global $charset;
 242          $table_message = Database::get_main_table(TABLE_MESSAGE);
 243          $group_id = intval($group_id);
 244          $receiver_user_id = intval($receiver_user_id);
 245          $parent_id = intval($parent_id);
 246          $user_sender_id = api_get_user_id();
 247          error_log('A');
 248  
 249          $total_filesize = 0;
 250          if (is_array($file_attachments)) {
 251              foreach ($file_attachments as $file_attach) {
 252                  $total_filesize += $file_attach['size'];
 253              }
 254          }
 255          error_log('B');
 256          error_log($total_filesize);
 257          error_log(api_get_setting('message_max_upload_filesize'));
 258  
 259          // validating fields
 260          if (empty($subject)) {
 261              return get_lang('YouShouldWriteASubject');
 262          } else if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
 263              return sprintf(get_lang("FilesSizeExceedsX"),format_file_size(api_get_setting('message_max_upload_filesize')));
 264          }
 265          error_log('C');
 266          if (!empty($receiver_user_id) || !empty($group_id)) {
 267  
 268              // message for user friend
 269          //    $subject = api_convert_encoding($subject, $charset);
 270              $subject = Database::escape_string($subject);
 271               //  $content = api_convert_encoding($content, $charset);
 272              $content = Database::escape_string($content);
 273              //$content = Security::remove_XSS($content);
 274  
 275              //useless query
 276              //echo $sql = "SELECT COUNT(*) as count FROM $table_message WHERE user_sender_id = ".$user_sender_id." AND user_receiver_id='$receiver_user_id' AND title = '$title' AND content ='$content' AND group_id = '$group_id' AND parent_id = '$parent_id'";
 277              //$res_exist = Database::query($sql);
 278              //$row_exist = Database::fetch_array($res_exist,'ASSOC');
 279  
 280              //We should ALWAYS sent emails
 281              //if ($row_exist['count'] == 0) {
 282          error_log('D');
 283              //message in inbox for user friend
 284              if ($edit_message_id) {
 285                  $query = " UPDATE $table_message SET update_date = '".date('Y-m-d H:i:s')."', title = '$subject', content = '$content' WHERE id = '$edit_message_id' ";
 286                  $result = Database::query($query);
 287                  $inbox_last_id = $edit_message_id;
 288              } else {
 289                  $query = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content, group_id, parent_id, update_date ) ".
 290                       " VALUES ('$user_sender_id', '$receiver_user_id', '1', '".date('Y-m-d H:i:s')."','$subject','$content','$group_id','$parent_id', '".date('Y-m-d H:i:s')."')";
 291                  $result = Database::query($query);
 292                  $inbox_last_id = Database::insert_id();
 293              }
 294  
 295              // save attachment file for inbox messages
 296              if (is_array($file_attachments)) {
 297                  $i = 0;
 298                  foreach ($file_attachments as $file_attach) {
 299                      if ($file_attach['error'] == 0) {
 300                          self::save_message_attachment_file($file_attach,$file_comments[$i],$inbox_last_id,null,$receiver_user_id,$group_id);
 301                      }
 302                      $i++;
 303                  }
 304              }
 305          error_log('E');
 306              if (empty($group_id)) {
 307                  //message in outbox for user friend or group
 308                  $sql = "INSERT INTO $table_message(user_sender_id, user_receiver_id, msg_status, send_date, title, content, group_id, parent_id, update_date ) ".
 309                           " VALUES ('$user_sender_id', '$receiver_user_id', '4', '".date('Y-m-d H:i:s')."','$subject','$content', '$group_id', '$parent_id', '".date('Y-m-d H:i:s')."')";
 310                  $rs = Database::query($sql);
 311                  $outbox_last_id = Database::insert_id();
 312  
 313                  // save attachment file for outbox messages
 314                  if (is_array($file_attachments)) {
 315                      $o = 0;
 316                      foreach ($file_attachments as $file_attach) {
 317                          if ($file_attach['error'] == 0) {
 318                              self::save_message_attachment_file($file_attach,$file_comments[$o],$outbox_last_id,$user_sender_id);
 319                          }
 320                          $o++;
 321                      }
 322                  }
 323              }
 324              return $result;
 325          }
 326          return false;
 327      }
 328  
 329      /**
 330       * Update parent ids for other receiver user from current message in groups
 331       * @author Christian Fasanando Flores
 332       * @param  int    parent id
 333       * @param  int    receiver user id
 334       * @param  int    message id
 335       * @return void
 336       */
 337  	public static function update_parent_ids_from_reply($parent_id,$receiver_user_id,$message_id) {
 338  
 339          $table_message = Database::get_main_table(TABLE_MESSAGE);
 340          $parent_id = intval($parent_id);
 341          $receiver_user_id = intval($receiver_user_id);
 342          $message_id = intval($message_id);
 343          // first get data from message id (parent)
 344          $sql_message= "SELECT * FROM $table_message WHERE id = '$parent_id'";
 345          $rs_message    = Database::query($sql_message);
 346          $row_message= Database::fetch_array($rs_message);
 347  
 348          // get message id from data found early for other receiver user
 349          $sql_msg_id    = " SELECT id FROM $table_message WHERE user_sender_id ='{$row_message[user_sender_id]}'
 350                           AND title='{$row_message[title]}' AND content='{$row_message[content]}' AND group_id='{$row_message[group_id]}' AND user_receiver_id='$receiver_user_id'";
 351          $rs_msg_id    = Database::query($sql_msg_id);
 352          $row = Database::fetch_array($rs_msg_id);
 353  
 354          // update parent_id for other user receiver
 355          $sql_upd = "UPDATE $table_message SET parent_id = '{$row[id]}' WHERE id = '$message_id'";
 356          Database::query($sql_upd);
 357      }
 358  
 359  	public static function delete_message_by_user_receiver ($user_receiver_id,$id) {
 360          $table_message = Database::get_main_table(TABLE_MESSAGE);
 361          if ($id != strval(intval($id))) return false;
 362          $user_receiver_id = intval($user_receiver_id);
 363          $id = Database::escape_string($id);
 364          $sql="SELECT * FROM $table_message WHERE id=".$id." AND msg_status<>4;";
 365          $rs=Database::query($sql);
 366  
 367          if (Database::num_rows($rs) > 0 ) {
 368              $row = Database::fetch_array($rs);
 369              // delete attachment file
 370              $res = self::delete_message_attachment_file($id,$user_receiver_id);
 371              // delete message
 372              if(api_is_allowed_to_edit()){
 373              $query = "UPDATE $table_message SET msg_status=3 WHERE id=".$id;
 374              }
 375              else {
 376              $query = "UPDATE $table_message SET msg_status=3 WHERE user_receiver_id=".$user_receiver_id." AND id=".$id;
 377              }
 378              //$query = "DELETE FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_receiver_id)." AND id=".$id;
 379              $result = Database::query($query);
 380              return $result;
 381          } else {
 382              return false;
 383          }
 384      }
 385      /**
 386       * Set status deleted
 387       * @author Isaac FLores Paz <isaac.flores@dokeos.com>
 388       * @param  integer
 389       * @param  integer
 390       * @return array
 391       */
 392  	public static function delete_message_by_user_sender ($user_sender_id,$id) {
 393          if ($id != strval(intval($id))) return false;
 394          $table_message = Database::get_main_table(TABLE_MESSAGE);
 395  
 396          $id = intval($id);
 397          $user_sender_id = intval($user_sender_id);
 398  
 399          $sql="SELECT * FROM $table_message WHERE id='$id'";
 400          $rs=Database::query($sql);
 401  
 402          if (Database::num_rows($rs) > 0 ) {
 403              $row = Database::fetch_array($rs);
 404              // delete attachment file
 405              $res = self::delete_message_attachment_file($id,$user_sender_id);
 406              // delete message
 407              $query = "UPDATE $table_message SET msg_status=3 WHERE user_sender_id='$user_sender_id' AND id='$id'";
 408              //$query = "DELETE FROM $table_message WHERE user_sender_id='$user_sender_id' AND id='$id'";
 409              $result = Database::query($query);
 410              return $result;
 411          }
 412          return false;
 413      }
 414  
 415      /**
 416       * Saves a message attachment files
 417       * @param  array     $_FILES['name']
 418       * @param  string      a comment about the uploaded file
 419       * @param  int        message id
 420       * @param  int        receiver user id (optional)
 421       * @param  int        sender user id (optional)
 422       * @param  int        group id (optional)
 423       * @return void
 424       */
 425  	public static function save_message_attachment_file($file_attach,$file_comment,$message_id,$receiver_user_id=0,$sender_user_id=0,$group_id=0) {
 426  
 427          $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 428  
 429          // Try to add an extension to the file if it hasn't one
 430          $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $file_attach['type']);
 431  
 432          // user's file name
 433          $file_name =$file_attach['name'];
 434          if (!filter_extension($new_file_name))  {
 435              Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
 436          } else {
 437              $new_file_name = uniqid('');
 438  
 439              $message_user_id = '';
 440              if (!empty($receiver_user_id)) {
 441                  $message_user_id = $receiver_user_id;
 442              } else {
 443                  $message_user_id = $sender_user_id;
 444              }
 445  
 446              // User-reserved directory where photos have to be placed.
 447  
 448              if (!empty($group_id)) {
 449                  $path_user_info = GroupPortalManager::get_group_picture_path_by_id($group_id, 'system', true);
 450              } else {
 451                  $path_user_info = UserManager::get_user_picture_path_by_id($message_user_id, 'system', true);
 452              }
 453  
 454              $path_message_attach = $path_user_info['dir'].'message_attachments/';
 455  
 456              // If this directory does not exist - we create it.
 457              if (!file_exists($path_message_attach)) {
 458                  @mkdir($path_message_attach, 0777, true);
 459              }
 460              $new_path=$path_message_attach.$new_file_name;
 461              if (is_uploaded_file($file_attach['tmp_name'])) {
 462                  $result= @copy($file_attach['tmp_name'], $new_path);
 463              }
 464              $safe_file_comment= Database::escape_string($file_comment);
 465              $safe_file_name = Database::escape_string($file_name);
 466              $safe_new_file_name = Database::escape_string($new_file_name);
 467              // Storing the attachments if any
 468              $sql="INSERT INTO $tbl_message_attach(filename,comment, path,message_id,size)
 469                    VALUES ( '$safe_file_name', '$safe_file_comment', '$safe_new_file_name' , '$message_id', '".$file_attach['size']."' )";
 470              $result=Database::query($sql);
 471          }
 472      }
 473  
 474      /**
 475       * Delete message attachment files (logically updating the row with a suffix _DELETE_id)
 476       * @param  int    message id
 477       * @param  int    message user id (receiver user id or sender user id)
 478       * @param  int    group id (optional)
 479       * @return void
 480       */
 481  	public static function delete_message_attachment_file($message_id,$message_uid,$group_id=0) {
 482  
 483          $message_id = intval($message_id);
 484          $message_uid = intval($message_uid);
 485          $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 486  
 487          $sql= "SELECT * FROM $table_message_attach WHERE message_id = '$message_id'";
 488          $rs    = Database::query($sql);
 489          $new_paths = array();
 490          while ($row = Database::fetch_array($rs)) {
 491              $path         = $row['path'];
 492              $attach_id  = $row['id'];
 493              $new_path     = $path.'_DELETED_'.$attach_id;
 494  
 495              if (!empty($group_id)) {
 496                  $path_user_info = GroupPortalManager::get_group_picture_path_by_id($group_id, 'system', true);
 497              } else {
 498                  $path_user_info = UserManager::get_user_picture_path_by_id($message_uid, 'system', true);
 499              }
 500  
 501              $path_message_attach = $path_user_info['dir'].'message_attachments/';
 502              if (is_file($path_message_attach.$path)) {
 503                  if(rename($path_message_attach.$path, $path_message_attach.$new_path)) {
 504                      $sql_upd = "UPDATE $table_message_attach set path='$new_path' WHERE id ='$attach_id'";
 505                      $rs_upd = Database::query($sql_upd);
 506                  }
 507              }
 508          }
 509      }
 510  
 511      /**
 512       * update messages by user id and message id
 513       * @param  int        user id
 514       * @param  int        message id
 515       * @return resource
 516       */
 517  	public static function update_message ($user_id, $message_id) {
 518          if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) return false;
 519          $table_message = Database::get_main_table(TABLE_MESSAGE);
 520          $query = "UPDATE $table_message SET msg_status = '0' WHERE msg_status<>4 AND user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
 521          $result = Database::query($query);
 522      }
 523  
 524      /**
 525       * get messages by user id and message id
 526       * @param  int        user id
 527       * @param  int        message id
 528       * @return array
 529       */
 530  	 public static function get_message_by_user ($user_id,$message_id) {
 531           if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) return false;
 532          $table_message = Database::get_main_table(TABLE_MESSAGE);
 533          $query = "SELECT * FROM $table_message WHERE user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
 534          $result = Database::query($query);
 535          return $row = Database::fetch_array($result);
 536      }
 537  
 538      /**
 539       * get messages by group id
 540       * @param  int        group id
 541       * @return array
 542       */
 543  	public static function get_messages_by_group($group_id) {
 544          if ($group_id != strval(intval($group_id))) return false;
 545           $table_message = Database::get_main_table(TABLE_MESSAGE);
 546           $current_uid = api_get_user_id();
 547           $group_id = intval($group_id);
 548          $query = "SELECT * FROM $table_message WHERE group_id=$group_id AND msg_status <> ".MESSAGE_STATUS_OUTBOX." ORDER BY id";
 549          $rs = Database::query($query);
 550          $data = array();
 551          if (Database::num_rows($rs) > 0) {
 552              while ($row = Database::fetch_array($rs)) {
 553                  $data[] = $row;
 554              }
 555          }
 556          return $data;
 557      }
 558  
 559      /**
 560       * get messages by parent id optionally with limit
 561       * @param  int        parent id
 562       * @param  int        group id (optional)
 563       * @param  int        offset (optional)
 564       * @param  int        limit (optional)
 565       * @return array
 566       */
 567  	public static function get_messages_by_parent($parent_id,$group_id = '',$offset = 0,$limit = 0) {
 568          if ($parent_id != strval(intval($parent_id))) return false;
 569           $table_message = Database::get_main_table(TABLE_MESSAGE);
 570           $current_uid = api_get_user_id();
 571           $parent_id = intval($parent_id);
 572  
 573           $condition_group_id = "";
 574           if ($group_id !== '') {
 575               $group_id = intval($group_id);
 576               $condition_group_id = " AND group_id = '$group_id' ";
 577           }
 578  
 579           $condition_limit = "";
 580           if ($offset && $limit) {
 581               $offset = ($offset - 1) * $limit;
 582               $condition_limit = " LIMIT $offset,$limit ";
 583           }
 584  
 585          $query = "SELECT * FROM $table_message WHERE parent_id='$parent_id' AND msg_status <> ".MESSAGE_STATUS_OUTBOX." $condition_group_id ORDER BY send_date DESC $condition_limit ";
 586          $rs = Database::query($query);
 587          $data = array();
 588          if (Database::num_rows($rs) > 0) {
 589              while ($row = Database::fetch_array($rs)) {
 590                  $data[$row['id']] = $row;
 591              }
 592          }
 593          return $data;
 594      }
 595  
 596      /**
 597       * Gets information about if exist messages
 598       * @author Isaac FLores Paz <isaac.flores@dokeos.com>
 599       * @param  integer
 600       * @param  integer
 601       * @return boolean
 602       */
 603  	 public static function exist_message ($user_id, $id) {
 604           if ($id != strval(intval($id)) || $user_id != strval(intval($user_id))) return false;
 605          $table_message = Database::get_main_table(TABLE_MESSAGE);
 606          $query = "SELECT id FROM $table_message WHERE user_receiver_id=".Database::escape_string($user_id)." AND id='".Database::escape_string($id)."'";
 607          $result = Database::query($query);
 608          $num = Database::num_rows($result);
 609          if ($num>0)
 610              return true;
 611          else
 612              return false;
 613      }
 614      /**
 615       * Gets information about messages sent
 616       * @param  integer
 617       * @param  integer
 618       * @param  string
 619       * @return array
 620       */
 621  	 public static function get_message_data_sent ($from, $number_of_items, $column, $direction) {
 622           global $charset;
 623  
 624           $from = intval($from);
 625          $number_of_items = intval($number_of_items);
 626  
 627          if (!isset($direction)) {
 628              $column = 3;
 629              $direction = 'DESC';
 630          } else {
 631              $column = intval($column);
 632              if (!in_array($direction, array('ASC', 'DESC')))
 633                  $direction = 'ASC';
 634          }
 635  
 636  
 637          $table_message = Database::get_main_table(TABLE_MESSAGE);
 638          $request=api_is_xml_http_request();
 639          if(api_is_allowed_to_edit()){
 640          $sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5 FROM $table_message " .
 641                       "WHERE user_sender_id=".api_get_user_id()." AND msg_status=".MESSAGE_STATUS_OUTBOX." " .
 642                       "ORDER BY col$column $direction LIMIT $from,$number_of_items";
 643          }
 644          else {
 645          $sql_query = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5 FROM $table_message " .
 646                       "WHERE user_sender_id=".api_get_user_id()." AND msg_status=".MESSAGE_STATUS_OUTBOX." " .
 647                       "ORDER BY col$column $direction LIMIT $from,$number_of_items";
 648          }
 649  
 650          $sql_result = Database::query($sql_query);
 651          $i = 0;
 652          $message_list = array ();
 653          while ($result = Database::fetch_row($sql_result)) {
 654  
 655              if ($request===true) {
 656                  $message[0] = '<input type="checkbox" value='.$result[0].' name="out[]">';
 657               } else {
 658                  $message[0] = ($result[0]);
 659               }
 660  
 661              $class = 'class = "read"';
 662              $result[2] = Security::remove_XSS($result[2]);
 663  
 664              if ($request===true) {
 665                  $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[4]).'</a>';
 666                  $message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\","",$result[2]).'</a>';
 667  
 668                  $datetime = explode(" ", $result[3]);
 669                  $dateparts = explode("-", $datetime[0]);        
 670                  $message_date = $dateparts[2].'-'.$dateparts[1].'-'.$dateparts[0];
 671  
 672                  $message[3] = $message_date; //date stays the same
 673                  $message[4] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('pixel.gif',get_lang('DeleteMessage'), array('class' => 'actionplaceholdericon actionsmessagedelete')).'</a>';
 674              } else {
 675                  $link = '';
 676                  if ($_GET['f']=='social') {
 677                      $link = '&f=social';
 678                  }
 679  
 680                  if (isset($_REQUEST['cidReq'])) {
 681                      $link = '&cidReq='.$_REQUEST['cidReq'];
 682                  }
 683                  if (isset($_REQUEST['id_session'])) {
 684                      $link .= '&id_session='.$_REQUEST['id_session'];
 685                  }
 686                  
 687                  if ($_GET['f']=='social') {
 688                  $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.GetFullUserName($result[4]).'</a>';
 689                  $message[2] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a>';
 690                  }
 691                  else {
 692                  $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../group/view_message.php?id_send='.$result[0].$link.'">'.GetFullUserName($result[4]).'</a>';
 693                  $message[2] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../group/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a>';
 694                  }
 695                  
 696                  $datetime = explode(" ", $result[3]);
 697                  $dateparts = explode("-", $datetime[0]);        
 698                  $message_date = $dateparts[2].'-'.$dateparts[1].'-'.$dateparts[0];
 699  
 700                  $message[3] = $message_date; //date stays the same
 701                  $message[4] = '<a href="outbox.php?action=deleteone&id='.$result[0].$link.'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;">'.Display::return_icon('pixel.gif',get_lang('DeleteMessage'), array('class' => 'actionplaceholdericon actionsmessagedelete')).'</a>';
 702              }
 703  
 704              foreach($message as $key => $value) {
 705                  $message[$key] = $value;
 706              }
 707              $message_list[] = $message;
 708              $i++;
 709          }
 710  
 711          return $message_list;
 712      }
 713      /**
 714       * Gets information about number messages sent
 715       * @author Isaac FLores Paz <isaac.flores@dokeos.com>
 716       * @param void
 717       * @return integer
 718       */
 719  	 public static function get_number_of_messages_sent () {
 720          $table_message = Database::get_main_table(TABLE_MESSAGE);
 721  
 722          if(api_is_allowed_to_edit()){
 723          $sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status=".MESSAGE_STATUS_OUTBOX;
 724          }
 725          else {
 726          $sql_query = "SELECT COUNT(*) as number_messages FROM $table_message WHERE msg_status=".MESSAGE_STATUS_OUTBOX." AND user_sender_id=".api_get_user_id();
 727          }
 728          $sql_result = Database::query($sql_query);
 729          $result = Database::fetch_array($sql_result);
 730          return $result['number_messages'];
 731      }
 732  
 733      /**
 734       * display message box in the inbox
 735       * @param int the message id
 736       * @param string inbox or outbox strings are available
 737       * @return string html with the message content
 738       */
 739  	public static function show_message_box($message_id, $source = 'inbox') {
 740          $table_message         = Database::get_main_table(TABLE_MESSAGE);
 741          $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 742          $message_id = intval($message_id);
 743  
 744          if ($source == 'outbox') {
 745              if (isset($message_id) && is_numeric($message_id)) {
 746                  if(api_is_allowed_to_edit()){
 747                  $query    = "SELECT * FROM $table_message WHERE id=".$message_id." AND msg_status=4;";
 748                  }
 749                  else {
 750                  $query    = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".$message_id." AND msg_status=4;";
 751                  }
 752                  $result = Database::query($query);
 753                  $path    = 'outbox.php';
 754              }
 755          } else {
 756              if (is_numeric($message_id) && !empty($message_id)) {
 757                  if(api_is_allowed_to_edit()){
 758                  $query = "SELECT * FROM $table_message WHERE msg_status<>4 AND id='".$message_id."';";
 759                  $result = Database::query($query);
 760                  }
 761                  else {
 762                  $query = "UPDATE $table_message SET msg_status = '".MESSAGE_STATUS_NEW."' WHERE user_receiver_id=".api_get_user_id()." AND id='".$message_id."';";
 763                  $result = Database::query($query);
 764  
 765                  $query = "SELECT * FROM $table_message WHERE msg_status<>4 AND user_receiver_id=".api_get_user_id()." AND id='".$message_id."';";
 766                  $result = Database::query($query);
 767                  }
 768              }
 769              $path='inbox.php';
 770          }
 771  
 772          $row = Database::fetch_array($result);
 773  
 774          // get file attachments by message id
 775          $files_attachments = self::get_links_message_attachment_files($message_id,$source);
 776  
 777          $user_con = self::users_connected_by_id();
 778          $band=0;
 779          $reply='';
 780          for ($i=0;$i<count($user_con);$i++)
 781              if ($row[1]==$user_con[$i])
 782                  $band=1;
 783  
 784          $row[5] = Security::remove_XSS($row[5]);
 785  
 786          $message_content =  '
 787          <table class="message_view_table actions">
 788              <tr>
 789                <td width=10>&nbsp; </td>
 790                <td vAlign=top width="100%">
 791                    <table>
 792                      <tr>
 793                        <td width="100%">
 794                         <h1>'.str_replace("\\","",$row[5]).'</h1>
 795                        </td>
 796                        <tr>';
 797              if (api_get_setting('allow_social_tool') == 'true') {
 798                  $user_image = '';
 799                  /*    @todo add user image
 800                  $user_image = UserManager::get_user_picture_path_by_id($row[1],'web', true,false);
 801                  $user_image = UserManager::get_picture_user($row[1], $user_image['file'],'40');
 802                  $user_image = '<img src="'.$user_image['file'].'" style="'.$user_image['style'].'" >';
 803                  */
 804                  if ($source == 'outbox') {
 805                      $message_content .='<td>'.get_lang('From').' '.$user_image.'<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$row[1].'">'.GetFullUserName($row[1]).'</a> '.api_strtolower(get_lang('To')).'&nbsp;<b>'.GetFullUserName($row[2]).'</b> </TD>';
 806                  } else {
 807                      $message_content .='<td>'.get_lang('From').' '.$user_image.'<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$row[1].'">'.GetFullUserName($row[1]).'</a> '.api_strtolower(get_lang('To')).'&nbsp;<b>'.get_lang('Me').'</b> </TD>';
 808                  }
 809  
 810              } else {
 811                  if ($source == 'outbox') {
 812                      $message_content .='<td>'.get_lang('From').'&nbsp;'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).' <b>'.GetFullUserName($row[2]).'</b> </TD>';
 813                  } else {
 814                      $message_content .='<td>'.get_lang('From').'&nbsp;'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).' <b>'.get_lang('Me').'</b> </TD>';
 815                  }
 816              }
 817  
 818           $message_content .='</tr>
 819                        <tr>
 820                        <td>'.get_lang('Date').'&nbsp; '.$row[4].'</TD>
 821                        </tr>
 822                      </tr>
 823                  </table>
 824                  <br />
 825                  <table height=209 width="100%">
 826                      <tr>
 827                        <td vAlign=top class="view-message-content "><div class="quiz_content_actions" style="min-height:200px;">'.str_replace("\\","",$row[6]).'</div></td>
 828                      </tr>
 829                  </table>
 830                  <div id="message-attach">'.(!empty($files_attachments)?implode('&nbsp;|&nbsp;',$files_attachments):'').'</div>
 831                  <div class=HT style="padding-bottom: 5px">';
 832              $social_link = '';
 833              if ($_GET['f'] == 'social') {
 834                  $social_link = 'f=social';
 835              }
 836  
 837              if (isset($_REQUEST['cidReq'])) {
 838                  $social_link = '&cidReq='.$_REQUEST['cidReq'];
 839              }
 840              if (isset($_REQUEST['id_session'])) {
 841                  $social_link .= '&id_session='.$_REQUEST['id_session'];
 842              }
 843  
 844              if ($source == 'outbox') {
 845                  $message_content .= '<a href="outbox.php?'.$social_link.'">'.Display::return_icon('pixel.gif',get_lang('ReturnToOutbox'), array('class' => 'actionplaceholdericon actionprev')).get_lang('ReturnToOutbox').'</a> &nbsp';
 846              } else {
 847                  $message_content .= '<a href="inbox.php?'.$social_link.'">'.Display::return_icon('pixel.gif',get_lang('ReturnToOutbox'), array('class' => 'actionplaceholdericon actionprev')).get_lang('ReturnToInbox').'</a> &nbsp';
 848                  $message_content .= '<a href="new_message.php?re_id='.$message_id.'&'.$social_link.'">'.Display::return_icon('pixel.gif',get_lang('ReplyToMessage'), array('class' => 'actionplaceholdericon actionsmessagereply')).get_lang('ReplyToMessage').'</a> &nbsp';
 849              }
 850              $message_content .= '<a href="inbox.php?action=deleteone&id='.$message_id.'&'.$social_link.'" >'.Display::return_icon('pixel.gif',get_lang('DeleteMessage'), array('class' => 'actionplaceholdericon actionsmessagedelete')).''.get_lang('DeleteMessage').'</a>&nbsp';
 851  
 852              $message_content .='</div></td>
 853                <td width=10></td>
 854              </tr>
 855          </table>';
 856          return $message_content;
 857      }
 858  
 859  
 860      /**
 861       * display message box sent showing it into outbox
 862       * @return void
 863       */
 864  	public static function show_message_box_sent () {
 865          global $charset;
 866  
 867          $table_message = Database::get_main_table(TABLE_MESSAGE);
 868          $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
 869  
 870          $message_id = '';
 871          if (is_numeric($_GET['id_send'])) {
 872              $query = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".intval(Database::escape_string($_GET['id_send']))." AND msg_status=4;";
 873              $result = Database::query($query);
 874              $message_id = intval($_GET['id_send']);
 875          }
 876          $path='outbox.php';
 877  
 878          // get file attachments by message id
 879          $files_attachments = self::get_links_message_attachment_files($message_id,'outbox');
 880  
 881          $row = Database::fetch_array($result);
 882          $user_con = self::users_connected_by_id();
 883          $band=0;
 884          $reply='';
 885          for ($i=0;$i<count($user_con);$i++)
 886              if ($row[1]==$user_con[$i])
 887                  $band=1;
 888          echo '<div class=actions>';
 889          echo '<a onclick="close_and_open_outbox()" href="javascript:void(0)">'.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToOutbox'))).api_xml_http_response_encode(get_lang('BackToOutbox')).'</a>';
 890          echo '<a onclick="delete_one_message_outbox('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon('message_delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
 891          echo '</div><br />';
 892          echo '
 893          <table class="message_view_table" >
 894              <TR>
 895                <TD width=10>&nbsp; </TD>
 896                <TD vAlign=top width="100%">
 897                    <TABLE>
 898                      <TR>
 899                        <TD width="100%">
 900                              <TR> <h1>'.str_replace("\\","",api_xml_http_response_encode($row[5])).'</h1></TR>
 901                        </TD>
 902                        <TR>
 903                            <TD>'.api_xml_http_response_encode(get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(get_lang('To')).'&nbsp;  <b>'.GetFullUserName($row[2])).'</b> </TD>
 904                        </TR>
 905                        <TR>
 906                        <TD >'.api_xml_http_response_encode(get_lang('Date').'&nbsp; '.$row[4]).'</TD>
 907                        </TR>
 908                      </TR>
 909                  </TABLE>
 910                  <br />
 911                  <TABLE height=209 width="100%" bgColor=#ffffff>
 912                    <TBODY>
 913                      <TR>
 914                        <TD vAlign=top>'.str_replace("\\","",api_xml_http_response_encode($row[6])).'</TD>
 915                      </TR>
 916                    </TBODY>
 917                  </TABLE>
 918                  <div id="message-attach">'.(!empty($files_attachments)?implode('&nbsp;|&nbsp;',$files_attachments):'').'</div>
 919                  <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
 920                <TD width=10>&nbsp;</TD>
 921              </TR>
 922          </TABLE>';
 923      }
 924  
 925      /**
 926       * get user id by user email
 927       * @param string $user_email
 928       * @return int user id
 929       */
 930  	public static function get_user_id_by_email ($user_email) {
 931          $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
 932          $sql='SELECT user_id FROM '.$tbl_user.' WHERE email="'.Database::escape_string($user_email).'";';
 933          $rs=Database::query($sql);
 934          $row=Database::fetch_array($rs,'ASSOC');
 935          if (isset($row['user_id'])) {
 936              return $row['user_id'];
 937          } else {
 938              return null;
 939          }
 940      }
 941  
 942      /**
 943       * Displays messages of a group with nested view
 944       * @param int group id
 945       */
 946  	public static function display_messages_for_group($group_id) {
 947  
 948          global $my_group_role;
 949  
 950          $rows = self::get_messages_by_group($group_id);
 951          $rows = self::calculate_children($rows);
 952          $group_info = GroupPortalManager::get_group_data($group_id);
 953          $current_user_id = api_get_user_id();
 954          $topics_per_page = 5;
 955          $items_per_page = 3;
 956          $count_items = 0;
 957          $html_messages = '';
 958          $query_vars = array('id'=>$group_id,'topics_page_nr'=>0);
 959  
 960          if (is_array($rows) && count($rows)> 0) {
 961                  // prepare array for topics with its items
 962                  $topics = array();
 963                  $x = 0;
 964                  foreach ($rows as $index=>$value) {
 965                      if (empty($value['parent_id'])) {
 966                          $x = $index;
 967                          $topics[$x] = $value;
 968                      } else {
 969                          $topics[$x]['items'][] = $value;
 970                      }
 971                  }
 972                  uasort($topics,array('MessageManager','order_desc_date'));
 973  
 974                  $param_names = array_keys($_GET);
 975                  $array_html = array();
 976                  foreach ($topics as $index => $topic) {
 977                      $html = '';
 978                      // topics
 979                      $indent    = 0;
 980                      $user_sender_info = UserManager::get_user_info_by_id($topic['user_sender_id']);
 981                      $files_attachments = self::get_links_message_attachment_files($topic['id']);
 982                      $name = api_get_person_name($user_sender_info['firstname'], $user_sender_info['lastname']);
 983  
 984                      $html .= '<div class="social-box-container2 " >';
 985                          $html .= '<div class="social-box-content2 quiz_content_actions">';
 986                              $html .= '<a href="#" class="head" id="head_'.$topic['id'].'">';
 987                              $html .= '<span class="message-group-title-topic">'.(((isset($_GET['anchor_topic']) && $_GET['anchor_topic'] == 'topic_'.$topic['id']) || in_array('items_'.$topic['id'].'_page_nr',$param_names))?Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align: middle')):
 988                                          Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align: middle'))).'
 989                                          '.Security::remove_XSS($topic['title']).'</span>';
 990                              $html .= '</a>';
 991  
 992                              if ($topic['send_date']!=$topic['update_date']) {
 993                                  if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00' ) {
 994                                      $html .= '<span class="message-group-date" > ('.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).')</span>';
 995                                  }
 996                              } else {
 997                                      $html .= '<span class="message-group-date" > ('.get_lang('Created').' '.date_to_str_ago($topic['send_date']).')</span>';
 998                              }
 999  
1000                              $html .= '<div id="topic_'.$topic['id'].'" >';
1001                                  $html .= '<a name="topic_'.$topic['id'].'"></a>';
1002                                  $html.= '<div style="margin-bottom:10px">';
1003                                      $html.= '<div id="message-reply-link" style="margin-right:10px">
1004                                              <a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=390&width=610&&user_friend='.$current_user_id.'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=reply_message_group&anchor_topic=topic_'.$topic['id'].'&topics_page_nr='.intval($_GET['topics_page_nr']).'&items_page_nr='.intval($_GET['items_page_nr']).'" class="thickbox" title="'.get_lang('Reply').'">'.Display :: return_icon('pixel.gif', get_lang('Reply'),array('class'=>'actionplaceholdericon actionforum')).'</a>';
1005  
1006                                      if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $topic['user_sender_id'] == $current_user_id) {
1007                                          $html.= '&nbsp;&nbsp;<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=390&width=610&&user_friend='.$current_user_id.'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=edit_message_group&anchor_topic=topic_'.$topic['id'].'&topics_page_nr='.intval($_GET['topics_page_nr']).'&items_page_nr='.intval($_GET['items_page_nr']).'" class="thickbox" title="'.get_lang('Edit').'">'.Display :: return_icon('pixel.gif', get_lang('Edit'),array('class'=>'actionplaceholdericon actionedit')).'</a>';
1008                                      }
1009  
1010                                      $html.=    '</div>';
1011                                      $html.= '<br />';
1012                                      $html.= '<div class="message-group-author">'.get_lang('From').'&nbsp;<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
1013                                      $html.= '<div class="message-group-content">'.$topic['content'].'</div>';
1014                                      $html.= '<div class="message-attach">'.(!empty($files_attachments)?implode('&nbsp;|&nbsp;',$files_attachments):'').'</div>';
1015                                  $html.= '</div>';
1016  
1017                      // items
1018                      if (is_array($topic['items'])) {
1019  
1020                          $items_page_nr = intval($_GET['items_'.$topic['id'].'_page_nr']);
1021                          $array_html_items = array();
1022                          foreach ($topic['items'] as $item) {
1023                              $html_items = '';
1024                              $user_sender_info = UserManager::get_user_info_by_id($item['user_sender_id']);
1025                              $files_attachments = self::get_links_message_attachment_files($item['id']);
1026                              $name = api_get_person_name($user_sender_info['firstname'], $user_sender_info['lastname']);
1027  
1028                              $html_items.= '<div class="social-box-container3" >';
1029                                  $html_items .= '<div class="social-box-content3 quiz_content_actions">';
1030                                  $html_items.= '<div id="message-reply-link">';
1031  
1032                                  $html_items.=    '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=390&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&message_id='.$item['id'].'&action=reply_message_group&anchor_topic=topic_'.$topic['id'].'&topics_page_nr='.intval($_GET['topics_page_nr']).'&items_page_nr='.intval($items_page_nr).'&topic_id='.$topic['id'].'" class="thickbox" title="'.get_lang('Reply').'">'.Display :: return_icon('pixel.gif', get_lang('Reply'),array('class'=>'actionplaceholdericon actionforum')).'</a>';
1033  
1034                                  if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $item['user_sender_id'] == $current_user_id) {
1035                                      $html_items.= '&nbsp;&nbsp;<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=390&width=610&&user_friend='.$current_user_id.'&group_id='.$group_id.'&message_id='.$item['id'].'&action=edit_message_group&anchor_topic=topic_'.$topic['id'].'&topics_page_nr='.intval($_GET['topics_page_nr']).'&items_page_nr='.intval($items_page_nr).'&topic_id='.$topic['id'].'" class="thickbox" title="'.get_lang('Edit').'">'.Display :: return_icon('pixel.gif', get_lang('Edit'),array('class'=>'actionplaceholdericon actionedit')).'</a>';
1036                                  }
1037                                  $html_items.= '</div>';
1038                                  $html_items.= '<div class="message-group-title">'.Security::remove_XSS($item['title']).'&nbsp;</div>';
1039                                  $html_items.= '<div class="message-group-author">'.get_lang('From').'&nbsp;<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$item['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
1040                                  $html_items.= '<div class="message-group-content">'.$item['content'].'</div>';
1041  
1042                                  if ($item['send_date'] != $item['update_date']) {
1043                                      if (!empty($item['update_date']) && $item['update_date'] != '0000-00-00 00:00:00' ) {
1044                                          $html_items .= '<div class="message-group-date"> '.get_lang('LastUpdate').' '.date_to_str_ago($item['update_date']).'</div>';
1045                                      }
1046                                  } else {
1047                                      $html_items .= '<div class="message-group-date"> '.get_lang('Created').' '.date_to_str_ago($item['send_date']).'</div>';
1048                                  }
1049  
1050                                  $html_items.= '<div class="message-attach">'.(!empty($files_attachments)?implode('&nbsp;|&nbsp;',$files_attachments):'').'</div>';
1051                                  $html_items.= '</div>';
1052                              $html_items.= '</div>';
1053                              $array_html_items[] = array($html_items);
1054                          }
1055                          // grids for items with paginations
1056                          $html .= Display::return_sortable_grid('items_'.$topic['id'], array(), $array_html_items, array('hide_navigation'=>false, 'per_page' => $items_per_page), $query_vars, false, array(true, true, true,false), false);
1057                      }
1058                              $html .= '</div>';
1059                          $html .= '</div>';
1060                      $html .= '</div>';
1061                      $array_html[] = array($html);
1062                  }
1063                  // grids for items and topics  with paginations
1064  
1065                  $html_messages .= '<div class="social-box-container2">';
1066                  $html_messages .= Display::return_sortable_grid('topics', array(), $array_html, array('hide_navigation'=>false, 'per_page' => $topics_per_page), $query_vars, false, array(true, true, true,false), false);
1067                  $html_messages .= '</div>';
1068          }
1069  
1070          return $html_messages;
1071      }
1072  
1073      /**
1074       * Add children to messages by id is used for nested view messages
1075       * @param array  rows of messages
1076       * @return array new list adding the item children
1077       */
1078  	public static function calculate_children($rows) {
1079  
1080          foreach($rows as $row) {
1081              $rows_with_children[$row["id"]]=$row;
1082              $rows_with_children[$row["parent_id"]]["children"][]=$row["id"];
1083          }
1084          $rows=$rows_with_children;
1085          $sorted_rows=array(0=>array());
1086          self::message_recursive_sort($rows, $sorted_rows);
1087          unset($sorted_rows[0]);
1088          return $sorted_rows;
1089      }
1090  
1091      /**
1092       * Sort recursively the messages, is used for for nested view messages
1093       * @param array  original rows of messages
1094       * @param array  list recursive of messages
1095       * @param int   seed for calculate the indent
1096       * @param int   indent for nested view
1097       * @return void
1098       */
1099  	public static function message_recursive_sort($rows, &$messages, $seed=0, $indent=0) {
1100          if($seed>0) {
1101              $messages[$rows[$seed]["id"]]=$rows[$seed];
1102              $messages[$rows[$seed]["id"]]["indent_cnt"]=$indent;
1103              $indent++;
1104          }
1105          if(isset($rows[$seed]["children"])) {
1106              foreach($rows[$seed]["children"] as $child) {
1107                  self::message_recursive_sort($rows, $messages, $child, $indent);
1108              }
1109          }
1110      }
1111  
1112      /**
1113       * Sort date by desc from a multi-dimensional array
1114       * @param array1  first array to compare
1115       * @param array2  second array to compare
1116       * @return bool
1117       */
1118  	public function order_desc_date($array1,$array2) {
1119          return strcmp($array2['send_date'],$array1['send_date']);
1120      }
1121  
1122      /**
1123       * Get array of links (download) for message attachment files
1124       * @param int          message id
1125       * @param string    type message list (inbox/outbox)
1126       * @return array
1127       */
1128  	public static function get_links_message_attachment_files($message_id,$type='') {
1129  
1130          $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1131          $message_id = intval($message_id);
1132  
1133          // get file attachments by message id
1134          $links_attach_file = array();
1135          if (!empty($message_id)) {
1136  
1137              $sql = "SELECT * FROM $tbl_message_attach WHERE message_id = '$message_id'";
1138  
1139              $rs_file = Database::query($sql);
1140              if (Database::num_rows($rs_file) > 0) {
1141                  $attach_icon = Display::return_icon('attachment.gif');
1142  
1143                  $archiveURL=api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
1144  
1145                  while ($row_file = Database::fetch_array($rs_file)) {
1146                      $archiveFile= $row_file['path'];
1147                      $filename     = $row_file['filename'];
1148                      $filesize     = format_file_size($row_file['size']);
1149                      $filecomment= $row_file['comment'];
1150                      $links_attach_file[] = $attach_icon.'&nbsp;<a href="'.$archiveURL.$archiveFile.'">'.$filename.'</a>&nbsp;('.$filesize.')'.(!empty($filecomment)?'&nbsp;-&nbsp;'.$filecomment:'');
1151                  }
1152              }
1153          }
1154          return $links_attach_file;
1155      }
1156  
1157      /**
1158       * Get message list by id
1159       * @param int  message id
1160       * @return array
1161       */
1162  	public static function get_message_by_id($message_id) {
1163          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1164          $message_id = intval($message_id);
1165          $sql = "SELECT * FROM $tbl_message WHERE id = '$message_id'";
1166          $res = Database::query($sql);
1167          $item = array();
1168          if (Database::num_rows($res)>0) {
1169              $item = Database::fetch_array($res,'ASSOC');
1170          }
1171          return $item;
1172      }
1173      /**
1174       *
1175       * Checks if there is a new chat invitation
1176       * @param integer $user_receiver_id
1177       */
1178  	public static function check_for_new_chat_invitation ($user_sender_id, $user_receiver_id) {
1179          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1180          $sql = "SELECT COUNT(*) as count FROM $tbl_message WHERE user_sender_id = '".Database::escape_string($user_sender_id)."' AND user_receiver_id = '".Database::escape_string($user_receiver_id)."' AND msg_status = '10'";
1181          $rs = Database::query($sql, __FILE__,__LINE__);
1182          $row = Database::fetch_array($rs,'ASSOC');
1183          return $row['count'];
1184      }
1185      /**
1186       *
1187       * Add a new chat invitation
1188       * @param integer $user_sender
1189       * @param integer $user_receiver
1190       */
1191  	public static function add_new_chat_invitation ($user_sender_id, $user_receiver_id) {
1192          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1193          if (self::check_for_new_chat_invitation($user_sender_id,$user_receiver_id) == 0) {
1194              $user_info = api_get_user_info($user_sender_id);
1195              $full_name = $user_info['firstName'].' '.$user_info['lastName'];
1196              $content = array('content' => get_lang('YouHaveReceivedAChatInvitationOf').' '.$full_name,
1197                               'cidReq' => api_get_course_id());
1198              $content = (object)$content;
1199              $content = serialize($content);
1200              $sql = "INSERT INTO $tbl_message (user_sender_id,user_receiver_id,msg_status,send_date,title,content,group_id,parent_id)
1201              VALUES('".Database::escape_string($user_sender_id)."','".Database::escape_string($user_receiver_id)."','10',
1202              '".date('Y-m-d H:i:s',time())."','".get_lang('MessageChatInvitationTitle')."','".$content."','0','0')";
1203              $rs = Database::query($sql, __FILE__, __LINE__);
1204              if ($rs !== false) {
1205                return true;
1206              } else {
1207                return false;
1208              }
1209  
1210          } else {
1211              return false;
1212          }
1213      }
1214      /**
1215       *
1216       * Decline the chat invitation
1217       * @param integer $user_sender_id
1218       * @param integer $user_receiver_id
1219       */
1220  	public static function decline_chat_invitation ($user_sender_id, $user_receiver_id) {
1221          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1222          $sql = "UPDATE $tbl_message SET msg_status = '11' WHERE msg_status = '10' AND user_sender_id = '".Database::escape_string($user_sender_id)."' AND
1223          user_receiver_id = '".Database::escape_string($user_receiver_id)."'";
1224          $rs = Database::query($sql, __FILE__, __LINE__);
1225          return $rs;
1226      }
1227      /**
1228       *
1229       * Accept the chat invitation
1230       * @param integer $user_sender_id
1231       * @param integer $user_receiver_id
1232       */
1233  	public static function accept_chat_invitation ($user_sender_id, $user_receiver_id) {
1234          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1235          $sql = "UPDATE $tbl_message SET msg_status = '12' WHERE user_sender_id = '".Database::escape_string($user_sender_id)."' AND
1236          user_receiver_id = '".Database::escape_string($user_receiver_id)."'";
1237          $rs = Database::query($sql, __FILE__, __LINE__);
1238          return $rs;
1239      }
1240      /**
1241       *
1242       * Get the chat notifications of an user
1243       * @param integer $user_receiver_id
1244       * @param date $date
1245       */
1246  	public static function get_chat_notifications ($user_receiver_id, $date) {
1247          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1248          $sql = "SELECT title,content,user_sender_id FROM $tbl_message m WHERE msg_status = '10' AND user_receiver_id = '".Database::escape_string($user_receiver_id)."'";
1249          $rs = Database::query($sql, __FILE__,__LINE__);
1250          $chat_notification_list = array();
1251          while ($row = Database::fetch_array($rs,'ASSOC')) {
1252              $chat_notification_list[] = $row;
1253          }
1254          return $chat_notification_list;
1255      }
1256      /**
1257       *
1258       * Display the chat notifications
1259       * @param array $chat_notification_list
1260       */
1261  	public static function return_chat_notifications ($chat_notification_list) {
1262          $return = '';
1263          $buttons = '<div align="center"><a class="accept_chat" href="javascript:void(0)" id="%s_accept_%s">'.Display::return_icon('checkok.png', get_lang('Accept')).get_lang('Accept').'</a>&nbsp;&nbsp;&nbsp;<a class="decline_chat" href="javascript:void(0)" id="%s_decline_%s">'.Display::return_icon('delete.png', get_lang('Decline')).get_lang('Decline').'</a></div>';
1264          foreach ($chat_notification_list as $chat_notification) {
1265               $message_info = unserialize($chat_notification['content']);
1266               $message_content = $message_info->content;
1267               $course_id = $message_info->cidReq;
1268               $return.="$.jGrowl('".$message_content.'<br/>'.sprintf($buttons,$course_id,$chat_notification['user_sender_id'],$course_id,$chat_notification['user_sender_id'])."',
1269               {header: '".$chat_notification['title']."',growlId:'notification_".$chat_notification['user_sender_id']."',sticky: true});".PHP_EOL;
1270          }
1271          return $return;
1272      }
1273  
1274  	public static function display_chat_notifications () {
1275          global $htmlHeadXtra;
1276          $htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jgrowl-1.1.2/jquery.jgrowl.js" language="javascript"></script>';
1277          $htmlHeadXtra[] = '<link rel="stylesheet" type="text/css" href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jgrowl-1.1.2/jquery.jgrowl.css" />';
1278          // Variables
1279          $message_notification_list = array();
1280          $message_notification_list = self::get_chat_notifications(api_get_user_id(), date('Y-m-d'));
1281          $count_chat_notifications = count($message_notification_list);
1282          // Display the jquery chat notification.
1283          if ($count_chat_notifications > 0) {
1284          $htmlHeadXtra[] ='<script type="text/javascript">
1285          $(document).ready(function(){
1286            // Display the jquery messages
1287            $.jGrowl.defaults.position = "center";
1288            '.self::return_chat_notifications($message_notification_list).'
1289  
1290              // Accept the chat invitation
1291              $(".accept_chat").click(function(){
1292                  var id = $(this).attr("id");
1293                  var user_data = new Array();
1294                  var user_info = id.split("_accept_");
1295                  _user_sender_id = user_info[1];// Get the user(sender) ID
1296                  _course_id = user_info[0];// Get the course ID
1297                  $.ajax({
1298                      type: "GET",
1299                      url: "'.api_get_path(WEB_PATH).'main/user/user_ajax_requests.php?cidReq="+_course_id+"&action=accept&user_sender_id="+_user_sender_id,
1300                      success: function(msg){
1301                        // Open chat
1302                        window.open("'.api_get_path(WEB_PATH).'main/chat/chat.php?cidReq="+_course_id+"&send_invitation=false","window_chat",config="height=500, width=925, left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no");
1303                        var notification_id = "#notification_"+_user_sender_id;
1304                        $("div#" + notification_id).trigger("jGrowl.close").remove();
1305                      }
1306                  })
1307              });
1308  
1309              // Decline the chat invitation
1310              $(".decline_chat").click(function(){
1311                  var id = $(this).attr("id");
1312                  var user_data = new Array();
1313                  var user_info = id.split("_decline_");
1314                  _user_sender_id = user_info[1];// Get the user(sender) ID
1315                  _course_id = user_info[0];// Get the course ID
1316  
1317                  $.ajax({
1318                      type: "GET",
1319                      url: "'.api_get_path(WEB_PATH).'main/user/user_ajax_requests.php?cidReq="+_course_id+"&action=decline&user_sender_id="+_user_sender_id,
1320                      success: function(msg){
1321                        var notification_id = "#notification_"+_user_sender_id;
1322                        $("div#" + notification_id).trigger("jGrowl.close").remove();
1323                      }
1324                  })
1325              });
1326          });
1327          </script> ';
1328          }
1329      }
1330  
1331      /**
1332       *
1333       * Checks if our chat invitations was declined
1334       * @param inetegr $user_sender_id
1335       */
1336  	public static function check_if_chat_invitations_was_declined ($user_sender_id) {
1337          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1338          $return = false;
1339          $sql = "SELECT count(*) as count FROM $tbl_message WHERE user_sender_id = '".Database::escape_string($user_sender_id)."' AND msg_status=11";
1340          $rs = Database::query($sql, __FILE__, __LINE__);
1341          $row = Database::fetch_array($rs,'ASSOC');
1342          if ($row['count'] > 0) {
1343            $return = true;
1344          }
1345          return $return;
1346      }
1347      /**
1348       *
1349       * Get user information of who have declined the chat invitation
1350       * @param integer $user_sender_id
1351       */
1352  	public static function get_users_who_declined_chat_invitation ($user_sender_id) {
1353          $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1354          $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1355  
1356          $sql = "SELECT id,u.lastname,u.firstname,u.username  FROM $tbl_message m INNER JOIN $tbl_user u ON m.user_receiver_id=u.user_id  WHERE m.user_sender_id = '".Database::escape_string($user_sender_id)."' AND m.msg_status='11'";
1357          $rs = Database::query($sql, __FILE__, __LINE__);
1358          $user_invitation_info = array();
1359          while ($row = Database::fetch_array($rs, 'ASSOC')) {
1360              $user_invitation_info[] = $row;
1361          }
1362          return $user_invitation_info;
1363      }
1364  }
1365  
1366  
1367  //@todo this functions should be in the message class
1368  
1369  function inbox_display() {
1370      global $charset;
1371  //    $charset = api_get_setting('platform_charset');
1372      $table_message = Database::get_main_table(TABLE_MESSAGE);
1373      $request=api_is_xml_http_request();
1374      if ($_SESSION['social_exist']===true) {
1375          if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
1376              $success= get_lang('SelectedMessagesDeleted');
1377          } else {
1378              $success= get_lang('SelectedMessagesDeleted');
1379          }
1380      } else {
1381          $success= get_lang('SelectedMessagesDeleted');
1382      }
1383      if (isset ($_REQUEST['action'])) {
1384          switch ($_REQUEST['action']) {
1385              case 'delete' :
1386                  $number_of_selected_messages = count($_POST['id']);
1387                  foreach ($_POST['id'] as $index => $message_id) {
1388                      MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1389                  }
1390                  Display::display_normal_message(api_xml_http_response_encode($success),false);
1391                  break;
1392              case 'deleteone' :
1393                  MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1394                  Display::display_confirmation_message(api_xml_http_response_encode($success),false);
1395                  echo '<br />';
1396                  break;
1397          }
1398      }
1399      // display sortable table with messages of the current user
1400      //$table = new SortableTable('messages', 'get_number_of_messages_mask', 'get_message_data_mask', 3, get_number_of_messages_mask(),'DESC');
1401      $table = new SortableTable('message_inbox', array('MessageManager','get_number_of_messages'), array('MessageManager','get_message_data'),3,20,'DESC');
1402      $table->set_header(0, '', false,array ('style' => 'width:20px;'));
1403      $title=api_xml_http_response_encode(get_lang('Title'));
1404      $action=api_xml_http_response_encode(get_lang('Actions'));
1405  
1406      $table->set_header(1,api_xml_http_response_encode(get_lang('From')),true, "align='left'");
1407      $table->set_header(2,$title,true);
1408      $table->set_header(3,api_xml_http_response_encode(get_lang('Date')),true, array('style' => 'width:150px;', 'align'=>'left'));
1409      $table->set_header(4,$action,false,array ('style' => 'width:70px;','align'=>'left'));
1410  
1411      if ($_REQUEST['f']=='social') {
1412          $parameters['f'] = 'social';
1413          $table->set_additional_parameters($parameters);
1414      }
1415  
1416      echo '<div id="div_content_table_data">';
1417      if ($request===true) {
1418          echo '<form name="form_send" id="form_send" action="" method="post">';
1419          echo '<input type="hidden" name="action" value="delete" />';
1420          $table->display();
1421          echo '</form>';
1422          if (get_number_of_messages_mask() > 0) {
1423              echo '<a href="javascript:void(0)" onclick="selectall_cheks()">'.api_xml_http_response_encode(get_lang('SelectAll')).'</a>&nbsp;&nbsp;&nbsp;';
1424              echo '<a href="javascript:void(0)" onclick="unselectall_cheks()">'.api_xml_http_response_encode(get_lang('UnSelectAll')).'</a>&nbsp;&nbsp;&nbsp;';
1425              echo '<button class="save" name="delete" type="button" value="'.api_xml_http_response_encode(get_lang('DeleteSelectedMessages')).'" onclick="submit_form(\'inbox\')">'.api_xml_http_response_encode(get_lang('DeleteSelectedMessages')).'</button>';
1426  
1427          }
1428      } else {
1429          $table->set_form_actions(array ('delete' => get_lang('DeleteSelectedMessages')));
1430          $table->display();
1431      }
1432      echo '</div>';
1433  }
1434  function get_number_of_messages_mask() {
1435      return MessageManager::get_number_of_messages();
1436  }
1437  function get_message_data_mask($from, $number_of_items, $column, $direction) {
1438      $column='3';
1439      $direction='DESC';
1440      //non set by SortableTable ?
1441      $number_of_items=get_number_of_messages_mask();
1442      return MessageManager::get_message_data($from, $number_of_items, $column, $direction);
1443  }
1444  function outbox_display() {
1445      $table_message = Database::get_main_table(TABLE_MESSAGE);
1446      $request=api_is_xml_http_request();
1447      global $charset;
1448  
1449      $social_link = false;
1450      if ($_REQUEST['f']=='social') {
1451          $social_link ='f=social';
1452      }
1453      if ($_SESSION['social_exist']===true) {
1454          if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
1455              $success= get_lang('SelectedMessagesDeleted')."&nbsp<br><a href=\""."../social/index.php?$social_link\">".get_lang('BackToOutbox')."</a>";
1456          }else {
1457              $success=get_lang('SelectedMessagesDeleted')."&nbsp<br><a href=\""."../social/index.php?$social_link\">".get_lang('BackToOutbox')."</a>";
1458          }
1459      } else {
1460          $success= get_lang('SelectedMessagesDeleted').'&nbsp</b><br /><a href="outbox.php?'.$social_link.'">'.get_lang('BackToOutbox').'</a>';
1461      }
1462      if (isset ($_REQUEST['action'])) {
1463          switch ($_REQUEST['action']) {
1464              case 'delete' :
1465              $number_of_selected_messages = count($_POST['id']);
1466              if ($number_of_selected_messages!=0) {
1467                  foreach ($_POST['id'] as $index => $message_id) {
1468                      MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1469                  }
1470              }
1471              Display::display_normal_message(api_xml_http_response_encode($success),false);
1472              break;
1473              case 'deleteone' :
1474              MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1475              Display::display_confirmation_message(api_xml_http_response_encode($success),false);
1476              echo '<br/>';
1477              break;
1478          }
1479      }
1480  
1481      // display sortable table with messages of the current user
1482      //$table = new SortableTable('messages', 'get_number_of_messages_send_mask', 'get_message_data_send_mask', 3, get_number_of_messages_send_mask(), 'DESC');
1483      $table = new SortableTable('message_outbox', array('MessageManager','get_number_of_messages_sent'), array('MessageManager','get_message_data_sent'),3,20,'DESC');
1484  
1485      $parameters['f'] = Security::remove_XSS($_GET['f']);
1486      $table->set_additional_parameters($parameters);
1487      $table->set_header(0, '', false,array ('style' => 'width:20px;'));
1488      $title = api_xml_http_response_encode(get_lang('Title'));
1489      $action= api_xml_http_response_encode(get_lang('Actions'));
1490  
1491      $table->set_header(1, api_xml_http_response_encode(get_lang('To')),true,"align='left'");
1492      $table->set_header(2, $title,true,"align='left'");
1493      $table->set_header(3, api_xml_http_response_encode(get_lang('Date')),true,array ('style' => 'width:150px;','align'=>'left'));
1494      $table->set_header(4,$action, false,array ('style' => 'width:70px;'));
1495  
1496      /*
1497      if ($_REQUEST['f']=='social') {
1498          $parameters['f'] = 'social';
1499          $table->set_additional_parameters($parameters);
1500      }
1501      */
1502  
1503      echo '<div id="div_content_table_data_sent">';
1504  
1505          if ($request===true) {
1506              echo '<form name="form_send_out" id="form_send_out" action="" method="post">';
1507  
1508              echo '<input type="hidden" name="action" value="delete" />';
1509  
1510              $table->display();
1511              echo '</form>';
1512              if (get_number_of_messages_send_mask() > 0) {
1513                  echo '<a href="javascript:void(0)" onclick="selectall_cheks()">'.api_xml_http_response_encode(get_lang('SelectAll')).'</a>&nbsp;&nbsp;&nbsp;';
1514                  echo '<a href="javascript:void(0)" onclick="unselectall_cheks()">'.api_xml_http_response_encode(get_lang('UnSelectAll')).'</a>&nbsp;&nbsp;&nbsp;';
1515                  echo '<button class="save" name="delete" type="button" value="'.api_xml_http_response_encode(get_lang('DeleteSelectedMessages')).'" onclick="submit_form(\'outbox\')">'.api_xml_http_response_encode(get_lang('DeleteSelectedMessages')).'</button>';
1516              }
1517          } else {
1518              $table->set_form_actions(array ('delete' => get_lang('DeleteSelectedMessages')));
1519              $table->display();
1520          }
1521      echo '</div>';
1522  }
1523  function get_number_of_messages_send_mask() {
1524      return MessageManager::get_number_of_messages_sent();
1525  }
1526  function get_message_data_send_mask($from, $number_of_items, $column, $direction) {
1527      $column='3';
1528      $direction='desc';
1529      //non set by SortableTable ?
1530      $number_of_items=get_number_of_messages_send_mask();
1531      return MessageManager::get_message_data_sent($from, $number_of_items, $column, $direction);
1532  }
1533  ?>

title

Description

title

Description

title

Description

title

title

Body