]> git.mjollnir.org Git - moodle.git/commitdiff
Latest messaging system
authormoodler <moodler>
Tue, 28 Dec 2004 13:49:15 +0000 (13:49 +0000)
committermoodler <moodler>
Tue, 28 Dec 2004 13:49:15 +0000 (13:49 +0000)
Needs a lot of work still but you can now manage your contact list
and send/receive messages from people so it's usable!

message/history.php [new file with mode: 0644]
message/index.php
message/lib.php
message/search.html
message/settings.html [new file with mode: 0644]
message/user.php [new file with mode: 0644]

diff --git a/message/history.php b/message/history.php
new file mode 100644 (file)
index 0000000..43ef2bb
--- /dev/null
@@ -0,0 +1,17 @@
+<?php // $Id$
+      // For listing message histories
+      
+    require('../config.php');
+
+    require_login();
+
+/// Script parameters
+    $userid = required_param('id', PARAM_INT);
+
+/// Check the user we are talking to is valid
+    if (! $user = get_record("user", "id", $userid)) {
+        error("User ID was incorrect");
+    }
+
+    print_heading('This script is not completed yet');
+?>
index c1a0f7d62ef88bd7e1c45949340e106a175063e4..0fed964cadaa1cf42de9dbec51ed9413dc20781c 100644 (file)
@@ -4,26 +4,44 @@
 require('../config.php');
 require('lib.php');
 
-$tab = optional_param('tab', 'contacts');
-$ftab = 'message_print_'.$tab;
+require_login(0, false);
 
+/// optional variables that may be passed in
+$tab            = optional_param('tab',       'contacts'); // current tab - default to contacts
+$addcontact     = optional_param('addcontact',     false); // adding a contact
+$removecontact  = optional_param('removecontact',  false); // removing a contact
+$blockcontact   = optional_param('blockcontact',   false); // blocking a contact
+$unblockcontact = optional_param('unblockcontact', false); // unblocking a contact
 
+if (($addcontact     !== false) and confirm_sesskey()) message_add_contact($addcontact);
+if (($removecontact  !== false) and confirm_sesskey()) message_remove_contact($removecontact);
+if (($blockcontact   !== false) and confirm_sesskey()) message_block_contact($blockcontact);
+if (($unblockcontact !== false) and confirm_sesskey()) message_unblock_contact($unblockcontact);
 
 
+/// a print function is associated with each tab
+$tabprintfunction = 'message_print_'.$tab;
 
-print_header(get_string('messaging').' - '.$SITE->fullname);
+
+print_header(get_string('messages', 'message').' - '.$SITE->fullname);
 
 ?>
 
-<table cellspacing="2" cellpadding="2" border="0" bgcolor="#ffffff" align="center" width="80%">
+<table cellspacing="2" cellpadding="2" border="0" align="center" width="95%">
 <tr>
-    <th class="message_tab_selected"><a href="<?php echo $ME ?>?tab=contacts">contacts</a></th>
-    <th class="message_tab"><a href="<?php echo $ME ?>?tab=search">search</a></th>
-    <th class="message_tab"><a href="<?php echo $ME ?>?tab=settings">settings</a></th>
+    <th class="<?php echo ($tab == 'contacts') ? 'generaltabselected' : 'generaltab' ?>">
+        <a href="<?php echo $ME ?>?tab=contacts">contacts</a>
+    </th>
+    <th class="<?php echo ($tab == 'search') ? 'generaltabselected' : 'generaltab' ?>">
+        <a href="<?php echo $ME ?>?tab=search">search</a>
+    </th>
+    <th class="<?php echo ($tab == 'settings') ? 'generaltabselected' : 'generaltab' ?>">
+        <a href="<?php echo $ME ?>?tab=settings">settings</a>
+    </th>
 </tr>
 <tr>
-    <td colspan="3">
-        <?php if (function_exists($ftab)) $ftab(); ?>
+    <td colspan="3" bgcolor="#ffffff">
+        <?php if (function_exists($tabprintfunction)) $tabprintfunction(); ?>
     </td>
 </tr>
 </table>
index 326dbfb2d29eaaa90b926da2cddbabc8a7749219..6d87aead93c0b3c0c8e0736eef941e8d60dc352d 100644 (file)
 <?php
 /// library functions for messaging
 
-/// todo: add some functions
+
+define ('MESSAGE_SHORTLENGTH', 300);
 
 
 function message_print_contacts() {
-    global $USER;
-    $contacts = get_records('message_contacts', 'userid', $USER->id, '', 'id, contactid');
-    echo 'contacts';
+    global $USER, $CFG;
+
+    $timetoshowusers = 300; //Seconds default
+    if (isset($CFG->block_online_users_timetosee)) {
+        $timetoshowusers = $CFG->block_online_users_timetosee * 60;
+    }
+    $timefrom = time()-$timetoshowusers;
+
+    
+    /// get lists of contacts and unread messages
+    $onlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture
+                                       FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
+                                       WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess>=$timefrom 
+                                         AND mc.blocked='0' 
+                                       ORDER BY u.lastaccess DESC");
+
+    $offlinecontacts = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.picture
+                                       FROM {$CFG->prefix}user u, {$CFG->prefix}message_contacts mc
+                                       WHERE mc.userid='$USER->id' AND u.id=mc.contactid AND u.lastaccess<$timefrom
+                                         AND mc.blocked='0' 
+                                       ORDER BY u.lastaccess DESC");
+
+    $unreadmessages = get_records_sql("SELECT m.id, m.useridfrom, u.firstname, u.lastname, u.picture 
+                                       FROM {$CFG->prefix}user u, {$CFG->prefix}message m 
+                                       WHERE m.useridto='$USER->id' AND u.id=m.useridfrom");
+
+    $blockedcontacts = get_records_select('message_contacts', "userid='$USER->id' AND blocked='1'", '', 'contactid, id');
+
+
+    echo '<table id="message_contacts" align="center" cellspacing="2" cellpadding="0">';
+    echo '<tr><td colspan="2"><strong>'.get_string('mycontacts', 'message').'</strong></td></tr>';
+
+
+/// print out list of online contacts
+    echo '<tr><td width="20">&nbsp;</td>';
+    echo '<td id="message_onlinecontacts">';
+
+    $countcontacts = (is_array($onlinecontacts)) ? count($onlinecontacts) : 0;
+    
+    echo '<table class="message_contacts">';
+    echo '<tr><td colspan="3">';
+    echo '<strong>'.get_string('onlinecontacts', 'message', $countcontacts).'</strong>';
+    echo '</td></tr>';
+    
+    if (!empty($onlinecontacts)) {
+        foreach ($onlinecontacts as $contact) {
+            if ($contact->blocked == 1) continue;
+            $strcontact  = '';
+        /// are there any unread messages for this contact?
+            if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
+                $strcontact .= '<strong>( '.get_string('unreadmessages', 'message', $unread).')</strong>';
+            }
+        /// link to remove from contact list
+            $strcontact .= ' [<a href="index.php?tab=contacts&amp;removecontact='.$contact->id.
+                           '&amp;sesskey='.$USER->sesskey.'" title="'.
+                           get_string('removecontact', 'message').'">'.
+                           get_string('removecontact', 'message').'</a>]</td>';
+            
+            echo '<tr><td class="message_pic">';
+            print_user_picture($contact->id, SITEID, $contact->picture, 20, false, false);
+            echo '</td>';
+            echo '<td class="message_contact">';
+            link_to_popup_window("/message/user.php?id=$contact->id", "message_$contact->id", fullname($contact), 400, 400, get_string('sendmessageto', 'message', fullname($contact)));
+            echo '</td>';
+            echo '<td class="message_link">'.$strcontact.'</td>';
+            echo '</tr>';
+        }
+    }
+    echo '<tr><td colspan="3">&nbsp;</td></tr>';
+    echo '</table>';
+
+    echo '</td></tr>';
+
+
+/// print out list of offline contacts
+    echo '<tr><td width="20">&nbsp;</td>';
+    echo '<td id="message_offlinecontacts">';
+    
+    $countcontacts = (is_array($offlinecontacts)) ? count($offlinecontacts) : 0;
+    
+    echo '<table class="message_contacts">';
+    echo '<tr><td colspan="3">';
+    echo '<strong>'.get_string('offlinecontacts', 'message', $countcontacts).'</strong>';
+    echo '</td></tr>';
+    
+    if (!empty($offlinecontacts)) {
+        foreach ($offlinecontacts as $contact) {
+            if ($contact->blocked == 1) continue;
+            $strcontact  = '';
+        /// are there any unread messages for this contact?
+            if (($unread = message_count_messages($unreadmessages, 'useridfrom', $contact->id)) > 0) {
+                $strcontact .= '<strong>( '.get_string('unreadmessages', 'message', $unread).')</strong>';
+            }
+        /// link to remove from contact list
+            $strcontact .= ' [<a href="index.php?tab=contacts&amp;removecontact='.$contact->id.
+                           '&amp;sesskey='.$USER->sesskey.'" title="'.
+                           get_string('removecontact', 'message').'">'.
+                           get_string('removecontact', 'message').'</a>]</td>';
+            
+            echo '<tr><td class="message_pic">';
+            print_user_picture($contact->id, SITEID, $contact->picture, 20, false, false);
+            echo '</td>';
+            echo '<td class="message_contact">';
+            link_to_popup_window("/message/user.php?id=$contact->id", "message_$contact->id", fullname($contact), 400, 400, get_string('sendmessageto', 'message', fullname($contact)));
+            echo '</td>';
+            echo '<td class="message_link">'.$strcontact.'</td>';
+            echo '</tr>';
+        }
+    }
+    echo '<tr><td colspan="3">&nbsp;</td></tr>';
+    echo '</table>';
+
+    echo '</td></tr>';
+    
+
+/// Cycle through messages and extract those that are from unknown contacts
+/// We can take advantage of the keys for $onlinecontacts and $offlinecontacts
+/// which are set to the userid and therefore we just need to see if the key
+/// exists in either of those arrays
+/// We can also discard any messages from users in our blocked contact list
+    $unknownmessages = array();
+    if (!empty($unreadmessages)) {
+    /// make sure we have valid arrays to test against - they may be boolean false
+        if (empty($onlinecontacts))  $onlinecontacts  = array();
+        if (empty($offlinecontacts)) $offlinecontacts = array();
+        if (empty($blockedcontacts)) $blockedcontacts = array();
+        foreach ($unreadmessages as $unreadmessage) {
+            if (array_key_exists($unreadmessage->useridfrom, $onlinecontacts) or 
+                array_key_exists($unreadmessage->useridfrom, $offlinecontacts) or
+                array_key_exists($unreadmessage->useridfrom, $blockedcontacts) ) {
+                continue;
+            }
+            if (!isset($unknownmessages[$unreadmessage->useridfrom])) {
+                $message = $unreadmessage;
+                $message->count = 1;
+                $unknownmessages[$unreadmessage->useridfrom] = $message;
+            } else {
+                $unknownmessages[$unreadmessage->useridfrom]->count++;
+            }
+        }
+    }
+
+/// print out list of incoming contacts
+    if (!empty($unknownmessages)) {
+        echo '<tr><td colspan="2">';
+        echo '<strong>'.get_string('incomingcontacts', 'message', count($unknownmessages)).'</strong>';
+        echo '</td></tr>';
+        echo '<tr><td width="20">&nbsp;</td>';
+        echo '<td id="message_unknowncontacts">';
+
+        echo '<table class="message_contacts">';
+        foreach ($unknownmessages as $messageuser) {
+            $strcontact = '<strong>( '.get_string('unreadmessages', 'message', $messageuser->count).')</strong>';
+        /// link to add to contact list
+            $strcontact .= ' [<a href="index.php?tab=contacts&amp;addcontact='.$messageuser->useridfrom.
+                           '&amp;sesskey='.$USER->sesskey.'" title="'.
+                           get_string('addcontact', 'message').'">'.
+                           get_string('addcontact', 'message').'</a>]</td>';
+            $strblock = '[<a href="index.php?tab=contacts&amp;blockcontact='.$messageuser->useridfrom.
+                        '&amp;sesskey='.$USER->sesskey.'" title="'.
+                        get_string('blockcontact', 'message').'">'.
+                        get_string('blockcontact', 'message').'</a>]</td>';
+            
+            echo '<tr><td class="message_pic">';
+            print_user_picture($messageuser->useridfrom, SITEID, $messageuser->picture, 20, false, false);
+            echo '</td>';
+            echo '<td class="message_contact">';
+            link_to_popup_window("/message/user.php?id=$messageuser->useridfrom", "message_$messageuser->useridfrom", fullname($messageuser), 400, 400, get_string('sendmessageto', 'message', fullname($messageuser)));
+            echo '</td>';
+            echo '<td class="message_link">'.$strcontact.'</td>';
+            echo '<td class="message_link">'.$strblock.'</td>';
+            echo '</tr>';
+        }
+        echo '</table>';
+        echo '</td></tr>';
+    }
+
+    echo '</table>';
+}
+
+
+
+
+/// $messagearray is an array of objects
+/// $field is a valid property of object
+/// $value is the value $field should equal to be counted
+/// if $field is empty then return count of the whole array
+/// if $field is non-existent then return 0;
+function message_count_messages($messagearray, $field='', $value='') {
+    if (!is_array($messagearray)) return 0;
+    if ($field == '' or empty($messagearray)) return count($messagearray);
+    
+    $count = 0;
+    foreach ($messagearray as $message) {
+        $count += ($message->$field == $value) ? 1 : 0;
+    }
+    return $count;
 }
 
+
 function message_print_search() {
     global $USER;
     
@@ -18,7 +214,6 @@ function message_print_search() {
         message_print_search_results($frm);
         
     } else {
-    /// todo make the following queries more efficient
         if ($teachers = get_records('user_teachers', 'userid', $USER->id, '', 'id, course')) {
         
             $courses = get_courses('all', 'c.sortorder ASC', 'c.id, c.shortname');
@@ -34,21 +229,450 @@ function message_print_search() {
 }
 
 function message_print_settings() {
+    global $ME, $USER;
+    
     if ($frm = data_submitted()) {
-        echo 'settings submitted - quick do something';
+        $pref = array();
+        $pref['message_showmessagewindow'] = (isset($frm->showmessagewindow)) ? '1' : '0';
+        $pref['message_beepnewmessage'] = (isset($frm->beepnewmessage)) ? '1' : '0';
+        $pref['message_maxmessages'] = ((int)$frm->maxmessages > 0) ? (int)$frm->maxmessages : '20';
+        $pref['message_deletemessagesdays'] = ((int)($frm->deletemessagesdays) > 0) ? (int)$frm->deletemessagesdays : '30';
+        $pref['message_emailmessages'] = (isset($frm->emailmessages)) ? '1' : '0';
+        $pref['message_emailaddress'] = (!empty($frm->emailaddress)) ? $frm->emailaddress : $USER->email;
+        $pref['message_emailformat'] = (isset($frm->emailformat)) ? $frm->emailformat : FORMAT_PLAIN;
+        $pref['message_emailtimenosee'] = ((int)$frm->emailtimenosee > 0) ? (int)$frm->emailtimenosee : '10';
+
+        set_user_preferences($pref);
+        
+        redirect($ME, get_string('settingssaved', 'message'), 3);
+    }
+
+    $cbshowmessagewindow = (get_user_preferences('message_showmessagewindow', 1) == '1') ? 'checked="checked"' : '';
+    $cbbeepnewmessage = (get_user_preferences('message_beepnewmessage', 1) == '1') ? 'checked="checked"' : '';
+    $txmaxmessages = get_user_preferences('message_maxmessages', 20);
+    $txdeletemessagesdays = get_user_preferences('message_deletemessagesdays', 30);
+    $cbemailmessages = (get_user_preferences('message_emailmessages', 1) == '1') ? 'checked="checked"' : '';
+    $txemailaddress = get_user_preferences('message_emailaddress', $USER->email);
+    $txemailtimenosee = get_user_preferences('message_emailtimenosee', 10);
+    $format_select = choose_from_menu( array(FORMAT_PLAIN => get_string('formatplain'),
+                                             FORMAT_HTML  => get_string('formathtml')),
+                                       'emailformat',
+                                       get_user_preferences('message_emailformat', FORMAT_PLAIN),
+                                       false, '', '0', true );
+    
+    include('settings.html');
+}
+
+
+
+function message_add_contact($contactid, $blocked=0) {
+    global $USER;
+    
+    if (!record_exists('user', 'id', $contactid)) { // invalid userid
+        return false;
+    }
+    
+    if (($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid)) !== false) {
+    /// record already exists - we may be changing blocking status
+    
+        if ($contact->blocked !== $blocked) {
+        /// change to blocking status
+            $contact->blocked = $blocked;
+            return update_record('message_contacts', $contact);
+        } else {
+        /// no changes to blocking status
+            return true;
+        }
+        
     } else {
-        echo 'settings form';
+    /// new contact record
+        unset($contact);
+        $contact->userid = $USER->id;
+        $contact->contactid = $contactid;
+        $contact->blocked = $blocked;
+        return insert_record('message_contacts', $contact, false);
     }
 }
 
+function message_remove_contact($contactid) {
+    global $USER;
+
+    return delete_records('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
+}
+
+function message_unblock_contact($contactid) {
+    return message_add_contact($contactid, 0);
+}
+
+function message_block_contact($contactid) {
+    return message_add_contact($contactid, 1);
+}
+
+function message_get_contact($contactid) {
+    global $USER;
+    return get_record('message_contacts', 'userid', $USER->id, 'contactid', $contactid);
+}
+    
+
+
 function message_print_search_results($frm) {
-    if (!empty($frm->personsubmit)) {
-        echo 'searched for person';
-    } else if (!empty($frm->keywordssubmit)) {
-        echo 'searched for keywords';
+    global $USER;
+
+    echo '<div align="center">';
+
+    /// search for person
+    if (!empty($frm->personsubmit) and !empty($frm->name)) {
+    
+        if ($frm->mycourses) {
+            $users = array();
+            $mycourses = get_my_courses($USER->id);
+            foreach ($mycourses as $mycourse) {
+                if (is_array($susers = message_search_users($mycourse->id, $frm->name))) {
+                    foreach ($susers as $suser) $users[$suser->id] = $suser;
+                }
+            }
+        } else {
+            $users = message_search_users(SITEID, $frm->name);
+        }
+
+        if (!empty($users)) {
+            echo '<strong>'.get_string('userssearchresults', 'message', count($users)).'</strong>';
+            echo '<table class="message_users">';
+            foreach ($users as $user) {
+                if (($contact = message_get_contact($user->id)) !== false)  {
+                    if ($contact->blocked == 0) { /// not blocked
+                        $strcontact = '[<a href="index.php?tab=contacts&amp;removecontact='.$user->id.
+                                      '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                      get_string('removecontact', 'message').'">'.
+                                      get_string('removecontact', 'message').'</a>]</td>';
+                        $strblock = '[<a href="index.php?tab=contacts&amp;blockcontact='.$user->id.
+                                    '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                    get_string('blockcontact', 'message').'">'.
+                                    get_string('blockcontact', 'message').'</a>]</td>';
+                    } else { // blocked
+                        $strcontact = '[<a href="index.php?tab=contacts&amp;unblockcontact='.$user->id.
+                                      '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                      get_string('addcontact', 'message').'">'.
+                                      get_string('addcontact', 'message').'</a>]</td>';
+                        $strblock = '[<a href="index.php?tab=contacts&amp;removecontact='.$user->id.
+                                    '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                    get_string('unblockcontact', 'message').'">'.
+                                    get_string('unblockcontact', 'message').'</a>]</td>';
+
+                    }
+
+                } else {
+                    $strcontact = '[<a href="index.php?tab=contacts&amp;addcontact='.$user->id.
+                                  '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                  get_string('addcontact', 'message').'">'.
+                                  get_string('addcontact', 'message').'</a>]</td>';
+                    $strblock = '[<a href="index.php?tab=contacts&amp;blockcontact='.$user->id.
+                                '&amp;sesskey='.$USER->sesskey.'" title="'.
+                                get_string('blockcontact', 'message').'">'.
+                                get_string('blockcontact', 'message').'</a>]</td>';
+
+                }
+                echo '<tr><td class="message_pic">';
+                print_user_picture($user->id, SITEID, $user->picture, 20, false, false);
+                echo '</td>';
+                echo '<td class="message_contact">';
+                link_to_popup_window("/message/user.php?id=$user->id", "message_$user->id", fullname($user), 400, 400, get_string('sendmessageto', 'message', fullname($user)));
+                echo '</td>';
+                
+                echo '<td class="message_link">'.$strcontact.'</td>';
+                echo '<td class="message_link">'.$strblock.'</td>';
+                echo '</tr>';
+            }
+            echo '</table>';
+                
+        } else {
+            notify(get_string('nosearchresults', 'message'));
+        }
+        
+        
+    /// search messages for keywords
+    } else if (!empty($frm->keywordssubmit) and !empty($frm->keywords)) {
+        $keywords = explode(' ', $frm->keywords);
+        $tome     = false;
+        $fromme   = false;
+        $courseid = 'none';
+
+        switch ($frm->keywordsoption) {
+            case 'tome':
+                $tome   = true;
+                break;
+            case 'fromme':
+                $fromme = true;
+                break;
+            case 'allmine':
+                $tome   = true;
+                $fromme = true;
+                break;
+            case 'allusers':
+                $courseid = SITEID;
+                break;
+            case 'courseusers':
+                $courseid = $frm->courseid;
+                break;
+            default:
+                $tome   = true;
+                $fromme = true;
+        }
+
+        if (($messages = message_search($keywords, $fromme, $tome, $courseid)) !== false) {
+        
+        /// get a list of contacts
+            $contacts = get_records_sql("SELECT contactid, blocked FROM {$CFG->prefix}message_contacts
+                                         WHERE userid='$USER->id'");
+                                         
+            echo '<strong>'.get_string('keywordssearchresults', 'message', count($messages)).'</strong>';
+            echo '<table class="message_users">';
+
+            foreach ($messages as $message) {
+            /// ignore messages from blocked users
+                if ((!$frm->includeblocked) and isset($contacts[$message->useridfrom]) and ($contacts[$message->useridfrom]->blocked == 1)) {
+                    continue;
+                }
+                echo '<tr><td class="message_pic">';
+                print_user_picture($message->useridfrom, SITEID, $message->picture, 20, false, false);
+                echo '</td>';
+                echo '<td class="message_contact">';
+                link_to_popup_window("/message/user.php?id=$message->useridfrom", "message_$message->useridfrom", fullname($message), 400, 400, get_string('sendmessageto', 'message', fullname($message)));
+                echo '</td>';
+                echo '<td>'.message_shorten_message($message->message, 20).'</td>';
+                echo '</tr>';
+             }
+
+            echo '</table>';
+        
+        } else {
+            notify(get_string('nosearchresults', 'message'));
+        }
+
+
+    /// what the ????, probably an empty search string, duh!
+    } else {
+        notify(get_string('emptysearchstring', 'message'));
+    }
+
+    print_single_button($ME, array( 'tab' => 'search'), get_string('newsearch', 'message') );
+
+    echo '</div>';
+}
+
+
+
+
+/**
+ * Search through course users
+ *
+ * If $coursid specifies the site course then this function searches 
+ * through all undeleted and confirmed users
+ *
+ * @uses $CFG
+ * @uses SITEID
+ * @param int $courseid The course in question.
+ * @param string $searchtext ?
+ * @param string $sort ?
+ * @param string $exceptions ? 
+ * @return array  An array of {@link $USER} records.
+ * @todo Finish documenting this function
+ */
+function message_search_users($courseid, $searchtext, $sort='', $exceptions='') {
+    global $CFG;
+
+    switch ($CFG->dbtype) {
+        case 'mysql':
+             $fullname = ' CONCAT(u.firstname," ",u.lastname) ';
+             $LIKE = 'LIKE';
+             break;
+        case 'postgres7':
+             $fullname = " u.firstname||' '||u.lastname ";
+             $LIKE = 'ILIKE';
+             break;
+        default:
+             $fullname = ' u.firstname||" "||u.lastname ';
+             $LIKE = 'ILIKE';
+    }
+
+    if (!empty($exceptions)) {
+        $except = ' AND u.id NOT IN ('. $exceptions .') ';
+    } else {
+        $except = '';
+    }
+
+    if (!empty($sort)) {
+        $order = ' ORDER BY '. $sort;
+    } else {
+        $order = '';
+    }
+
+    $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
+
+    if (!$courseid or $courseid == SITEID) {
+        return get_records_sql("SELECT u.id, u.firstname, u.lastname
+                      FROM {$CFG->prefix}user u
+                      WHERE $select
+                          AND ($fullname $LIKE '%$searchtext%')
+                          $except $order");
+    } else {
+
+
+        if (!$teachers = get_records_sql("SELECT u.id, u.firstname, u.lastname
+                      FROM {$CFG->prefix}user u,
+                           {$CFG->prefix}user_teachers s
+                      WHERE $select AND s.course = '$courseid' AND s.userid = u.id
+                          AND ($fullname $LIKE '%$searchtext%')
+                          $except $order")) {
+            $teachers = array();
+        }
+        if (!$students = get_records_sql("SELECT u.id, u.firstname, u.lastname
+                      FROM {$CFG->prefix}user u,
+                           {$CFG->prefix}user_students s
+                      WHERE $select AND s.course = '$courseid' AND s.userid = u.id
+                          AND ($fullname $LIKE '%$searchtext%')
+                          $except $order")) {
+            $students = array();
+        }
+        return $teachers + $students;
+    }
+}
+
+
+
+
+function message_search($searchterms, $fromme=true, $tome=true, $courseid='none') {
+/// Returns a list of posts found using an array of search terms
+/// eg   word  +word -word
+///
+
+    global $CFG, $USER;
+
+    /// Some differences in syntax for PostgreSQL
+    if ($CFG->dbtype == "postgres7") {
+        $LIKE = "ILIKE";   // case-insensitive
+        $NOTLIKE = "NOT ILIKE";   // case-insensitive
+        $REGEXP = "~*";
+        $NOTREGEXP = "!~*";
+    } else {
+        $LIKE = "LIKE";
+        $NOTLIKE = "NOT LIKE";
+        $REGEXP = "REGEXP";
+        $NOTREGEXP = "NOT REGEXP";
+    }
+
+    $messagesearch = "";
+
+    foreach ($searchterms as $searchterm) {
+        if (strlen($searchterm) < 2) {
+            continue;
+        }
+        if ($messagesearch) {
+            $messagesearch .= " AND ";
+        }
+
+        if (substr($searchterm,0,1) == "+") {
+            $searchterm = substr($searchterm,1);
+            $messagesearch .= " m.message $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
+        } else if (substr($searchterm,0,1) == "-") {
+            $searchterm = substr($searchterm,1);
+            $messagesearch .= " m.message $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
+        } else {
+            $messagesearch .= " m.message $LIKE '%$searchterm%' ";
+        }
     }
 
-    print_single_button($ME, array( 'tab' => 'search'), get_string('newsearch') );
+
+    $messagesearch = "($messagesearch) ";
+
+
+    /////////////////////////////////////
+    
+    if ($courseid !== SITEID) {
+        if ($courseid == 'none') {
+            if     ($fromme and $tome) $messagesearch .= "AND (m.useridfrom='$USER->id' OR m.useridto='$USER->id') ";
+            elseif ($fromme)           $messagesearch .= "AND m.useridfrom='$USER->id' ";
+            elseif ($tome)             $messagesearch .= "AND m.useridto='$USER->id' ";
+        } else {
+            /// Code in here for searching for messages between users in a particular course
+            /// This is not implemented at present because of potential abuse issues
+            /// Temporary measure, in case we ever get here is all the users messages
+            $messagesearch .= "AND (m.useridto='$USER->id' OR m.useridfrom='$USER->id')  ";
+        }
+    }
+
+    $messages = array();
+
+    if (($m_unread = get_records_sql("SELECT m.id, m.useridfrom, m.message, u.firstname, u.lastname, u.picture 
+                            FROM {$CFG->prefix}user u, {$CFG->prefix}message m
+                            WHERE $messagesearch AND u.id=m.useridfrom ") ) !== false) {
+        foreach ($m_unread as $m) $messages[] = $m;
+    }
+
+    if (($m_read = get_records_sql("SELECT m.id, m.useridfrom, m.message_read, u.firstname, u.lastname, u.picture 
+                            FROM {$CFG->prefix}user u, {$CFG->prefix}message m
+                            WHERE $messagesearch AND u.id=m.useridfrom ") ) !== false) {
+        foreach ($m_read as $m) $messages[] = $m;
+    }
+
+    ///////////////////////////////////////
+
+    return (empty($messages)) ? false : $messages;
 }
 
+
+
+/// Borrowed with changes from mod/forum/lib.php
+function message_shorten_message($message, $minlength=0) {
+// Given a post object that we already know has a long message
+// this function truncates the message nicely to the first
+// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
+
+    $i = 0;
+    $tag = false;
+    $length = strlen($message);
+    $count = 0;
+    $stopzone = false;
+    $truncate = 0;
+    if ($minlength == 0) $minlength = MESSAGE_SHORTLENGTH;
+    
+
+    for ($i=0; $i<$length; $i++) {
+        $char = $message[$i];
+
+        switch ($char) {
+            case "<":
+                $tag = true;
+                break;
+            case ">":
+                $tag = false;
+                break;
+            default:
+                if (!$tag) {
+                    if ($stopzone) {
+                        if ($char == '.' or $char == ' ') {
+                            $truncate = $i+1;
+                            break 2;
+                        }
+                    }
+                    $count++;
+                }
+                break;
+        }
+        if (!$stopzone) {
+            if ($count > $minlength) {
+                $stopzone = true;
+            }
+        }
+    }
+
+    if (!$truncate) {
+        $truncate = $i;
+    }
+
+    return substr($message, 0, $truncate);
+}
+
+
+
 ?>
index 0981c63267b5bb1ac41d66d0d455af602ea5deac..2edb85051d8ada67abe730967b94071e0ddb896b 100644 (file)
@@ -1,11 +1,12 @@
 <form name="personsearch" action="<?php echo $ME ?>" method="post">
 <input type="hidden" name="tab" value="search" />
 
+
 <table cellpadding="5" align="center">
 
 
     <tr>
-        <td colspan="3"><strong><?php print_string('searchforperson') ?></strong></td>
+        <td colspan="3"><strong><?php print_string('searchforperson', 'message') ?></strong></td>
     </tr>
     <tr>
         <td align="right"><?php print_string('name') ?>:</td>
         <td><input type="submit" name="personsubmit" value="<?php print_string('search') ?>" /></td>
     </tr>
     <tr>
-        <td colspan="3"><input type="checkbox" name="mycourses" alt="<?php print_string('onlyinmycourses') ?>" /><?php print_string('onlyinmycourses') ?></td>
+        <td>&nbsp;</td>
+        <td colspan="2"><input type="checkbox" name="mycourses" alt="<?php print_string('onlymycourses', 'message') ?>" /><?php print_string('onlymycourses', 'message') ?></td>
     </tr>
     
     <tr><td colspan="3"><hr /></td></tr>
 
+
     <tr>
-        <td colspan="3"><strong><?php print_string('searchformessage') ?></strong></td>
+        <td colspan="3"><strong><?php print_string('searchmessages', 'message') ?></strong></td>
     </tr>
     <tr>
-        <td align="right"><?php print_string('keywords') ?>:</td>
-        <td><input type="text" name="name" size="20" alt="<?php print_string('keywords')?>" /></td>
+        <td align="right"><?php print_string('keywords', 'message') ?>:</td>
+        <td><input type="text" name="keywords" size="20" alt="<?php print_string('keywords', 'message')?>" /></td>
         <td><input type="submit" name="keywordssubmit" value="<?php print_string('search') ?>" /></td>
     </tr>
-    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('onlytome') ?>" /><?php print_string('onlytome') ?></td></tr>
-    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('onlyfromme') ?>" /><?php print_string('onlyfromme') ?></td></tr>
-    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('allmine') ?>" /><?php print_string('allmine') ?></td></tr>
+    
+    <tr>
+        <td>&nbsp;</td>
+        <td colspan="2"><input type="checkbox" name="includeblocked" alt="<?php print_string('includeblockedusers', 'message') ?>" /><?php print_string('includeblockedusers', 'message') ?></td>
+    </tr>
+    
+    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('onlytome', 'message') ?>" value="tome" checked="checked" /><?php print_string('onlytome', 'message') ?></td></tr>
+    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('onlyfromme', 'message') ?>" value="fromme" /><?php print_string('onlyfromme', 'message') ?></td></tr>
+    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('allmine', 'message') ?>" value="allmine" /><?php print_string('allmine', 'message') ?></td></tr>
     
     <?php if (isadmin()) { ?>
-    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('allusers') ?>" /><?php print_string('allusers') ?></td></tr>
+    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('allusers', 'message') ?>" value="allusers" /><?php print_string('allusers', 'message') ?></td></tr>
     <?php } ?>
-    
-    <tr><td colspan="3"><input type="radio" name="keywordsoption" alt="<?php print_string('allstudents') ?>" /><?php print_string('allstudents'); ?><?php echo $cs; ?></td></tr>
 
+<?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>
 
diff --git a/message/settings.html b/message/settings.html
new file mode 100644 (file)
index 0000000..bd771dd
--- /dev/null
@@ -0,0 +1,64 @@
+<form name="message_settings" action="<?php echo $ME ?>" method="post">
+<input type="hidden" name="tab" value="settings" />
+
+
+<table cellpadding="5" align="center">
+
+
+    <tr valign="top">
+        <td align="right"><input type="checkbox" name="showmessagewindow" alt="<?php print_string('showmessagewindow', 'message') ?>" <?php echo $cbshowmessagewindow ?> /></td>
+        <td colspan="2"><?php print_string('showmessagewindow', 'message') ?></td>
+    </tr>
+    <tr valign="top">
+        <td align="right"><input type="checkbox" name="beepnewmessage" alt="<?php print_string('beepnewmessage', 'message') ?>" <?php echo $cbbeepnewmessage ?>  /></td>
+        <td colspan="2"><?php print_string('beepnewmessage', 'message') ?></td>
+    </tr>
+
+    
+    <tr><td colspan="3"><hr /></td></tr>
+
+
+    <tr valign="top">
+        <td><input type="text" name="maxmessages" size="2" value="<?php echo $txmaxmessages ?>" alt="<?php print_string('maxmessages', 'message') ?>" /></td>
+        <td colspan="2"><?php print_string('maxmessages', 'message') ?></td>
+    </tr>
+    <tr valign="top">
+        <td><input type="text" name="deletemessagesdays" size="2" value="<?php echo $txdeletemessagesdays ?>" alt="<?php print_string('deletemessagesdays', 'message') ?>" /></td>
+        <td colspan="2"><?php print_string('deletemessagesdays', 'message') ?></td>
+    </tr>
+    
+
+    <tr><td colspan="3"><hr /></td></tr>
+
+    <tr valign="top">
+        <td><input type="checkbox" name="emailmessages" alt="<?php print_string('emailmessages', 'message') ?>" <?php echo $cbemailmessages ?>  /></td>
+        <td colspan="2"><?php print_string('emailmessages', 'message') ?></td>
+    </tr>
+    <tr valign="top">
+        <td>&nbsp;</td>
+        <td align="right"><?php print_string('email') ?>:</td>
+        <td><input type="text" name="emailaddress" size="30" value="<?php echo $txemailaddress ?>" alt="<?php print_string('email') ?>" /></td>
+    </tr>
+    <tr valign="top">
+        <td>&nbsp;</td>
+        <td align="right"><?php print_string('format') ?>:</td>
+        <td><?php echo $format_select ?>
+        </td>
+    </tr>
+    <tr valign="top">
+        <td>&nbsp;</td>
+        <td align="right"><?php print_string('timenosee', 'message') ?>:</td>
+        <td><input type="text" name="emailtimenosee" size="2" value="<?php echo $txemailtimenosee ?>" alt="<?php print_string('timenosee', 'message') ?>" /></td>
+
+
+    <tr><td colspan="3"><hr /></td></tr>
+
+    
+    <tr valign="top">
+        <td colspan="3" align="center"><input type="submit" value="<?php print_string('savemysettings', 'message') ?>" /></td>
+    </tr>
+
+
+</table>
+
+</form>
diff --git a/message/user.php b/message/user.php
new file mode 100644 (file)
index 0000000..528c728
--- /dev/null
@@ -0,0 +1,188 @@
+<?php // $Id$
+      
+    require('../config.php');
+
+    require_login();
+
+/// Script parameters
+    $userid = required_param('id', PARAM_INT);
+    $frame  = optional_param('frame', '', PARAM_ALPHA);
+
+    $message = optional_param('message', '', PARAM_CLEAN);
+    $format  = optional_param('format', FORMAT_MOODLE, PARAM_INT);
+
+/// Check the user we are talking to is valid
+    if (! $user = get_record("user", "id", $userid)) {
+        error("User ID was incorrect");
+    }
+
+/// By default, print frameset to contain all the various panes
+    if (!$frame) {
+    ?>
+    <html>
+     <head><title><?php echo get_string('discussion', 'message').': '.fullname($user) ?></title></head>
+     <frameset rows="110,*,0,200" border="0" marginwidth="2" marginheight="1">
+       <frame src="user.php?id=<?php p($user->id)?>&amp;frame=info"     name="info"     
+              scrolling="no"  marginwidth="0" marginheight="">
+       <frame src="user.php?id=<?php p($user->id)?>&amp;frame=messages" name="messages" 
+              scrolling="yes" marginwidth="10" marginheight="10">
+       <frame src="user.php?id=<?php p($user->id)?>&amp;frame=refresh"  name="refresh" 
+              scrolling="no"  marginwidth="0" marginheight="0">
+       <frame src="user.php?id=<?php p($user->id)?>&amp;frame=edit"     name="edit" 
+              scrolling="no"  marginwidth="2" marginheight="2">
+     </frameset>
+     <noframes>Sorry, but support for Frames is required to use Messaging</noframes>
+    </html>
+    <?php
+    }
+
+    switch ($frame) {     /// Put data into all the frames
+
+        case 'info':      /// Print the top frame with information and links
+            print_header();
+            echo '<table width="100%" cellpadding="0" cellspacing="0"><tr>';
+            echo '<td>'.print_user_picture($user->id, SITEID, $user->picture, true, true, false).'</td>';
+            echo '<td>';
+            echo fullname($user);
+            echo '<br /><font size="1">';
+            if ($user->lastaccess) {
+                $datestring = get_string('ago', 'message', format_time(time() - $user->lastaccess));
+            } else {
+                $datestring = get_string("never");
+            }
+            echo get_string("lastaccess").":", $datestring;
+            echo '</font>';
+            echo '</td>';
+            echo '</tr></table>';
+            echo '</table></table></body>'; // Close possible theme tables off
+        break;
+
+        case 'messages':  /// Print the main frame containing the current chat
+            $THEME->body = '#FFFFFF';
+            print_header();
+            echo '<script language="Javascript">';
+            echo 'document.write(\'<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/theme/standard/styles.php" />\');';
+            echo "</script>\n\n";
+        break;
+
+        case 'refresh':  /// Print the main frame containing the current chat
+            header("Expires: Sun, 28 Dec 1997 09:32:45 GMT");
+            header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
+            header("Cache-Control: no-cache, must-revalidate");
+            header("Pragma: no-cache");
+            header("Content-Type: text/html");
+            header("Refresh: 5; url=user.php?id=$user->id&frame=refresh");
+
+            echo '<body>';
+            if ($messages = get_records_select('message', "useridto = '$USER->id' AND useridfrom = '$user->id'", 
+                                               'timecreated')) {
+                foreach ($messages as $message) {
+                    $time = userdate($message->timecreated, get_string('strftimemessage', 'chat'));
+
+                    $options = NULL;
+                    $options->para = false;
+                    $options->newlines = true;
+                    $printmessage = format_text($message->message, $message->format, $options, 0);
+                    $printmessage = str_replace("\r", ' ', $printmessage);
+                    $printmessage = str_replace("\n", ' ', $printmessage);
+                    $printmessage = '<p><font size="-1"><b>'.$user->firstname.' ['.$time.']</b>: '.
+                               $printmessage.'</font></p>';
+                    echo '<script language="Javascript">';
+                    echo "parent.messages.document.write('".addslashes($printmessage)."\\n');\n";
+                    echo "</script>\n\n";
+                    
+                    /// Move the entry to the other table
+                    $message->timeread = time();
+                    $message->message = addslashes($message->message);
+                    $messageid = $message->id;
+                    unset($message->id);
+                    if (insert_record('message_read', $message)) {
+                        delete_records('message', 'id', $messageid);
+                    }
+                }
+                echo '<script language="Javascript">';
+                echo "parent.messages.scroll(1,5000000);\n";
+                echo "</script>\n\n";
+            }
+            $timeago = time() - $user->lastaccess;
+            if ($user->lastaccess and $timeago > 300) {
+                echo '<script language="Javascript">';
+                echo "parent.info.document.location.replace('$CFG->wwwroot/message/user.php?id=$user->id&frame=info');\n";
+                echo "</script>\n\n";
+            }
+            echo '</body>';
+        break;
+
+        case 'edit':      /// Print the bottom frame with the text editor
+
+            /// Check that the user is not blocking us!!
+            if ($contact = get_record('message_contacts', 'userid', $user->id, 'contact', $USER->id)) {
+                if ($contact->blocked) {
+                    print_heading(get_string('userisblockingyou', 'message'));
+                    exit;
+                }
+            }
+
+            $message = trim($message);
+
+            if ($message and confirm_sesskey()) {   /// Current user has just sent a message
+
+            /// Save it to the database...
+                $savemessage = NULL;
+                $savemessage->useridfrom    = $USER->id;
+                $savemessage->useridto      = $user->id;
+                $savemessage->message       = $message;
+                $savemessage->format        = $format;
+                $savemessage->timecreated   = time();
+                $savemessage->messagetype   = 'direct';
+
+                if (!insert_record('message', $savemessage)) {
+                    notify('Error: Message was not sent!!');
+                }
+
+            /// Format the message as HTML
+                $options = NULL;
+                $options->para = false;
+                $options->newlines = true;
+                $message = format_text($message, $format, $options, 0);
+                $message = str_replace("\r", ' ', $message);
+                $message = str_replace("\n", ' ', $message);
+
+            /// Then write it to our own screen immediately
+                $time = userdate(time(), get_string('strftimemessage', 'chat'));
+                $message = '<p><font size="-1"><b>'.$USER->firstname.' ['.$time.']</b>: '.$message.'</font></p>';
+
+                $script  = "<script>\n";
+                $script .= "parent.messages.document.write('$message\\n');\n";
+                $script .= "parent.messages.scroll(1,5000000);\n";
+                $script .= "</script>\n\n";
+
+                add_to_log(SITEID, 'message', 'write', 'history.php?user='.$user->id.'&amp;time='.time(), $user->id);
+            } else {
+                $script  = '';
+            }
+
+            print_header('','','','',$script,false,'','',false,'');
+
+            echo '<body><center>';
+            echo '<form name="editing" method="post" action="user.php">';
+            echo '<input type="hidden" name="id" value="'.$user->id.'" />';
+            echo '<input type="hidden" name="frame" value="edit" />';
+            echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
+
+            $usehtmleditor = can_use_html_editor();
+            $usehtmleditor = false; // REMOVE
+            print_textarea($usehtmleditor, 5, 50, 450, 200, 'message', '');
+            if ($usehtmleditor) {
+                use_html_editor("message");
+            }
+            echo '<br /><input type="submit" value="'.get_string('sendmessage', 'message').'" />';
+            echo '<input type="hidden" name="format" value="'.(int)$usehtmleditor.'" />';
+            echo '</form>';
+            echo '</center>';
+
+        break;
+
+    }
+
+?>