';
		echo ''.Display::return_icon('folder_up.gif',api_xml_http_response_encode(get_lang('BackToOutbox'))).api_xml_http_response_encode(get_lang('BackToOutbox')).'';
		echo ''.Display::return_icon('delete.png',api_xml_http_response_encode(get_lang('DeleteMessage'))).api_xml_http_response_encode(get_lang('DeleteMessage')).'';
		echo '
';
		echo '
		
		    
		      |    | 
		      
		      	
		            
		              | 
		                     |   '.str_replace("\\","",api_xml_http_response_encode($row[5])).' 
		              
		              
		              	| '.api_xml_http_response_encode(get_lang('From').' '.GetFullUserName($row[1]).' '.api_strtolower(get_lang('To')).'   '.GetFullUserName($row[2])).'  | 
		               
		              
		              | '.api_xml_http_response_encode(get_lang('Date').'  '.$row[4]).' | 
		               
		            
		         
		         
		        
		          
		            
		              | '.str_replace("\\","",api_xml_http_response_encode($row[6])).' | 
		             
		          
		         
		        '.(!empty($files_attachments)?implode(' | ',$files_attachments):'').' 
		           | 
		        | 
		    
		
';
	}
	/**
	 * get user id by user email
	 * @param string $user_email
	 * @return int user id
	 */
	public static function get_user_id_by_email($user_email) {
		$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
		$sql='SELECT user_id FROM '.$tbl_user.' WHERE email="'.Database::escape_string($user_email).'";';
		$rs=Database::query($sql);
		$row=Database::fetch_array($rs,'ASSOC');
		if (isset($row['user_id'])) {
			return $row['user_id'];
		} else {
			return null;
		}
	}
	/**
	 * Displays messages of a group with nested view
	 * @param int group id
	 */
	public static function display_messages_for_group($group_id) {
		global $my_group_role;
		$rows = self::get_messages_by_group($group_id);		 
		//$rows = self::calculate_children($rows);
		$group_info = GroupPortalManager::get_group_data($group_id);
		$current_user_id = api_get_user_id();
		$topics_per_page  = 10;
		
		$count_items = 0;
		$html_messages = '';
		$query_vars = array('id'=>$group_id, 'topics_page_nr'=>0);
		if (is_array($rows) && count($rows)> 0) {
			// prepare array for topics with its items
			$topics = array();
			$x = 0;
			foreach ($rows as $index=>$value) {
				if (empty($value['parent_id'])) {
					$x = $index;
					$topics[$x] = $value;
				} else {
					$topics[$x]['items'][] = $value;
				}
			}
			uasort($topics,array('MessageManager','order_desc_date'));
			$param_names = array_keys($_GET);
			$array_html = array();
			foreach ($topics as $index => $topic) {
				$html = '';
				// topics
				$indent	= 0;
				$user_sender_info = UserManager::get_user_info_by_id($topic['user_sender_id']);
				$files_attachments = self::get_links_message_attachment_files($topic['id']);
				$name = api_get_person_name($user_sender_info['firstname'], $user_sender_info['lastname']);
				$html .= '';
				    $items = count($topic['items']);
				    $reply_label = ($items == 1) ? get_lang('Reply'): get_lang('Replies'); 
				    $html .= Display::div(Display::tag('span', $items).$reply_label, array('class' =>'group_discussions_replies'));
				        $topic['title'] = trim($topic['title']);
				        
				        if (empty($topic['title'])) {
				            $topic['title'] = get_lang('Untitled');
				        } 				
				        $title = Display::url('
'.Security::remove_XSS($topic['title']).'
', 'group_topics.php?id='.$group_id.'&topic_id='.$topic['id']);
                                                
                        $date = '';
                        $link = '';
						if ($topic['send_date']!=$topic['update_date']) {
							if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00' ) {
								$date .= '
 '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'
';
							}
						} else {
                            $date .= '
 '.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'
';
						}
							
						/*$link = '
';	
						*/							
						$image_path = UserManager::get_user_picture_path_by_id($topic['user_sender_id'], 'web', false, true);							
						$image_repository = $image_path['dir'];
						$existing_image = $image_path['file'];
						$user_image = '
';
						$user = '
'.$name.' ';
						
						//$html.= '
'.$user.$date.$topic['content'].$link.'
';
						 
						$html .= Display::div($title.cut($topic['content'], 350).$user_image.$user.$date.$link, array('class'=>'group_discussions_info'));
						
						//$html.= '
'.(!empty($files_attachments)?implode(' | ',$files_attachments):'').'
';
					
				
				$html .= '
 '; //rounded_div
				
				$array_html[] = array($html);
			}
			// grids for items and topics  with paginations
			$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);
		}
		return $html_messages;
	}
	
	
/**
     * Displays messages of a group with nested view
     * @param int group id
     */
    public static function display_message_for_group($group_id, $message_id, $is_member) {
        global $my_group_role;
        
        $main_message = self::get_message_by_id($message_id);
                
        $group_info = GroupPortalManager::get_group_data($group_id);
        $rows = self::get_messages_by_group_by_message($group_id, $message_id);            
        $rows = self::calculate_children($rows, $message_id);                
        
        $current_user_id = api_get_user_id();
        $topics_per_page  = 5;
        $items_per_page   = 100;
        $count_items = 0;
        $html_messages = '';
        $query_vars = array('id'=>$group_id, 'topic_id'=>$message_id , 'topics_page_nr'=>0);        
        
        
        // Main message        
        $html = '';              
        $user_link = '';
        $links = '';
        $main_content  = '';
        
        echo Display::tag('h2', $main_message['title']);
        $user_sender_info = UserManager::get_user_info_by_id($main_message['user_sender_id']);
        $files_attachments = self::get_links_message_attachment_files($main_message['id']);
        $name = api_get_person_name($user_sender_info['firstname'], $user_sender_info['lastname']);
            
        $links.= '';
                                
        $image_path = UserManager::get_user_picture_path_by_id($main_message['user_sender_id'], 'web', false, true);                                
        $image_repository = $image_path['dir'];
        $existing_image = $image_path['file'];
        $main_content.= '';
        $user_link = ''.$name.' ';
        
        $date = '';
        if ($main_message['send_date'] != $main_message['update_date']) {
            if (!empty($main_message['update_date']) && $main_message['update_date'] != '0000-00-00 00:00:00' ) {
                $date  = ' '.get_lang('LastUpdate').' '.date_to_str_ago($main_message['update_date']).'
';
            }
        } else {
            $date = ' '.get_lang('Created').' '.date_to_str_ago($main_message['send_date']).'
';
        }
        $attachment = ''.(!empty($files_attachments)?implode(' | ',$files_attachments):'').'
';                
        $main_content.= ''.$links.$user_link.' '.$date.$main_message['content'].$attachment.'
';          
        $html = '';   
        
        $html .= Display::div(Display::div(Display::div($main_content, array('class'=>'group_social_sub_item', 'style'=>'background-color:#fff;')), array('class' => 'group_social_item')), array('class' => 'group_social_grid'));
        
        $topic_id = $main_message['id'];
        
        if (is_array($rows) && count($rows)> 0) {
            $topics = $rows;            
            $array_html = array();            
            foreach ($topics as $index => $topic) {
                if (empty($topic['id'])) {
                    continue;
                }
                $items_page_nr = intval($_GET['items_'.$topic['id'].'_page_nr']);                
                  
                $user_link = '';
                $links = '';
                $html_items = '';
                $user_sender_info = UserManager::get_user_info_by_id($topic['user_sender_id']);
                $files_attachments = self::get_links_message_attachment_files($topic['id']);
                $name = api_get_person_name($user_sender_info['firstname'], $user_sender_info['lastname']);
                    
                $links.= '';
                                        
                $image_path = UserManager::get_user_picture_path_by_id($topic['user_sender_id'], 'web', false, true);                                
                $image_repository = $image_path['dir'];
                $existing_image = $image_path['file'];
                $html_items.= '';
                $user_link = ''.$name.' ';
                
                $date = '';
                if ($topic['send_date'] != $topic['update_date']) {
                    if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00' ) {
                        $date  = ' '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'
';
                    }
                } else {
                    $date = ' '.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'
';
                }
                $attachment = ''.(!empty($files_attachments)?implode(' | ',$files_attachments):'').'
';                
                $html_items.= ''.$links.$user_link.' '.$date.$topic['content'].$attachment.'
';                          
                      
                
                if ($topic['indent_cnt'] == 0 || $topic['indent_cnt'] == 1) { 
                    $indent = 0;
                } else {
                    $indent = intval($topic['indent_cnt'])*20;
                }
                
                //var_dump($topic); 'style'=>'margin-left:'.$indent.'px'
                $html_items = Display::div($html_items, array('class' => 'group_social_sub_item'));
                $html_items = Display::div($html_items, array('class' => '', 'style'=>'margin-left:'.$indent.'px'));            
                $array_html_items[] = array($html_items);
            }                   
            // grids for items with paginations
            $options = array('hide_navigation'=>false, 'per_page' => $items_per_page);
            $order = array(true, true, true,false);          
            
            $style_class = array('item' => array('class'=>'group_social_item'), 'main' => array('class'=>'group_social_grid'));
            if (!empty($array_html_items)) {
                $html .= Display::return_sortable_grid('items_'.$topic['id'], array(), $array_html_items, $options, $query_vars, false, $order, false, $style_class);
            }
        }
        $html .= '';                
        $html = Display::div($html, array('class'=>'rounded_div', 'style'=>'width:638px'));
        return $html;
    }	
	
	/**
	 * Add children to messages by id is used for nested view messages
	 * @param array  rows of messages
	 * @return array new list adding the item children
	 */
	public static function calculate_children($rows, $first_seed) {
		foreach($rows as $row) {
			$rows_with_children[$row["id"]]=$row;
			$rows_with_children[$row["parent_id"]]["children"][]=$row["id"];
		}	    
		$rows=$rows_with_children;		
		$sorted_rows=array(0=>array());					
		self::message_recursive_sort($rows, $sorted_rows, $first_seed);		
		unset($sorted_rows[0]);
		return $sorted_rows;
	}
	/**
	 * Sort recursively the messages, is used for for nested view messages
	 * @param array  original rows of messages
	 * @param array  list recursive of messages
	 * @param int   seed for calculate the indent
	 * @param int   indent for nested view
	 * @return void
	 */
	public static function message_recursive_sort($rows, &$messages, $seed=0, $indent=0) {
		if ($seed > 0) {		    
			$messages[$rows[$seed]["id"]]=$rows[$seed];
			$messages[$rows[$seed]["id"]]["indent_cnt"]=$indent;
			$indent++;
		}
		
		if (isset($rows[$seed]["children"])) {		    
			foreach($rows[$seed]["children"] as $child) {			    
				self::message_recursive_sort($rows, $messages, $child, $indent);
			}
		}
	}
	/**
	 * Sort date by desc from a multi-dimensional array
	 * @param array1  first array to compare
	 * @param array2  second array to compare
	 * @return bool
	 */
	public function order_desc_date($array1,$array2) {
		return strcmp($array2['send_date'],$array1['send_date']);
	}
	/**
	 * Get array of links (download) for message attachment files
	 * @param int  		message id
	 * @param string	type message list (inbox/outbox)
	 * @return array
	 */
	public static function get_links_message_attachment_files($message_id,$type='') {
		$tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
		$message_id = intval($message_id);
		// get file attachments by message id
		$links_attach_file = array();
		if (!empty($message_id)) {
			$sql = "SELECT * FROM $tbl_message_attach WHERE message_id = '$message_id'";
			$rs_file = Database::query($sql);
			if (Database::num_rows($rs_file) > 0) {
				$attach_icon = Display::return_icon('attachment.gif');
				$archiveURL=api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
				while ($row_file = Database::fetch_array($rs_file)) {
					$archiveFile= $row_file['path'];
					$filename 	= $row_file['filename'];
					$filesize 	= format_file_size($row_file['size']);
					$filecomment= $row_file['comment'];
					$links_attach_file[] = $attach_icon.' '.$filename.' ('.$filesize.')'.(!empty($filecomment)?' - '.$filecomment.'':'');
				}
			}
		}
		return $links_attach_file;
	}
	/**
	 * Get message list by id
	 * @param int  message id
	 * @return array
	 */
	public static function get_message_by_id($message_id) {
		$tbl_message = Database::get_main_table(TABLE_MESSAGE);
		$message_id = intval($message_id);
		$sql = "SELECT * FROM $tbl_message WHERE id = '$message_id'";
		$res = Database::query($sql);
		$item = array();
		if (Database::num_rows($res)>0) {
			$item = Database::fetch_array($res,'ASSOC');
		}
		return $item;
	}
}
//@todo this functions should be in the message class
function inbox_display() {
	global $charset;
//	$charset = api_get_system_encoding();
	$table_message = Database::get_main_table(TABLE_MESSAGE);
	//$request=api_is_xml_http_request();
	if ($_SESSION['social_exist']===true) {
		if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
			$success= get_lang('SelectedMessagesDeleted');
		} else {
			$success= get_lang('SelectedMessagesDeleted');
		}
	} else {
		$success= get_lang('SelectedMessagesDeleted');
	}
	if (isset ($_REQUEST['action'])) {
		switch ($_REQUEST['action']) {
			case 'delete' :
    			$number_of_selected_messages = count($_POST['id']);
    			foreach ($_POST['id'] as $index => $message_id) {
    				MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
    			}
    			Display::display_normal_message(api_xml_http_response_encode($success),false);
    			break;
			case 'deleteone' :
    			MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
    			Display::display_confirmation_message(api_xml_http_response_encode($success),false);
    			echo '
';
    			break;
		}
	}
	// display sortable table with messages of the current user
	//$table = new SortableTable('messages', 'get_number_of_messages_mask', 'get_message_data_mask', 3, get_number_of_messages_mask(),'DESC');
	$table = new SortableTable('message_inbox', array('MessageManager','get_number_of_messages'), array('MessageManager','get_message_data'),3,20,'DESC');
	$table->set_header(0, '', false,array ('style' => 'width:15px;'));
	$title=api_xml_http_response_encode(get_lang('Title'));
	$action=api_xml_http_response_encode(get_lang('Modify'));
	$table->set_header(1,api_xml_http_response_encode(get_lang('Messages')),false);
	//$table->set_header(2,$title,true);
	$table->set_header(2,api_xml_http_response_encode(get_lang('Date')),true, array('style' => 'width:160px;'));
	$table->set_header(3,$action,false,array ('style' => 'width:70px;'));
	if ($_REQUEST['f']=='social') {
		$parameters['f'] = 'social';
		$table->set_additional_parameters($parameters);
	}    
	$table->set_form_actions(array ('delete' => get_lang('DeleteSelectedMessages')));
	$table->display();	
}
function get_number_of_messages_mask() {
	return MessageManager::get_number_of_messages();
}
function get_message_data_mask($from, $number_of_items, $column, $direction) {
	$column='3';
	$direction='DESC';
	//non set by SortableTable ?
	$number_of_items=get_number_of_messages_mask();
	return MessageManager::get_message_data($from, $number_of_items, $column, $direction);
}
function outbox_display() {
	$table_message = Database::get_main_table(TABLE_MESSAGE);
	$request=api_is_xml_http_request();
	global $charset;
	$social_link = false;
	if ($_REQUEST['f']=='social') {
		$social_link ='f=social';
	}
	if ($_SESSION['social_exist']===true) {
		if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') {
			$success= get_lang('SelectedMessagesDeleted')." 
".get_lang('BackToOutbox')."";
		}else {
			$success=get_lang('SelectedMessagesDeleted')." 
".get_lang('BackToOutbox')."";
		}
	} else {
		$success= get_lang('SelectedMessagesDeleted').' 
'.get_lang('BackToOutbox').'';
	}
	if (isset ($_REQUEST['action'])) {
		switch ($_REQUEST['action']) {
			case 'delete' :
    			$number_of_selected_messages = count($_POST['id']);
    			if ($number_of_selected_messages!=0) {
    				foreach ($_POST['id'] as $index => $message_id) {
    					MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
    				}
    			}
    			Display::display_normal_message(api_xml_http_response_encode($success),false);
    			break;
			case 'deleteone' :
    			MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
    			Display::display_confirmation_message(api_xml_http_response_encode($success),false);
                echo '
';
			 break;
		}
	}
	// display sortable table with messages of the current user
	//$table = new SortableTable('messages', 'get_number_of_messages_send_mask', 'get_message_data_send_mask', 3, get_number_of_messages_send_mask(), 'DESC');
	$table = new SortableTable('message_outbox', array('MessageManager','get_number_of_messages_sent'), array('MessageManager','get_message_data_sent'),3,20,'DESC');
	$parameters['f'] = Security::remove_XSS($_GET['f']);
	$table->set_additional_parameters($parameters);
	$table->set_header(0, '', false,array ('style' => 'width:15px;'));
	$title = api_xml_http_response_encode(get_lang('Title'));
	$action= api_xml_http_response_encode(get_lang('Modify'));
	$table->set_header(1, api_xml_http_response_encode(get_lang('Messages')),false);
	//$table->set_header(2, $title,true);
	$table->set_header(2, api_xml_http_response_encode(get_lang('Date')),true,array ('style' => 'width:160px;'));
	$table->set_header(3,$action, false,array ('style' => 'width:70px;'));
	
	if ($request===true) {
		echo '';
		if (get_number_of_messages_send_mask() > 0) {
			echo ''.api_xml_http_response_encode(get_lang('SelectAll')).'   ';
			echo ''.api_xml_http_response_encode(get_lang('UnSelectAll')).'   ';
			echo '';
		}
	} else {
		$table->set_form_actions(array ('delete' => get_lang('DeleteSelectedMessages')));
		$table->display();
	}
	
}
function get_number_of_messages_send_mask() {
	return MessageManager::get_number_of_messages_sent();
}
function get_message_data_send_mask($from, $number_of_items, $column, $direction) {
	$column='3';
	$direction='desc';
	//non set by SortableTable ?
	$number_of_items=get_number_of_messages_send_mask();
	return MessageManager::get_message_data_sent($from, $number_of_items, $column, $direction);
}