# This patch file was generated by NetBeans IDE
# This patch can be applied using context Tools: Apply Diff Patch action on respective folder.
# It uses platform neutral UTF-8 encoding.
# Above lines and this line are ignored by the patching process.
Index: moodle/lang/en/message.php
--- moodle/lang/en/message.php Base (1.20)
+++ moodle/lang/en/message.php Locally Modified (Based On 1.20)
@@ -57,6 +57,7 @@
 $string['keywordssearchresults'] = 'Search results: {$a} messages found';
 $string['loggedin'] = 'Online';
 $string['loggedoff'] = 'Not online';
+$string['managecontacts'] = 'Manage contacts';
\ No newline at end of file
 $string['mailsent'] = 'Your message was sent via email.';
 $string['maxmessages'] = 'Maximum number of messages to show in the discussion history';
 $string['message'] = 'Message';
Index: moodle/lib/navigationlib.php
--- moodle/lib/navigationlib.php Base (1.141)
+++ moodle/lib/navigationlib.php Locally Modified (Based On 1.141)
@@ -1524,6 +1524,9 @@
             }
         }
 
+        $url = new moodle_url('/message/contacts_messages.php',array());
+        $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
+
         // Add a node to view the users notes if permitted
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
@@ -3145,6 +3148,13 @@
             }
         }
 
+        // Messaging
+        // TODO this is adding itself to the messaging settings for other people based on one's own setting
+        if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) {
+            $url = new moodle_url('/message/edit.php', array('id'=>$user->id, 'course'=>$course->id));
+            $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
+        }
+
         // View the roles settings
         if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
             $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
Index: moodle/message/contacts.php
--- moodle/message/contacts.php No Base Revision
+++ moodle/message/contacts.php Locally New
@@ -0,0 +1,117 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * A page displaying the user's contacts. Similar to index.php but not a popup.
+ *
+ * @package   moodlecore
+ * @copyright 2010 Andrew Davis
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require('../config.php');
+require('lib.php');
+
+require_login(0, false);
+
+if (isguestuser()) {
+    redirect($CFG->wwwroot);
+}
+
+if (empty($CFG->messaging)) {
+    print_error('disabled', 'message');
+}
+
+/// Optional variables that may be passed in
+//$tab            = optional_param('tab', 'contacts', PARAM_ALPHA); // current tab - default to contacts
+$addcontact     = optional_param('addcontact',     0, PARAM_INT); // adding a contact
+$removecontact  = optional_param('removecontact',  0, PARAM_INT); // removing a contact
+$blockcontact   = optional_param('blockcontact',   0, PARAM_INT); // blocking a contact
+$unblockcontact = optional_param('unblockcontact', 0, PARAM_INT); // unblocking a contact
+//$popup          = optional_param('popup', false, PARAM_ALPHANUM);    // If set then starts a new popup window
+$advancedsearch = optional_param('advanced', 0, PARAM_INT);
+
+$url = new moodle_url('/message/contacts.php');
+if ($addcontact !== 0) {
+    $url->param('addcontact', $addcontact);
+}
+if ($removecontact !== 0) {
+    $url->param('removecontact', $removecontact);
+}
+if ($blockcontact !== 0) {
+    $url->param('blockcontact', $blockcontact);
+}
+if ($unblockcontact !== 0) {
+    $url->param('unblockcontact', $unblockcontact);
+}
+if ($advancedsearch !== 0) {
+    $url->param('advanced', $advancedsearch);
+}
+$PAGE->set_url($url);
+
+
+$context = get_context_instance(CONTEXT_SYSTEM);
+
+
+/// Process any contact maintenance requests there may be
+if ($addcontact and confirm_sesskey()) {
+    add_to_log(SITEID, 'message', 'add contact', 'history.php?user1='.$addcontact.'&amp;user2='.$USER->id, $addcontact);
+    message_add_contact($addcontact);
+}
+if ($removecontact and confirm_sesskey()) {
+    add_to_log(SITEID, 'message', 'remove contact', 'history.php?user1='.$removecontact.'&amp;user2='.$USER->id, $removecontact);
+    message_remove_contact($removecontact);
+}
+if ($blockcontact and confirm_sesskey()) {
+    add_to_log(SITEID, 'message', 'block contact', 'history.php?user1='.$blockcontact.'&amp;user2='.$USER->id, $blockcontact);
+    message_block_contact($blockcontact);
+}
+if ($unblockcontact and confirm_sesskey()) {
+    add_to_log(SITEID, 'message', 'unblock contact', 'history.php?user1='.$unblockcontact.'&amp;user2='.$USER->id, $unblockcontact);
+    message_unblock_contact($unblockcontact);
+}
+
+//$PAGE->blocks->add_region('content');
+$PAGE->set_context(get_context_instance(CONTEXT_USER, $USER->id));
+$PAGE->navigation->extend_for_user($USER);
+
+$strcontacts = get_string('contacts', 'message');
+
+$PAGE->set_pagelayout('course');
+$PAGE->set_title(fullname($USER).': '.$strcontacts);
+$PAGE->set_heading($strcontacts);//text usually in the top left above nav bar
+
+//now the page contents
+echo $OUTPUT->header();
+echo $OUTPUT->heading(fullname($USER).': '.$strcontacts);
+
+echo $OUTPUT->box_start('message');
+
+echo html_writer::start_tag('div', array('class'=>'userselector mdl-align'));
+    $refreshpage = false;
+    $showactionlinks = true;
+    message_print_contacts($refreshpage, 'contacts_messages.php?usergroup=contacts', 0, $showactionlinks);
+echo html_writer::end_tag('div');
+
+echo html_writer::start_tag('div', array('class'=>'messagearea mdl-align'));
+    message_print_search($advancedsearch);
+echo html_writer::end_tag('div');
+
+echo $OUTPUT->box_end();
+
+echo $OUTPUT->footer();
+
Index: moodle/message/contacts_messages.php
--- moodle/message/contacts_messages.php No Base Revision
+++ moodle/message/contacts_messages.php Locally New
@@ -0,0 +1,251 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * A page displaying the user's contacts. Similar to index.php but not a popup.
+ *
+ * @package   moodlecore
+ * @copyright 2010 Andrew Davis
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('VIEW_UNREAD_MESSAGES','unread');
+define('VIEW_CONTACTS','contacts');
+define('VIEW_COURSE','course_');
+
+define('SHOW_ACTION_LINKS_IN_CONTACT_LIST', false);
+
+require('../config.php');
+require('lib.php');
+require('send_form.php');
+
+require_login(0, false);
+
+if (isguestuser()) {
+    redirect($CFG->wwwroot);
+}
+
+if (empty($CFG->messaging)) {
+    print_error('disabled', 'message');
+}
+
+$usergroup = optional_param('usergroup', VIEW_UNREAD_MESSAGES, PARAM_ALPHANUMEXT);
+$contactid = optional_param('contact', 0, PARAM_INT);
+
+$message = optional_param('messagesend', null, PARAM_TEXT);
+
+$url = new moodle_url('/message/contacts_messages.php');
+
+if ($usergroup !== 0) {
+    $url->param('usergroup', $usergroup);
+}
+if ($contactid !== 0) {
+    $url->param('contact', $contactid);
+}
+$PAGE->set_url($url);
+
+$context = get_context_instance(CONTEXT_SYSTEM);
+
+$theotheruser = null;
+$unreadmessagecount = 0;
+if (!empty($contactid)) {
+    $theotheruser = $DB->get_record("user", array("id"=>$contactid));
+    if (!$theotheruser) {
+        print_error('invaliduserid');
+    }
+    
+    $unreadmessagecount = $DB->count_records('message', array('useridto'=>$USER->id));
+
+    //this marks popup messages as read. Not marking other messages types read
+    //(ie email messages) as we want them dealt with by their processor
+    $unreadpopupmessages = message_get_popup_messages($USER->id, $theotheruser->id);
+}
+
+//was a message sent?
+$messageerror = null;
+if (!empty($theotheruser) && !empty($message) && has_capability('moodle/site:sendmessage', $context)) {
+
+    // Check that the user is not blocking us!!
+    if ($contact = $DB->get_record('message_contacts', array('userid'=>$theotheruser->id, 'contactid'=>$USER->id))) {
+        if ($contact->blocked and !has_capability('moodle/site:readallmessages', $context)) {
+            $messageerror = get_string('userisblockingyou', 'message');
+        }
+    }
+    $userpreferences = get_user_preferences(NULL, NULL, $theotheruser->id);
+
+    if (!empty($userpreferences['message_blocknoncontacts'])) {  // User is blocking non-contacts
+        if (empty($contact)) {   // We are not a contact!
+            $messageerror = get_string('userisblockingyounoncontact', 'message');
+        }
+    }
+
+
+    //////////////////////////////////
+    /*$mform = new send_form();
+    $defaultmessage = new stdClass;
+    $defaultmessage->id = $theotheruser->id;
+    $defaultmessage->message = '';
+  //  if (can_use_html_editor() && get_user_preferences('message_usehtmleditor', 0)) {
+//        $defaultmessage->messageformat = FORMAT_HTML;
+    //} else {
+        $defaultmessage->messageformat = FORMAT_MOODLE;
+    //}
+    $mform->set_data($defaultmessage);
+    $data = $mform->get_data();
+    var_dump($data);
+    $messageid = message_post_message($USER, $theotheruser, $data->message, $data->messageformat, 'direct');*/
+    //////////////////////////////////
+
+    $messageid = message_post_message($USER, $theotheruser, $message, FORMAT_HTML, 'direct');
+}
+if (!empty($messageerror)) {
+    echo $OUTPUT->header();
+    echo $OUTPUT->heading($messageerror, 1);
+    echo $OUTPUT->footer();
+    exit;
+}
+
+$PAGE->set_context(get_context_instance(CONTEXT_USER, $USER->id));
+$PAGE->navigation->extend_for_user($USER);
+
+$strmessages = get_string('messages', 'message');
+
+$PAGE->set_pagelayout('course');
+
+$PAGE->set_title("$SITE->shortname: $strmessages");
+$PAGE->set_heading("$SITE->shortname: $strmessages");
+
+//now the page contents
+echo $OUTPUT->header();
+echo $OUTPUT->heading(fullname($USER).': '.$strmessages);
+
+echo $OUTPUT->box_start('message');
+$refreshpage = false;
+
+echo html_writer::start_tag('div', array('class'=>'userselector mdl-align'));
+
+    $unreadcount = $DB->count_records('message', array('useridto'=>$USER->id));
+    $strunreadmessages = null;
+    if ($unreadcount>0) { //if there are unread messages
+        $strunreadmessages = get_string('unreadmessages','message', $unreadcount);
+        $options = array(VIEW_UNREAD_MESSAGES=>$strunreadmessages);
+    } else {
+        //if 0 unread messages and they've requested unread messages then show contacts
+        if ($usergroup==VIEW_UNREAD_MESSAGES) {
+            $usergroup = VIEW_CONTACTS;
+        }
+    }
+
+    $strcontacts = get_string('contacts', 'message');
+    $options[VIEW_CONTACTS] = $strcontacts;
+
+    $courses = get_my_courses($USER->id);
+    $coursecontexts = array();//we need one of these again so holding on to them
+    if (!empty($courses)) {
+        $courses_options = array();
+
+        foreach($courses as $course) {
+            $coursecontexts[$course->id] = get_context_instance(CONTEXT_COURSE, $course->id);
+            if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) {
+                $courses_options[VIEW_COURSE.$course->id] = $course->fullname;
+            }
+        }
+
+        if (!empty($courses_options)) {
+            $options[] = array(get_string('courses')=>$courses_options);
+        }
+    }
+
+    //$content = html_writer::start_tag('form', array('class'=>'adminsearchform', 'method'=>'get', 'action'=>$formtarget));
+    echo html_writer::start_tag('form', array('id'=>'usergroupform','method'=>'get'));
+        echo html_writer::select($options, 'usergroup', $usergroup, false, array('id'=>'usergroup','onchange'=>'this.form.submit()'));
+    echo html_writer::end_tag('form');
+
+    if ($usergroup==VIEW_UNREAD_MESSAGES) {
+        message_print_contacts($refreshpage, $PAGE->url, 1, SHOW_ACTION_LINKS_IN_CONTACT_LIST,$strunreadmessages);
+    } else if ($usergroup==VIEW_CONTACTS) {
+        message_print_contacts($refreshpage, $PAGE->url, 0, SHOW_ACTION_LINKS_IN_CONTACT_LIST);
+    } else if (substr($usergroup, 0, 7)==VIEW_COURSE) {
+        $courseidtoshow = intval(substr($usergroup, 7));
+
+        if (!empty($courseidtoshow)
+            && array_key_exists($courseidtoshow, $coursecontexts)
+            && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) {
+
+            message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, SHOW_ACTION_LINKS_IN_CONTACT_LIST);
+        } else {
+            //something odd is going on. User trying to access a course theyre not in perhaps.
+            add_to_log(SITEID, 'message', 'view', 'contacts_messages.php', $usergroup);
+        }
+    }
+
+    echo html_writer::start_tag('form', array('action'=>'contacts.php?advanced=1'));
+        $strmanagecontacts = get_string('managecontacts','message');
+        echo html_writer::empty_tag('input', array('type'=>'submit','value'=>$strmanagecontacts));
+    echo html_writer::end_tag('form');
+echo html_writer::end_tag('div');
+
+echo html_writer::start_tag('div', array('class'=>'messagearea mdl-align'));
+    if ($contactid) {
+        if (!$theotheruser) {
+            print_error('invaliduserid');
+        }
+
+        echo html_writer::start_tag('div', array('class'=>'mdl-left messagehistory'));
+
+            $displaycount = MESSAGE_SHORTVIEW_LIMIT;
+            if ($unreadmessagecount>MESSAGE_SHORTVIEW_LIMIT) {
+                $displaycount = $unreadmessagecount;
+            }
+
+            $includemessagehistorylink = true;
+            message_print_message_history($USER, $theotheruser, null, $displaycount, $includemessagehistorylink);
+
+        echo html_writer::end_tag('div');
+
+        if (has_capability('moodle/site:sendmessage', $context)) {
+            //send message form
+            /*$mform = new send_form();
+            $defaultmessage = new stdClass;
+            $defaultmessage->id = $theotheruser->id;
+            $defaultmessage->message = '';
+            if (can_use_html_editor() && get_user_preferences('message_usehtmleditor', 0)) {
+                $defaultmessage->messageformat = FORMAT_HTML;
+            } else {
+                $defaultmessage->messageformat = FORMAT_MOODLE;
+            }
+            $mform->set_data($defaultmessage);
+            $mform->display();*/
+
+            $strsendmessage = get_string('sendmessage','message');
+            echo html_writer::start_tag('div', array('class'=>'mdl-align messagesend'));
+                echo html_writer::start_tag('form', array('id'=>'sendmessageform','method'=>'post'));
+                    echo '<textarea name="messagesend" rows="4" class="messagesendbox"></textarea>';
+                    echo "<br /><input type='submit' value='$strsendmessage' />";
+                echo html_writer::end_tag('form');
+            echo html_writer::end_tag('div');
+        }
+    }
+echo html_writer::end_tag('div');
+
+//echo $OUTPUT->blocks_for_region('content');
+
+echo $OUTPUT->box_end();
+
+echo $OUTPUT->footer();
+
+
Index: moodle/message/discussion.php
--- moodle/message/discussion.php Base (1.38)
+++ moodle/message/discussion.php Locally Modified (Based On 1.38)
Index: moodle/message/edit.php
--- moodle/message/edit.php Base (1.29)
+++ moodle/message/edit.php Locally Modified (Based On 1.29)
@@ -65,6 +65,8 @@
 $personalcontext = get_context_instance(CONTEXT_USER, $user->id);
 $coursecontext   = get_context_instance(CONTEXT_COURSE, $course->id);
 
+$PAGE->set_context(get_context_instance(CONTEXT_USER, $USER->id));
+$PAGE->set_pagelayout('course');
 
 // check access control
 if ($user->id == $USER->id) {
@@ -95,13 +97,16 @@
     foreach ( $providers as $providerid => $provider){
         foreach (array('loggedin', 'loggedoff') as $state){
             $linepref = '';
-            foreach ($form->{$provider->component.'_'.$provider->name.'_'.$state} as $process=>$one){
+            $componentproviderstate = $provider->component.'_'.$provider->name.'_'.$state;
+            if (array_key_exists($componentproviderstate, $form)) {
+                foreach ($form->{$componentproviderstate} as $process=>$one){
                 if ($linepref == ''){
                     $linepref = $process;
                 } else {
                     $linepref .= ','.$process;
                 }
             }
+            }
             $preferences['message_provider_'.$provider->component.'_'.$provider->name.'_'.$state] = $linepref;
         }
     }
@@ -171,12 +176,17 @@
 $strparticipants  = get_string('participants');
 $userfullname     = fullname($user, true);
 
+if ($user->id==$USER->id) {
+    $PAGE->navigation->extend_for_user($USER);
+} else {
 if (has_capability('moodle/course:viewparticipants', $coursecontext) ||
     has_capability('moodle/site:viewparticipants', $systemcontext)) {
     $PAGE->navbar->add($strparticipants, new moodle_url('/message/index.php', array('id'=>$course->id)));
 }
 $PAGE->navbar->add($userfullname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)));
 $PAGE->navbar->add($streditmymessage);
+}
+
 $PAGE->set_title("$course->shortname: $streditmymessage");
 if ($course->id != SITEID) {
     $PAGE->set_heading("$course->fullname: $streditmymessage");
Index: moodle/message/history.php
--- moodle/message/history.php Base (1.27)
+++ moodle/message/history.php Locally Modified (Based On 1.27)
@@ -36,11 +36,45 @@
     print_error('disabled', 'message');
 }
 
-$PAGE->set_title(get_string('messagehistory', 'message'));
-
 /// Script parameters
 $userid1 = required_param('user1', PARAM_INT);
-$PAGE->set_url('/message/history.php', array('user1'=>$userid1));
+$userid2 = optional_param('user2', $USER->id, PARAM_INT);
+$popup   = optional_param('popup', 0, PARAM_INT);
+
+$url = new moodle_url('/message/history.php');
+$url->param('user1', $userid1);
+if (!empty($userid2)) {
+    $url->param('user2', $userid2);
+}
+$PAGE->set_url($url);
+
+$PAGE->set_context(get_context_instance(CONTEXT_USER, $USER->id));
+
+$iscurrentuser = $USER->id == $userid1;
+
+if ($iscurrentuser) {
+    $PAGE->navigation->extend_for_user($USER);
+} else {
+    $PAGE->navigation->extend_for_user($DB->get_record('user',array('id'=>$userid1)));
+}
+$PAGE->navigation->extend_for_user($DB->get_record('user',array('id'=>$userid2)));
+
+
+if (!$popup) {
+    if ($iscurrentuser) {
+        $PAGE->navigation->get('myprofile')->get('messages')->make_active();
+    } else {
+        $PAGE->navigation->find($userid1,navigation_node::TYPE_USER)->make_active();
+    }
+
+    $strmessagehistory = get_string('messagehistory', 'message');
+    $PAGE->navbar->add($strmessagehistory);
+
+    $PAGE->set_pagelayout('course');
+    $PAGE->set_heading($strmessagehistory);
+}
+$PAGE->set_title($strmessagehistory);
+
 if (! $user1 = $DB->get_record("user", array("id"=>$userid1))) {  // Check it's correct
     print_error('invaliduserid');
 }
@@ -53,8 +87,6 @@
 }
 
 if (has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) {             // Able to see any discussion
-    $userid2 = optional_param('user2', $USER->id, PARAM_INT);
-    $PAGE->url->param('user2', $userid2);
     if (! $user2 = $DB->get_record("user", array("id"=>$userid2))) {  // Check
         print_error('invaliduserid');
     }
@@ -78,50 +110,7 @@
 
 /// Print out a heading including the users we are looking at
 
-echo $OUTPUT->box_start('center');
-echo '<table align="center" cellpadding="10"><tr>';
-echo '<td align="center">';
-echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID)).'<br />';
-echo fullname($user1);
-echo '</td>';
-echo '<td align="center">';
-echo '<img src="'.$CFG->wwwroot.'/pix/t/left.gif" alt="'.get_string('from').'" />';
-echo '<img src="'.$CFG->wwwroot.'/pix/t/right.gif" alt="'.get_string('to').'" />';
-echo '</td>';
-echo '<td align="center">';
-echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID)).'<br />';
-echo fullname($user2);
-echo '</td>';
-echo '</tr></table>';
-echo $OUTPUT->box_end();
+message_print_message_history($user1, $user2, $search);
 
-
-/// Get all the messages and print them
-
-if ($messages = message_get_history($user1, $user2)) {
-    $current->mday = '';
-    $current->month = '';
-    $current->year = '';
-    $messagedate = get_string('strftimetime');
-    $blockdate   = get_string('strftimedaydate');
-    foreach ($messages as $message) {
-        $date = usergetdate($message->timecreated);
-        if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
-            $current->mday = $date['mday'];
-            $current->month = $date['month'];
-            $current->year = $date['year'];
-            echo '<a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
-            echo $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center');
-        }
-        if ($message->useridfrom == $user1->id) {
-            echo message_format_message($message, $user1, $messagedate, $search, 'other');
-        } else {
-            echo message_format_message($message, $user2, $messagedate, $search, 'me');
-        }
-    }
-} else {
-    echo $OUTPUT->heading(get_string('nomessagesfound', 'message'), 1);
-}
-
 echo $OUTPUT->footer();
 
Index: moodle/message/index.php
--- moodle/message/index.php Base (1.32)
+++ moodle/message/index.php Locally Modified (Based On 1.32)
@@ -112,8 +112,6 @@
                            get_string('contacts', 'message'));
 $tabrow[] = new tabobject('search', $CFG->wwwroot.'/message/index.php?tab=search',
                            get_string('search', 'message'));
-$tabrow[] = new tabobject('settings', $CFG->wwwroot.'/message/index.php?tab=settings',
-                           get_string('settings', 'message'));
 $tabrows = array($tabrow);
 
 print_tabs($tabrows, $tab);
@@ -129,7 +127,7 @@
 /// a print function is associated with each tab
 $tabprintfunction = 'message_print_'.$tab;
 if (function_exists($tabprintfunction)) {
-    $tabprintfunction();
+    $tabprintfunction('index.php');
 }
 
 echo '</td> </tr> </table>';
Index: moodle/message/lib.php
--- moodle/message/lib.php Base (1.108)
+++ moodle/message/lib.php Locally Modified (Based On 1.108)
@@ -29,6 +29,13 @@
 define ('MESSAGE_SHORTLENGTH', 300);
 define ('MESSAGE_WINDOW', true);          // We are in a message window (so don't pop up a new one!)
 
+define ('MESSAGE_DISCUSSION_WIDTH',600);
+define ('MESSAGE_DISCUSSION_HEIGHT',500);
+
+define ('MESSAGE_SHORTVIEW_LIMIT', 8);//the maximum number of messages to show on the short message history
+
+define ('CONTACT_ID','contact');
+
 if (!isset($CFG->message_contacts_refresh)) {  // Refresh the contacts list every 60 seconds
     $CFG->message_contacts_refresh = 60;
 }
@@ -39,8 +46,35 @@
     $CFG->message_offline_time = 300;
 }
 
+function message_print_participants($context, $courseid, $contactselecturl=null, $showactionlinks=true, $titletodisplay=null) {
+    global $DB, $USER;
 
-function message_print_contacts() {
+    $participants = get_enrolled_users($context);
+    
+    echo '<table id="message_participants" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
+
+    if (!empty($titletodisplay)) {
+        echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
+    }
+
+    if (empty($titletodisplay)) {
+        echo '<tr><td colspan="3" class="heading">';
+        echo get_string('participants');
+        echo '</td></tr>';
+    }
+
+    foreach ($participants as $participant) {
+        if ($participant->id != $USER->id) {
+            $participant->messagecount = 0;//todo andrew we need to get this from the db
+            message_print_contactlist_user($participant, true, $contactselecturl, $showactionlinks);
+        }
+    }
+    //$participants->close();
+
+    echo '</table>';
+}
+
+function message_print_contacts($refresh=true, $contactselecturl=null, $minmessages=0, $showactionlinks=true, $titletodisplay=null) {
     global $USER, $CFG, $DB, $PAGE, $OUTPUT;
 
     $timetoshowusers = 300; //Seconds default
@@ -115,35 +149,47 @@
         print_string('contactlistempty', 'message');
         echo '</div>';
         echo '<div class="note">';
-        print_string('addsomecontacts', 'message', $CFG->wwwroot.'/message/index.php?tab=search');
+        print_string('addsomecontacts', 'message', message_remove_url_params($PAGE->url).'?tab=search');
         echo '</div>';
     }
 
     echo '<table id="message_contacts" class="boxaligncenter" cellspacing="2" cellpadding="0" border="0">';
 
+    if (!empty($titletodisplay)) {
+        echo "<tr><td colspan='3' class='heading'>$titletodisplay</td></tr>";
+    }
+
     if($countonlinecontacts) {
         /// print out list of online contacts
 
+        if (empty($titletodisplay)) {
         echo '<tr><td colspan="3" class="heading">';
         echo get_string('onlinecontacts', 'message', $countonlinecontacts);
         echo '</td></tr>';
+        }
 
         foreach ($onlinecontacts as $contact) {
-            message_print_contactlist_user($contact);
+            if ($minmessages==0 || $contact->messagecount>=$minmessages) {
+                message_print_contactlist_user($contact, true, $contactselecturl, $showactionlinks);
         }
     }
+    }
     echo '<tr><td colspan="3">&nbsp;</td></tr>';
 
     if ($countofflinecontacts) {
         /// print out list of offline contacts
 
+        if (empty($titletodisplay)) {
         echo '<tr><td colspan="3" class="heading">';
         echo get_string('offlinecontacts', 'message', $countofflinecontacts);
         echo '</td></tr>';
+        }
 
         foreach ($offlinecontacts as $contact) {
-            message_print_contactlist_user($contact);
+            if ($minmessages==0 || $contact->messagecount>=$minmessages) {
+                message_print_contactlist_user($contact, true, $contactselecturl, $showactionlinks);
         }
+        }
         echo '<tr><td colspan="3">&nbsp;</td></tr>';
     }
 
@@ -154,9 +200,11 @@
         echo '</td></tr>';
 
         foreach ($strangers as $stranger) {
-            message_print_contactlist_user($stranger, false);
+            if ($minmessages==0 || $contact->messagecount>=$minmessages) {
+                message_print_contactlist_user($stranger, false, $contactselecturl, $showactionlinks);
         }
     }
+    }
 
     echo '</table>';
 
@@ -168,18 +216,29 @@
 
     echo '<br />';
 
+    if ($refresh) {
     $PAGE->requires->js_init_call('M.core_message.init_refresh_page', array(60*1000, $PAGE->url->out(false)));
 
     echo $OUTPUT->container_start('messagejsautorefresh note center');
     echo get_string('pagerefreshes', 'message', $CFG->message_contacts_refresh);
     echo $OUTPUT->container_end();
+    }
 
     echo $OUTPUT->container_start('messagejsmanualrefresh aligncenter');
-    echo $OUTPUT->single_button('index.php', get_string('refresh'));
+    echo $OUTPUT->single_button(message_remove_url_params($PAGE->url), get_string('refresh'));
     echo $OUTPUT->container_end();
 }
 
+function message_remove_url_params($moodleurl) {
+    //this should work but doesnt for some reason
+    //return $PAGE->url->out(true);
 
+    $newurl = new moodle_url($moodleurl);
+    $newurl->remove_params('addcontact','removecontact','blockcontact','unblockcontact');
+    return $newurl->out();
+}
+
+
 /// $messagearray is an array of objects
 /// $field is a valid property of object
 /// $value is the value $field should equal to be counted
@@ -196,15 +255,53 @@
     return $count;
 }
 
+/**
+ *
+ * @global <type> $USER
+ * @global <type> $PAGE
+ * @global <type> $OUTPUT
+ * @param  boolean advancedsearch show basic or advanced search form
+ * @return boolean was a search performed?
+ */
+function message_print_search($advancedsearch = false) {
+    global $USER, $PAGE, $OUTPUT;
 
-function message_print_search() {
-    global $USER, $OUTPUT;
+    $frm = data_submitted();
 
-    if ($frm = data_submitted()) {
+    $doingsearch = false;
+    if ($frm) {
+        $doingsearch = !empty($frm->combinedsubmit) || !empty($frm->keywords) || (!empty($frm->personsubmit) and !empty($frm->name));
+    }
 
-        message_print_search_results($frm);
+    if (!empty($frm->combinedsearch)) {
+        $combinedsearchstring = $frm->combinedsearch;
+    } else {
+        $combinedsearchstring = get_string('search').'...';
+    }
 
+    $PAGE->requires->js_init_call('M.core_message.init_search_page', array($combinedsearchstring));
+
+    if ($doingsearch) {
+        if ($advancedsearch) {
+            
+            $messagesearch = '';
+            if (!empty($frm->keywords)) {
+                $messagesearch = $frm->keywords;
+            }
+            $personsearch = '';
+            if (!empty($frm->name)) {
+                $personsearch = $frm->name;
+            }
+            include('search_advanced.html');
     } else {
+            include('search.html');
+        }
+
+        $showicontext = true;
+        message_print_search_results($frm, $showicontext);
+
+        return true;
+    } else {
 /*
 /// unfinished buggy code disabled in search.html anyway
         // find all courses this use has readallmessages capabilities in
@@ -217,9 +314,16 @@
             $cs .= '</select>';
         }
 */
+
+        if ($advancedsearch) {
+            $personsearch = $messagesearch = '';
+            include('search_advanced.html');
+        } else {
         include('search.html');
     }
+        return false;
 }
+}
 
 function message_print_settings() {
     global $USER, $OUTPUT;
@@ -239,7 +343,7 @@
 
         set_user_preferences($pref);
 
-        redirect('index.php', get_string('settingssaved', 'message'), 1);
+        redirect(message_remove_url_params($PAGE->url), get_string('settingssaved', 'message'), 1);
     }
 
     $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
@@ -309,52 +413,67 @@
 
 
 
-function message_print_search_results($frm) {
-    global $USER, $CFG, $DB, $OUTPUT;
+function message_print_search_results($frm, $showicontext=false) {
+    global $USER, $CFG, $DB, $OUTPUT, $PAGE;
 
     echo '<div class="mdl-align">';
 
-    /// search for person
+    $personsearch = false;
+    $personsearchstring = null;
     if (!empty($frm->personsubmit) and !empty($frm->name)) {
+        $personsearch = true;
+        $personsearchstring = $frm->name;
+    } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
+        $personsearch = true;
+        $personsearchstring = $frm->combinedsearch;
+    }
 
+    /// search for person
+    if ($personsearch) {
         if (optional_param('mycourses', 0, PARAM_BOOL)) {
             $users = array();
             $mycourses = get_my_courses($USER->id);
             foreach ($mycourses as $mycourse) {
-                if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
+                if (is_array($susers = message_search_users($mycourse->id, $personsearchstring))) {
                     foreach ($susers as $suser) $users[$suser->id] = $suser;
                 }
             }
         } else {
-            $users = message_search_users(SITEID, $frm->name);
+            $users = message_search_users(SITEID, $personsearchstring);
         }
 
         if (!empty($users)) {
             echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
-            echo '<table class="message_users">';
+            echo '<table class="messagesearchresults">';
             foreach ($users as $user) {
 
                 if ( $user->contactlistid )  {
                     if ($user->blocked == 0) { /// not blocked
-                        $strcontact = message_contact_link($user->id, 'remove', true);
-                        $strblock   = message_contact_link($user->id, 'block', true);
+                        $strcontact = message_contact_link($user->id, 'remove', true, null, $showicontext);
+                        $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
                     } else { // blocked
-                        $strcontact = message_contact_link($user->id, 'add', true);
-                        $strblock   = message_contact_link($user->id, 'unblock', true);
+                        $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
+                        $strblock   = message_contact_link($user->id, 'unblock', true, null, $showicontext);
                     }
                 } else {
-                    $strcontact = message_contact_link($user->id, 'add', true);
-                    $strblock   = message_contact_link($user->id, 'block', true);
+                    $strcontact = message_contact_link($user->id, 'add', true, null, $showicontext);
+                    $strblock   = message_contact_link($user->id, 'block', true, null, $showicontext);
                 }
-                $strhistory = message_history_link($user->id, 0, true, '', '', 'icon');
 
+                //should we show just the icon or icon and text?
+                $histicontext = 'icon';
+                if ($showicontext) {
+                    $histicontext = 'both';
+                }
+                $strhistory = message_history_link($user->id, 0, true, '', '', $histicontext);
+
                 echo '<tr><td class="pix">';
                 echo $OUTPUT->user_picture($user, array('size'=>20, 'courseid'=>SITEID));
                 echo '</td>';
                 echo '<td class="contact">';
                 $popupoptions = array(
-                        'height' => 500,
-                        'width' => 500,
+                        'height' => MESSAGE_DISCUSSION_HEIGHT,
+                        'width' => MESSAGE_DISCUSSION_WIDTH,
                         'menubar' => false,
                         'location' => false,
                         'status' => true,
@@ -375,15 +494,24 @@
             echo '</table>';
 
         } else {
-            echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
+            echo get_string('userssearchresults', 'message', 0).'<br /><br />';
         }
+    }
 
+    // search messages for keywords
+    $messagesearch = false;
+    $messagesearchstring = null;
+    if (!empty($frm->keywords)) {
+        $messagesearch = true;
+        $messagesearchstring = clean_text(trim($frm->keywords));
+    } else if (!empty($frm->combinedsubmit) and !empty($frm->combinedsearch)) {
+        $messagesearch = true;
+        $messagesearchstring = clean_text(trim($frm->combinedsearch));
+    }
 
-    /// search messages for keywords
-    } else if (!empty($frm->keywordssubmit)) {
-        $keywordstring = clean_text(trim($frm->keywords));
-        if ($keywordstring) {
-            $keywords = explode(' ', $keywordstring);
+    if ($messagesearch) {
+        if ($messagesearchstring) {
+            $keywords = explode(' ', $messagesearchstring);
         } else {
             $keywords = array();
         }
@@ -391,6 +519,10 @@
         $fromme   = false;
         $courseid = 'none';
 
+        if (empty($frm->keywordsoption)) {
+            $frm->keywordsoption = 'allmine';
+        }
+
         switch ($frm->keywordsoption) {
             case 'tome':
                 $tome   = true;
@@ -421,10 +553,10 @@
             }
 
         /// print heading with number of results
-            echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($keywordstring).'")</p>';
+            echo '<p class="heading">'.get_string('keywordssearchresults', 'message', count($messages)).' ("'.s($messagesearchstring).'")</p>';
 
         /// print table headings
-            echo '<table class="searchresults" cellspacing="0">';
+            echo '<table class="messagesearchresults" cellspacing="0">';
             echo '<tr>';
             echo '<td><strong>'.get_string('from').'</strong></td>';
             echo '<td><strong>'.get_string('to').'</strong></td>';
@@ -480,15 +612,15 @@
             /// print out message row
                 echo '<tr valign="top">';
                 echo '<td class="contact">';
-                message_print_user($userfrom, $fromcontact, $fromblocked);
+                message_print_user($userfrom, $fromcontact, $fromblocked, $showicontext);
                 echo '</td>';
                 echo '<td class="contact">';
-                message_print_user($userto, $tocontact, $toblocked);
+                message_print_user($userto, $tocontact, $toblocked, $showicontext);
                 echo '</td>';
                 echo '<td class="summary">'.message_get_fragment($message->fullmessage, $keywords);
                 echo '<br /><div class="link">';
                 message_history_link($message->useridto, $message->useridfrom, false,
-                                     $keywordstring, 'm'.$message->id, $strcontext);
+                                     $messagesearchstring, 'm'.$message->id, $strcontext);
                 echo '</div>';
                 echo '</td>';
                 echo '<td class="date">'.userdate($message->timecreated, $dateformat).'</td>';
@@ -502,46 +634,47 @@
             echo '</table>';
 
         } else {
-            echo $OUTPUT->notification(get_string('nosearchresults', 'message'));
+            echo '<p class="heading">'.get_string('keywordssearchresults', 'message', 0).' ("'.s($messagesearchstring).'")</p>';
         }
-
-
-    /// what the ????, probably an empty search string, duh!
     } else {
+        //empty search string
         echo $OUTPUT->notification(get_string('emptysearchstring', 'message'));
     }
 
     echo '<br />';
-    echo $OUTPUT->single_button(new moodle_url('index.php', array('tab' => 'search')), get_string('newsearch', 'message'));
+    echo $OUTPUT->single_button(new moodle_url($PAGE->url, array('tab' => 'search')), get_string('newsearch', 'message'));
 
     echo '</div>';
 }
 
 
-function message_print_user ($user=false, $iscontact=false, $isblocked=false) {
+function message_print_user ($user=false, $iscontact=false, $isblocked=false, $includeicontext=false) {
     global $USER, $OUTPUT;
 
     if ($user === false) {
         echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
     } else {
-        echo $OUTPUT->user_picture($USE, array('size'=>20, 'courseid'=>SITEID));
+        echo $OUTPUT->user_picture($USER, array('size'=>20, 'courseid'=>SITEID));
         echo '&nbsp;';
+
+        $return = false;
+        $script = null;
         if ($iscontact) {
-            message_contact_link($user->id, 'remove');
+            message_contact_link($user->id, 'remove', $return, $script, $includeicontext);
         } else {
-            message_contact_link($user->id, 'add');
+            message_contact_link($user->id, 'add', $return, $script, $includeicontext);
         }
         echo '&nbsp;';
         if ($isblocked) {
-            message_contact_link($user->id, 'unblock');
+            message_contact_link($user->id, 'unblock', $return, $script, $includeicontext);
         } else {
-            message_contact_link($user->id, 'block');
+            message_contact_link($user->id, 'block', $return, $script, $includeicontext);
         }
         echo '<br />';
 
         $popupoptions = array(
-                'height' => 500,
-                'width' => 500,
+                'height' => MESSAGE_DISCUSSION_HEIGHT,
+                'width' => MESSAGE_DISCUSSION_WIDTH,
                 'menubar' => false,
                 'location' => false,
                 'status' => true,
@@ -557,11 +690,16 @@
 
 
 /// linktype can be: add, remove, block, unblock
-function message_contact_link($userid, $linktype='add', $return=false, $script="index.php?tab=contacts", $text=false) {
-    global $USER, $CFG, $OUTPUT;
+function message_contact_link($userid, $linktype='add', $return=false, $script=null, $text=false) {
+    global $USER, $CFG, $OUTPUT, $PAGE;
 
     static $str;
 
+    if (empty($script)) {
+        //$script = "index.php?tab=contacts";
+        $script = message_remove_url_params($PAGE->url).'?tab=contacts';
+    }
+
     if (empty($str->blockcontact)) {
        $str->blockcontact   =  get_string('blockcontact', 'message');
        $str->unblockcontact =  get_string('unblockcontact', 'message');
@@ -642,7 +780,7 @@
             'scrollbars' => true,
             'resizable' => true);
 
-    $link = new moodle_url("/message/history.php?user1=$userid1&user2=$userid2$keywords$position");
+    $link = new moodle_url("/message/history.php?user1=$userid1&user2=$userid2$keywords$position&popup=1");
     $action = new popup_action('click', $link, "message_history_$userid1", $popupoptions);
     $str = $OUTPUT->action_link($link, $fulllink, $action, array('title'=>$strmessagehistory));
 
@@ -791,7 +929,6 @@
         $searchcond = implode(" AND ", $searchcond);
     }
 
-
     /// There are several possibilities
     /// 1. courseid = SITEID : The admin is searching messages by all users
     /// 2. courseid = ??     : A teacher is searching messages by users in
@@ -953,23 +1090,91 @@
     return $fragment;
 }
 
-
-function message_get_history($user1, $user2) {
+//retrieve the messages between two users
+function message_get_history($user1, $user2, $limitnum=0) {
     global $DB;
 
-    $messages = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
+    $messages = array();
+
+    if ($messages_read = $DB->get_records_select('message_read', "(useridto = ? AND useridfrom = ?) OR
                                                     (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
-                                                    'timecreated');
+                                                    'timecreated desc', '*', 0, $limitnum)) {
+        foreach ($messages_read as $message) {
+            $messages[$message->timecreated] = $message;
+        }
+    }
     if ($messages_new =  $DB->get_records_select('message', "(useridto = ? AND useridfrom = ?) OR
                                                     (useridto = ? AND useridfrom = ?)", array($user1->id, $user2->id, $user2->id, $user1->id),
-                                                    'timecreated')) {
+                                                    'timecreated desc', '*', 0, $limitnum)) {
         foreach ($messages_new as $message) {
-            $messages[] = $message;
+            $messages[$message->timecreated] = $message;
         }
     }
+
+    //if we only want the last $limitnum messages
+    if ($limitnum>0) {
+        ksort($messages);
+        $messages = array_slice($messages, count($messages)-$limitnum, $limitnum, true);
+    }
+    
     return $messages;
 }
 
+function message_print_message_history($user1,$user2,$search='',$messagelimit=0, $includemessagehistorylink=false) {
+    global $CFG, $OUTPUT;
+
+    echo $OUTPUT->box_start('center');
+    echo '<table align="center" cellpadding="10"><tr>';
+    echo '<td align="center">';
+    echo $OUTPUT->user_picture($user1, array('size'=>100, 'courseid'=>SITEID)).'<br />';
+    echo fullname($user1);
+    echo '</td>';
+    echo '<td align="center">';
+    echo '<img src="'.$CFG->wwwroot.'/pix/t/left.gif" alt="'.get_string('from').'" />';
+    echo '<img src="'.$CFG->wwwroot.'/pix/t/right.gif" alt="'.get_string('to').'" />';
+    echo '</td>';
+    echo '<td align="center">';
+    echo $OUTPUT->user_picture($user2, array('size'=>100, 'courseid'=>SITEID)).'<br />';
+    echo fullname($user2);
+    echo '</td>';
+    echo '</tr></table>';
+    echo $OUTPUT->box_end();
+
+    if ($includemessagehistorylink) {
+        echo html_writer::start_tag('div', array('class'=>'mdl-align'));
+        echo html_writer::link('history.php?user1='.$user1->id.'&user2='.$user2->id, get_string('messagehistory','message'));
+        echo html_writer::end_tag('div');
+    }
+
+
+    /// Get all the messages and print them
+
+    if ($messages = message_get_history($user1, $user2, $messagelimit)) {
+        $current->mday = '';
+        $current->month = '';
+        $current->year = '';
+        $messagedate = get_string('strftimetime');
+        $blockdate   = get_string('strftimedaydate');
+        foreach ($messages as $message) {
+            $date = usergetdate($message->timecreated);
+            if ($current->mday != $date['mday'] | $current->month != $date['month'] | $current->year != $date['year']) {
+                $current->mday = $date['mday'];
+                $current->month = $date['month'];
+                $current->year = $date['year'];
+                echo '<a name="'.$date['year'].$date['mon'].$date['mday'].'"></a>';
+                echo $OUTPUT->heading(userdate($message->timecreated, $blockdate), 4, 'center');
+            }
+            if ($message->useridfrom == $user1->id) {
+                echo message_format_message($message, $user1, $messagedate, $search, 'other');
+            } else {
+                echo message_format_message($message, $user2, $messagedate, $search, 'me');
+            }
+        }
+    } else {
+        echo $OUTPUT->heading(get_string('nomessagesfound', 'message'), 1);
+    }
+}
+
 function message_format_message(&$message, &$user, $format='', $keywords='', $class='other') {
 
     static $dateformat;
@@ -1035,8 +1240,9 @@
  * block links etc
  * @param $contact contact object containing all fields required for $OUTPUT->user_picture()
  * @param $incontactlist is the user a contact of ours?
+ * @param $selectcontacturl string the url to send the user to when a contact's name is clicked
  */
-function message_print_contactlist_user($contact, $incontactlist = true){
+function message_print_contactlist_user($contact, $incontactlist = true, $selectcontacturl = null, $showactionlinks = true) {
     global $OUTPUT;
     $fullname  = fullname($contact);
     $fullnamelink  = $fullname;
@@ -1046,7 +1252,9 @@
         $fullnamelink = '<strong>'.$fullnamelink.' ('.$contact->messagecount.')</strong>';
     }
 
+    $strcontact = $strblock = $strhistory = null;
 
+    if ($showactionlinks) {
     if($incontactlist){
         $strcontact = message_contact_link($contact->id, 'remove', true);
         $strblock   = '';
@@ -1056,6 +1264,7 @@
     }
 
     $strhistory = message_history_link($contact->id, 0, true, '', '', 'icon');
+    }
 
     echo '<tr><td class="pix">';
     echo $OUTPUT->user_picture($contact, array('size'=>20, 'courseid'=>SITEID));
@@ -1063,16 +1272,21 @@
     echo '<td class="contact">';
 
     $popupoptions = array(
-            'height' => 500,
-            'width' => 500,
+            'height' => MESSAGE_DISCUSSION_HEIGHT,
+            'width' => MESSAGE_DISCUSSION_WIDTH,
             'menubar' => false,
             'location' => false,
             'status' => true,
             'scrollbars' => true,
             'resizable' => true);
 
+    $link = $action = null;
+    if (!empty($selectcontacturl)) {
+        $link = new moodle_url($selectcontacturl.'&'.CONTACT_ID.'='.$contact->id);
+    } else {
     $link = new moodle_url("/message/discussion.php?id=$contact->id");
     $action = new popup_action('click', $link, "message_$contact->id", $popupoptions);
+    }
\ No newline at end of file
     echo $OUTPUT->action_link($link, $fullnamelink, $action, array('title'=>get_string('sendmessageto', 'message', $fullname)));
 
     echo '</td>';
Index: moodle/message/module.js
--- moodle/message/module.js Base (1.2)
+++ moodle/message/module.js Locally Modified (Based On 1.2)
@@ -5,7 +5,6 @@
 }
 
 M.core_message.init_refresh_parent_frame = function(Y, msgcount, msg) {
-
 	var add_message = function (messagestr) {
 	    var messageblock = parent.messages.document.getElementById('messages');
 	    var message = document.createElement('div');
@@ -28,3 +27,18 @@
 	}
 	setTimeout(delay_callback, delay);
 }
+
+M.core_message.init_search_page = function(Y, defaultsearchterm) {
+    this.Y = Y;
+    this.defaultsearchterm = defaultsearchterm;
+
+    var combinedsearchbox = this.Y.one('#combinedsearch');
+    combinedsearchbox.on('focus', this.combinedsearchgotfocus, this);
+}
+
+
+M.core_message.combinedsearchgotfocus = function(e) {
+    if (e.target.get('value')==this.defaultsearchterm) {
+        e.target.select();
+    }
+}
\ No newline at end of file
Index: moodle/message/output/popup/message_output_popup.php
--- moodle/message/output/popup/message_output_popup.php Base (1.9)
+++ moodle/message/output/popup/message_output_popup.php Locally Modified (Based On 1.9)
@@ -56,22 +56,42 @@
                '<tr><td align="right">'.get_string('showmessagewindow', 'message').':</td><td><input type="checkbox" name="showmessagewindow" '.($preferences->showmessagewindow==1?" checked=\"checked\"":"").' /></td></tr>'.
                '<tr><td align="right">'.get_string('blocknoncontacts', 'message').':</td><td><input type="checkbox" name="blocknoncontacts" '.($preferences->blocknoncontacts==1?" checked=\"checked\"":"").' /></td></tr>'.
                '<tr><td align="right">'.get_string('beepnewmessage', 'message').':</td><td><input type="checkbox" name="beepnewmessage" '.($preferences->beepnewmessage==1?" checked=\"checked\"":"").' /></td></tr>'.
+               '<tr><td align="right">'.get_string('htmleditor').':</td><td><input type="checkbox" name="usehtmleditor" '.($preferences->usehtmleditor==1?" checked=\"checked\"":"").' /></td></tr>'.
                '<tr><td align="right">'.get_string('noframesjs', 'message').':</td><td><input type="checkbox" name="noframesjs" '.($preferences->noframesjs==1?" checked=\"checked\"":"").' /></td></tr>'.
+               '<tr><td align="right">'.get_string('emailmessages', 'message').':</td><td><input type="checkbox" name="emailmessages" '.($preferences->emailmessages==1?" checked=\"checked\"":"").' /></td></tr>'.
+               '<tr><td align="right">'.get_string('formorethan', 'message').':</td><td><input type="text" name="emailtimenosee" id="emailtimenosee" size="2" value="'.$preferences->emailtimenosee.'" /> '.get_string('mins').'</td></tr>'.
+               '<tr><td align="right">'.get_string('email').':</td><td><input type="text" name="emailaddress" id="emailaddress" size="20" value="'.$preferences->emailaddress.'" /></td></tr>'.
+               '<tr><td align="right">'.get_string('format').':</td><td>'.$preferences->formatselect.'</td></tr>'.
                '</table>';
     }
 
     public function process_form($form, &$preferences) {
-        $preferences['message_showmessagewindow'] = $form->showmessagewindow?1:0;
-        $preferences['message_blocknoncontacts']  = $form->blocknoncontacts?1:0;
-        $preferences['message_beepnewmessage']    = $form->beepnewmessage?1:0;
-        $preferences['message_noframesjs']        = $form->noframesjs?1:0;
+        $preferences['message_showmessagewindow'] = !empty($form->showmessagewindow)?1:0;
+        $preferences['message_blocknoncontacts']  = !empty($form->blocknoncontacts)?1:0;
+        $preferences['message_beepnewmessage']    = !empty($form->beepnewmessage)?1:0;
+        $preferences['message_usehtmleditor']     = !empty($form->usehtmleditor)?1:0;
+        $preferences['message_noframesjs']        = !empty($form->noframesjs)?1:0;
+        $preferences['message_emailmessages']     = !empty($form->emailmessages)?1:0;
+        $preferences['message_emailtimenosee']    = $form->emailtimenosee;
+        $preferences['message_emailaddress']      = $form->emailaddress;
+        $preferences['message_emailformat']       = $form->emailformat;
+
         return true;
     }
     public function load_data(&$preferences, $userid) {
+        global $USER;
         $preferences->showmessagewindow =  get_user_preferences( 'message_showmessagewindow', 1, $userid);
         $preferences->blocknoncontacts  =  get_user_preferences( 'message_blocknoncontacts', '', $userid);
         $preferences->beepnewmessage    =  get_user_preferences( 'message_beepnewmessage', '', $userid);
+        $preferences->usehtmleditor     =  get_user_preferences( 'message_usehtmleditor', '', $userid);
         $preferences->noframesjs        =  get_user_preferences( 'message_noframesjs', '', $userid);
+        $preferences->emailmessages     =  get_user_preferences( 'message_emailmessages', 1, $userid);
+        $preferences->emailtimenosee    =  get_user_preferences( 'message_emailtimenosee', 10, $userid);
+        $preferences->emailaddress      =  get_user_preferences( 'message_emailaddress', $USER->email, $userid);
+        $preferences->formatselect      =  html_writer::select(array(FORMAT_PLAIN => get_string('formatplain'),
+                                                                FORMAT_HTML  => get_string('formathtml')),
+                                                                'emailformat', get_user_preferences('message_emailformat', FORMAT_PLAIN));
+
\ No newline at end of file
         return true;
     }
 }
Index: moodle/message/refresh.php
--- moodle/message/refresh.php Base (1.31)
+++ moodle/message/refresh.php Locally Modified (Based On 1.31)
@@ -76,7 +76,7 @@
     }
 }
 
-$PAGE->requires->js_init_call('M.core_message.init_refresh_parent_frame', array($jsmessages, $jsmessages));
+$PAGE->requires->js_init_call('M.core_message.init_refresh_parent_frame', array(count($jsmessages), $jsmessages));
 
 echo $OUTPUT->header();
 if (!empty($playbeep)) {
Index: moodle/message/search.html
--- moodle/message/search.html Base (1.17)
+++ moodle/message/search.html Locally Modified (Based On 1.17)
@@ -1,58 +1,15 @@
-<form id="personsearch" action="index.php" method="post">
+<form id="personsearch" method="post">
 <div><input type="hidden" name="tab" value="search" /></div>
 
-
+<div id="combinedcontactssearchspan">
 <table cellpadding="5" class="message_form boxaligncenter">
-
-
     <tr>
-        <td colspan="3" class="message_heading"><?php echo $OUTPUT->heading(get_string('searchforperson', 'message')) ?></td>
+        <td colspan="3" class="message_heading"><input type="text" name="combinedsearch" size="50" id="combinedsearch" value="<?php echo $combinedsearchstring; ?>" />
+            <input type="submit" name="combinedsubmit" value="<?php print_string('search') ?>" />
+            <a href="contacts.php?advanced=1" id="advancedcontactsearchlink"><?php print_string('advanced') ?></a>
+        </td>
     </tr>
-    <tr>
-        <td align="right"><label for="name"><?php print_string('name') ?></label></td>
-        <td><input type="text" name="name" size="16" id="name" /></td>
-        <td><input type="submit" name="personsubmit" value="<?php print_string('search') ?>" /></td>
-    </tr>
-    <tr>
-        <td>&nbsp;</td>
-        <td colspan="2">
-            <input type="checkbox" name="mycourses" id="mycourses" /><label for="mycourses"><?php print_string('onlymycourses', 'message') ?></label></td>
-    </tr>
-
-    <tr><td colspan="3"></td></tr>
-
-
-    <tr>
-        <td colspan="3" class="message_heading"><?php echo $OUTPUT->heading(get_string('searchmessages', 'message')) ?></td>
-    </tr>
-    <tr>
-        <td align="right"><label for="keywords"><?php print_string('keywords', 'message') ?></label></td>
-        <td><input type="text" name="keywords" id="keywords" size="16" /></td>
-        <td><input type="submit" name="keywordssubmit" value="<?php print_string('search') ?>" /></td>
-    </tr>
-
-    <tr>
-        <td>&nbsp;</td>
-        <td colspan="2">
-            <input type="checkbox" name="includeblocked" id="includeblocked" /><label for="includeblocked"><?php print_string('includeblockedusers', 'message') ?></label></td>
-    </tr>
-
-    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption1" value="tome" /><label for="keywordsoption1"><?php print_string('onlytome', 'message') ?></label></td></tr>
-    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption2" value="fromme" /><label for="keywordsoption2"><?php print_string('onlyfromme', 'message') ?></label></td></tr>
-    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" checked="checked" name="keywordsoption" id="keywordsoption3" value="allmine" /><label for="keywordsoption3"><?php print_string('allmine', 'message') ?></label></td></tr>
-
-    <?php if (has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) { ?>
-    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption4" value="allusers" /><label for="keywordsoption4"><?php print_string('allusers', 'message') ?></label></td></tr>
-    <?php } ?>
-
-<?php
-/* Potential abuse problems - temporarily disabled
-    echo '<tr><td colspan="3"><input type="radio" name="keywordsoption" alt="'.get_string('allstudents', 'message').'" value="courseusers" />'.get_string('allstudents', 'message').'<br />&nbsp;&nbsp;&nbsp;'.$cs.'; </td></tr>';
-
-*/
-
-?>
-
 </table>
+</div>
 
 </form>
Index: moodle/message/search_advanced.html
--- moodle/message/search_advanced.html No Base Revision
+++ moodle/message/search_advanced.html Locally New
@@ -0,0 +1,61 @@
+<form id="personsearch" method="post">
+<div><input type="hidden" name="tab" value="search" /></div>
+
+
+<div id="advancedcontactssearchspan">
+<table cellpadding="5" class="message_form boxaligncenter">
+    <tr>
+        <td colspan="3" class="message_heading"><div id="hideadvancedsearch" class="mdl-align"><a href="contacts.php" id="combinedcontactsearchlink"><?php print_string('hideadvanced','form') ?></a></div></td>
+    </tr>
+    <tr>
+        <td colspan="3" class="message_heading"><?php echo $OUTPUT->heading(get_string('searchforperson', 'message')) ?></td>
+    </tr>
+    <tr>
+        <td align="right"><label for="name"><?php print_string('name') ?></label></td>
+        <td><input type="text" name="name" size="16" id="name" value="<? echo $personsearch ?>" /></td>
+        <td><input type="submit" name="personsubmit" value="<?php print_string('search') ?>" /></td>
+    </tr>
+    <tr>
+        <td>&nbsp;</td>
+        <td colspan="2">
+            <input type="checkbox" name="mycourses" id="mycourses" /><label for="mycourses"><?php print_string('onlymycourses', 'message') ?></label></td>
+    </tr>
+
+    <tr><td colspan="3"></td></tr>
+
+
+    <tr>
+        <td colspan="3" class="message_heading"><?php echo $OUTPUT->heading(get_string('searchmessages', 'message')) ?></td>
+    </tr>
+    <tr>
+        <td align="right"><label for="keywords"><?php print_string('keywords', 'message') ?></label></td>
+        <td><input type="text" name="keywords" id="keywords" size="16" value="<? echo $messagesearch ?>" /></td>
+        <td><input type="submit" name="keywordssubmit" value="<?php print_string('search') ?>" /></td>
+    </tr>
+
+    <tr>
+        <td>&nbsp;</td>
+        <td colspan="2">
+            <input type="checkbox" name="includeblocked" id="includeblocked" /><label for="includeblocked"><?php print_string('includeblockedusers', 'message') ?></label></td>
+    </tr>
+
+    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption1" value="tome" /><label for="keywordsoption1"><?php print_string('onlytome', 'message') ?></label></td></tr>
+    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption2" value="fromme" /><label for="keywordsoption2"><?php print_string('onlyfromme', 'message') ?></label></td></tr>
+    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" checked="checked" name="keywordsoption" id="keywordsoption3" value="allmine" /><label for="keywordsoption3"><?php print_string('allmine', 'message') ?></label></td></tr>
+
+    <?php if (has_capability('moodle/site:readallmessages', get_context_instance(CONTEXT_SYSTEM))) { ?>
+    <tr><td>&nbsp;</td><td colspan="2"><input type="radio" name="keywordsoption" id="keywordsoption4" value="allusers" /><label for="keywordsoption4"><?php print_string('allusers', 'message') ?></label></td></tr>
+    <?php } ?>
+
+<?php
+/* Potential abuse problems - temporarily disabled
+    echo '<tr><td colspan="3"><input type="radio" name="keywordsoption" alt="'.get_string('allstudents', 'message').'" value="courseusers" />'.get_string('allstudents', 'message').'<br />&nbsp;&nbsp;&nbsp;'.$cs.'; </td></tr>';
+
+*/
+
+?>
+
+</table>
+</div>
+
+</form>
Index: moodle/message/send.php
--- moodle/message/send.php Base (1.45)
+++ moodle/message/send.php Locally Modified (Based On 1.45)
@@ -102,7 +102,7 @@
                    '<span class="time">['.$time.']</span>: '.
                    '<span class="content">'.$message.'</span></div>';
         //$PAGE->requires->js_function_call('parent.messages.document.write', Array($message));
-        $PAGE->requires->js_function_call('add_message', Array($message));
\ No newline at end of file
+        $PAGE->requires->js_function_call('parent.refresh.add_message', Array($message));
\ No newline at end of file
         $PAGE->requires->js_function_call('parent.messages.scroll', Array(1,5000000));
 
         add_to_log(SITEID, 'message', 'write', 'history.php?user1='.$user->id.'&amp;user2='.$USER->id.'#m'.$messageid, $user->id);
Index: moodle/testbackup.php
--- moodle/testbackup.php No Base Revision
+++ moodle/testbackup.php Locally New
@@ -0,0 +1,11 @@
+<?php
+ 
+require_once('config.php');
+require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
+
+$course_module_to_backup = 9; // Set this to one existing choice cmid in your dev site
+$user_doing_the_backup   = 2;  // Set this to the id of your admin accouun
+ 
+$bc = new backup_controller(backup::TYPE_1ACTIVITY, $course_module_to_backup, backup::FORMAT_MOODLE,
+                            backup::INTERACTIVE_NO, backup::MODE_GENERAL, $user_doing_the_backup);
+$bc->execute_plan();
Index: moodle/theme/standard/style/message.css
--- moodle/theme/standard/style/message.css Base (1.1)
+++ moodle/theme/standard/style/message.css Locally Modified (Based On 1.1)
@@ -29,3 +29,13 @@
 
 .message .note {padding:10px;}
 table.message .searchresults td {padding:5px;}
+
+.message .userselector {width:25%;float:left;}
+.message .messagearea  {border-left:1px solid gray;width:74%;float:right;min-height:150px;}
+.message .messagearea .messagehistory {padding-left:20px;}
+.message .messagearea .messagesend {padding-top:20px;}
+.message .messagearea .messagesend .messagesendbox {width:80%}
+
+.messagesearchresults {margin-left:auto;margin-right:auto;border:;}
+.messagesearchresults td {padding:0px 10px 0px 20px;}
+.messagesearchresults td span {white-space:nowrap;}
