Dokeos PHP Cross Reference Learning Management Systems

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

title

Description

title

Description

title

Description

title

title

Body