Index: plugins/blocks/mrbs/settings.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/mrbs/settings.php,v
retrieving revision 1.9
diff -u -r1.9 settings.php
--- plugins/blocks/mrbs/settings.php	4 Aug 2008 01:17:52 -0000	1.9
+++ plugins/blocks/mrbs/settings.php	5 Aug 2008 04:49:41 -0000
@@ -167,15 +167,15 @@
 $settings->add(new admin_setting_configtext('entry_type_j', get_string('config_entry_type', 'block_mrbs','J'), get_string('config_entry_type2', 'block_mrbs','J'), NULL, PARAM_TEXT));
 $settings->settings->entry_type_j->plugin='block/mrbs';
 
-$options = array('0' => get_string('no'), '1' => get_string('1'));
+$options = array('0' => get_string('no'), '1' => get_string('yes'));
 $settings->add(new admin_setting_configselect('mail_admin_on_bookings', get_string('config_mail_admin_on_bookings', 'block_mrbs'), get_string('config_mail_admin_on_bookings2', 'block_mrbs'), '0', $options));
 $settings->settings->mail_admin_on_bookings->plugin='block/mrbs';
 
-$options = array('0' => get_string('no'), '1' => get_string('1'));
+$options = array('0' => get_string('no'), '1' => get_string('yes'));
 $settings->add(new admin_setting_configselect('mail_area_admin_on_bookings', get_string('config_mail_area_admin_on_bookings', 'block_mrbs'), get_string('config_mail_area_admin_on_bookings2', 'block_mrbs'), 0, $options));
 $settings->settings->mail_area_admin_on_bookings->plugin='block/mrbs';
 
-$options = array('0' => get_string('no'), '1' => get_string('1'));
+$options = array('0' => get_string('no'), '1' => get_string('yes'));
 $settings->add(new admin_setting_configselect('mail_room_admin_on_bookings', get_string('config_mail_room_admin_on_bookings', 'block_mrbs'), get_string('config_mail_room_admin_on_bookings2', 'block_mrbs'), 0, $options));
 $settings->settings->mail_room_admin_on_bookings->plugin='block/mrbs';
 
Index: plugins/blocks/mrbs/lang/en_utf8/block_mrbs.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/mrbs/lang/en_utf8/block_mrbs.php,v
retrieving revision 1.9
diff -u -r1.9 block_mrbs.php
--- plugins/blocks/mrbs/lang/en_utf8/block_mrbs.php	3 Aug 2008 17:21:55 -0000	1.9
+++ plugins/blocks/mrbs/lang/en_utf8/block_mrbs.php	5 Aug 2008 04:49:41 -0000
@@ -8,7 +8,7 @@
 $string['adminview'] = 'What is URL to your MRBS Install?';
 $string['advanced_search']    = 'Advanced search';
 $string['all_day']            = 'All day';
-$string['area_admin_email']   = 'Area admin email:';
+$string['area_admin_email']   = 'Area admin email';
 $string['areas']              = 'Areas';
 $string['backadmin']          = 'Back to Admin';
 $string['bgcolor']            = 'bgcolor';
@@ -23,7 +23,7 @@
 $string['class']            = 'class';
 $string['click_to_reserve']   = 'Click on the cell to make a reservation.';
 $string['config_admin_email'] = 'MRBS admin email';
-$string['config_admin_email2'] = 'Email address of the MRBS administrator';
+$string['config_admin_email2'] = 'Email address of the MRBS administrator. In order to receive MRBS email notifications, the email address must be associated with a Moodle user account.';
 $string['config_admin'] = 'MRBS Admin';
 $string['config_admin2'] = 'Name of the MRBS administrator';
 $string['config_area_list_format'] = 'Show area list';
@@ -57,11 +57,11 @@
 $string['config_mail_area_admin_on_bookings'] = 'Mail area admin';
 $string['config_mail_area_admin_on_bookings2'] = 'Send email to area admin notifying of a new booking';
 $string['config_mail_cc'] = 'Mail cc'; 
-$string['config_mail_cc2'] = 'Set email address of the Carbon Copy field. Default is blank. Similar to mail recipients, you can define more than one recipient.' ; 
+$string['config_mail_cc2'] = 'Set email address of the Carbon Copy field. Default is blank. Similar to mail recipients, you can define more than one recipient. All recipient emails must be associated with a Moodle user account.' ; 
 $string['config_mail_from'] = 'Mail from'; 
-$string['config_mail_from2'] = 'Set the email address of the From field. Default is site admin.'; 
+$string['config_mail_from2'] = 'Set the email address of the From field. Default is site admin. From email must be associated with a Moodle user account.'; 
 $string['config_mail_recipients'] = 'Mail recipients'; 
-$string['config_mail_recipients2'] = 'Set the recipient email. You can define more than one recipient like this \'john@doe.com,scott@tiger.com\''; 
+$string['config_mail_recipients2'] = 'Set the recipient email. You can define more than one recipient like this \'john@doe.com,scott@tiger.com\'. Recipient email(s) must be associated with a Moodle user account.'; 
 $string['config_mail_room_admin_on_bookings'] = 'Mail room admin';
 $string['config_mail_room_admin_on_bookings2'] = 'Send email to room admin notifying of a new booking';
 $string['config_mail_admin_on_delete'] = 'Mail admin deletes';
@@ -98,11 +98,11 @@
 $string['config_view_week_number2'] = 'To view weeks in the bottom (trailer.php) as week numbers (42) instead of \'first day of the week\' (13 Oct), set this to TRUE';
 $string['config_weekstarts'] = 'Start of Week';
 $string['config_weekstarts2']  = 'Select the start of week.';$string['confirmdel']         = 'Are you sure\\nyou want to\\ndelete this entry?\\n\\n';
-$string['conflict']           = 'The new booking will conflict with the following entry(s):';
-$string['createdby']          = 'Created By:';
+$string['conflict']           = 'The new booking will conflict with the following entry(s)';
+$string['createdby']          = 'Created By';
 $string['ctrl_click_type']    = 'Use Control-Click to select more than one type';
 $string['ctrl_click']         = 'Use Control-Click to select more than one room';
-$string['database']           = 'Database: ';
+$string['database']           = 'Database';
 $string['dayafter']           = 'Go To Day After';
 $string['daybefore']          = 'Go To Day Before';
 $string['delarea']            = 'You must delete all rooms in this area before you can delete it<p>';
@@ -110,20 +110,21 @@
 $string['deleteentry']        = 'Delete Entry';
 $string['deletefollowing']    = 'This will delete the following bookings';
 $string['deleteseries']       = 'Delete Series';
-$string['duration']           = 'Duration:';
+$string['duration']           = 'Duration';
 $string['edit_user']          = 'Edit user';
 $string['editarea']           = 'Edit Area';
 $string['editentry']          = 'Edit Entry';
 $string['editroom']           = 'Edit Room';
 $string['editroomarea']       = 'Edit Area or Room Description';
 $string['editseries']         = 'Edit Series';
-$string['end_date']           = 'End Time:';
+$string['end_date']           = 'End Time';
 $string['entries_found']      = 'entries found';
 $string['entry_found']        = 'entry found';
 $string['entry']              = 'Entry';
 $string['entryid']            = 'Entry ID ';
 $string['error_area']         = 'Error: area ';
 $string['error_room']         = 'Error: room ';
+$string['error_send_email']   = 'Error: Problem sending email to: $a';
 $string['external']           = 'Non-class';
 $string['failed_connect_db']  = 'Fatal Error: Failed to connect to database';
 $string['failed_to_acquire']  = 'Failed to acquire exclusive database access';
@@ -137,24 +138,24 @@
 $string['hours']              = 'hours';
 $string['hybrid']            = 'hybrid';
 $string['in']                 = 'in';
-$string['include']            = 'Include:';
+$string['include']            = 'Include';
 $string['internal']           = 'Class';
 $string['invalid_entry_id']   = 'Invalid entry id.';
 $string['invalid_search']     = 'Empty or invalid search string.';
 $string['invalid_series_id']  = 'Invalid series id.';
-$string['mail_body_changed_entry'] = '$a changed_entry'; //$mail was prepended to this string
-$string['mail_body_del_entry'] = '$a deleted_entry'; //$mail was prepended to this string
-$string['mail_body_new_entry'] = '$a new_entry'; //$mail was prepended to this string
-$string['mail_changed_entry'] = 'An entry has been modified, here are the details: ';
-$string['mail_deleted_entry'] = 'An entry has been deleted, here are the details: ';
-$string['mail_new_entry'] = 'A new entry has been booked, here are the details: ';
-$string['mail_subject'] = 'Entry added/changed for $a MRBS';
-$string['mail_subject_delete'] = 'Entry deleted for $a MRBS';
-$string['match_area']         = 'Match area:';
-$string['match_descr']        = 'Match full description:';
-$string['match_entry']        = 'Match brief description:';
-$string['match_room']         = 'Match room:';
-$string['match_type']         = 'Match type:';
+$string['mail_body_changed_entry'] = 'An entry has been modified, here are the details'; //$mail was prepended to this string
+$string['mail_body_del_entry'] = 'An entry has been deleted, here are the details'; //$mail was prepended to this string
+$string['mail_body_new_entry'] = 'A new entry has been booked, here are the details'; //$mail was prepended to this string
+$string['mail_changed_entry'] = 'An entry has been modified, here are the details';
+$string['mail_deleted_entry'] = 'An entry has been deleted, here are the details';
+$string['mail_new_entry'] = 'A new entry has been booked, here are the details';
+$string['mail_subject_entry'] = 'Entry added/changed for $a';
+$string['mail_subject_delete'] = 'Entry deleted for $a ';
+$string['match_area']         = 'Match area';
+$string['match_descr']        = 'Match full description';
+$string['match_entry']        = 'Match brief description';
+$string['match_room']         = 'Match room';
+$string['match_type']         = 'Match type';
 $string['month']            = 'Month';
 $string['monthafter']         = 'Go To Month After';
 $string['monthbefore']        = 'Go To Month Before';
@@ -163,8 +164,9 @@
 $string['mrbs:viewmrbs'] = 'Access MRBS (Read only)';
 $string['mrbs']               = 'Meeting Room Booking System';
 $string['mustlogin'] = 'You must be logged in to Moodle before you can access the MRBS calendar block';
-$string['namebooker']         = 'Brief Description:';
+$string['namebooker']         = 'Reservation for';
 $string['no_rooms_for_area']  = 'No rooms defined for this area';
+$string['no_user_with_email'] = 'No user found with an email address of: $a';
 $string['no_users_create_first_admin'] = 'Create a user configured as administrator and then you can log in and create more users.';
 $string['no_users_initial']   = 'No users in database, allowing initial user creation';
 $string['noarea']             = 'No area selected';
@@ -175,7 +177,7 @@
 $string['not_php3']             = '<H1>WARNING: This probably does not work with PHP3</H1>';
 $string['of']                 = ' of ';
 $string['password_twice']     = 'If you wish to change the password, please type the new password twice';
-$string['period']             = 'Period:';
+$string['period']             = 'Period';
 $string['periods']            = 'periods';
 $string['please_contact']     = 'Please contact ';
 $string['postbrowserlang']    = 'language.';
@@ -183,13 +185,13 @@
 $string['records']            = 'Records ';
 $string['rep_dsp_dur']        = 'Duration';
 $string['rep_dsp_end']        = 'End Time';
-$string['rep_dsp']            = 'Display in report:';
-$string['rep_end_date']       = 'Repeat End Date:';
+$string['rep_dsp']            = 'Display in report';
+$string['rep_end_date']       = 'Repeat End Date';
 $string['rep_for_nweekly']    = '(for n-weekly)';
 $string['rep_for_weekly']     = '(for (n-)weekly)';
-$string['rep_freq']           = 'Frequency:';
+$string['rep_freq']           = 'Frequency';
 $string['rep_num_weeks']      = 'Number of weeks';
-$string['rep_rep_day']        = 'Repeat Day:';
+$string['rep_rep_day']        = 'Repeat Day';
 $string['rep_type_0']         = 'None';
 $string['rep_type_1']         = 'Daily';
 $string['rep_type_2']         = 'Weekly';
@@ -197,46 +199,46 @@
 $string['rep_type_4']         = 'Yearly';
 $string['rep_type_5']         = 'Monthly, corresponding day';
 $string['rep_type_6']         = 'n-Weekly';
-$string['rep_type']           = 'Repeat Type:';
+$string['rep_type']           = 'Repeat Type';
 $string['repeat_id']          = 'Repeat ID '; 
 $string['report_and_summary'] = 'Report and Summary';
-$string['report_end']         = 'Report end date:';
-$string['report_on']          = 'Report on Meetings:';
+$string['report_end']         = 'Report end date';
+$string['report_on']          = 'Report on Meetings';
 $string['report_only']        = 'Report only';
-$string['report_start']       = 'Report start date:';
+$string['report_start']       = 'Report start date';
 $string['resolution_units'] = ' Minutes';
 $string['returncal']          = 'Return to calendar view';
 $string['returnprev']         = 'Return to previous page';
 $string['rights']             = 'Rights';
-$string['room_admin_email']   = 'Room admin email:';
+$string['room_admin_email']   = 'Room admin email';
 $string['room']               = 'Room';
 $string['rooms']              = 'Rooms';
 $string['sched_conflict']     = 'Scheduling Conflict';
 $string['search_for']         = 'Search For';
-$string['search_results']     = 'Search Results for:';
+$string['search_results']     = 'Search Results for';
 $string['seconds']            = 'seconds';
 $string['serverpath'] = 'MRBS Installation path';
 $string['show_my_entries']    = 'Click to display all my upcoming entries';
 $string['slot']            = 'Slot';
 $string['sort_rep_time']      = 'Start Date/Time';
-$string['sort_rep']           = 'Sort Report by:';
-$string['start_date']         = 'Start Time:';
+$string['sort_rep']           = 'Sort Report by';
+$string['start_date']         = 'Start Time';
 $string['submitquery']        = 'Run Report';
 $string['sum_by_creator']     = 'Creator';
 $string['sum_by_descrip']     = 'Brief description';
-$string['summarize_by']       = 'Summarize by:';
+$string['summarize_by']       = 'Summarize by';
 $string['summary_header_per'] = 'Summary of (Entries) Periods';
 $string['summary_header']     = 'Summary of (Entries) Hours';
 $string['summary_only']       = 'Summary only';
 $string['sure']               = 'Are you sure?';
-$string['system']             = 'System: ';
+$string['system']             = 'System';
 $string['through']            = ' through ';
 $string['too_may_entrys']     = 'The selected options will create too many entries.<BR>Please use different options!';
 $string['type']               = 'Type';
 $string['typea']               = NULL;
 $string['unknown']            = 'Unknown';
-$string['update_area_failed'] = 'Update area failed: ';
-$string['update_room_failed'] = 'Update room failed: ';
+$string['update_area_failed'] = 'Update area failed';
+$string['update_room_failed'] = 'Update room failed';
 $string['useful_n-weekly_value'] = 'useful n-weekly value.';
 $string['valid_room']         = 'room.';
 $string['valid_time_of_day']  = 'valid time of day.';
Index: plugins/blocks/mrbs/web/functions.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/mrbs/web/functions.php,v
retrieving revision 1.7
diff -u -r1.7 functions.php
--- plugins/blocks/mrbs/web/functions.php	4 Aug 2008 01:17:51 -0000	1.7
+++ plugins/blocks/mrbs/web/functions.php	5 Aug 2008 04:49:41 -0000
@@ -603,4 +603,865 @@
 
 	return $modification;
 }
+
+/**
+ * Convert already utf-8 encoded strings to charset defined for mails in
+ * c.i.php.
+ *
+ * @param string    $string   string to convert
+ * @return string   $string   string converted to get_string('charset','block_mrbs') [i.e. the character set of the MRBS block language pack
+ */
+function removeMailUnicode($string)
+{
+    global $unicode_encoding;
+    //
+    if ($unicode_encoding)
+    {
+        return iconv("utf-8", get_string('charset','block_mrbs'), $string);
+    }
+    else
+    {
+        return $string;
+    }
+}
+
+// }}}
+// {{{ getMailPeriodDateString()
+
+/**
+ * Format a timestamp in non-unicode output (for emails).
+ *
+ * @param   timestamp   $t
+ * @param   int         $mod_time
+ * @return  array
+ */
+function getMailPeriodDateString($t, $mod_time=0)
+{
+    global $periods;
+    //
+    $time = getdate($t);
+    $p_num = $time['minutes'] + $mod_time;
+    ( $p_num < 0 ) ? $p_num = 0 : '';
+    ( $p_num >= count($periods) - 1 ) ? $p_num = count($periods ) - 1 : '';
+    // I have made the separater a ',' as a '-' leads to an ambiguious
+    // display in report.php when showing end times.
+    return array($p_num, $periods[$p_num] . userdate($t, ", %A %d %B %Y"));
+}
+
+// }}}
+// {{{ getMailTimeDateString()
+
+/**
+ * Format a timestamp in non-unicode output (for emails).
+ *
+ * @param   timestamp   $t         timestamp to format
+ * @param   boolean     $inc_time  include time in return string
+ * @return  string                 formated string
+ */
+function getMailTimeDateString($t, $inc_time=TRUE)
+{
+    global $twentyfourhour_format;
+    // This bit's necessary, because it seems %p in userdate format
+    // strings doesn't work
+    $ampm = date("a",$t);
+    if ($inc_time)
+    {
+        if ($twentyfourhour_format)
+        {
+            return userdate($t, "%H:%M:%S - %A %d %B %Y");
+        }
+        else
+        {
+            return userdate($t, "%I:%M:%S$ampm - %A %d %B %Y");
+        }
+    }
+    else
+    {
+        return userdate($t, "%A %d %B %Y");
+    }
+}
+
+// }}}
+// {{{ notifyAdminOnBooking()
+
+/**
+ * Send email to administrator to notify a new/changed entry.
+ *
+ * @param bool    $new_entry    to know if this is a new entry or not
+ * @param int     $new_id       used for create a link to the new entry
+ * @return bool                 TRUE or PEAR error object if fails
+ */
+function notifyAdminOnBooking($new_entry , $new_id)
+{   global $CFG;
+    global $url_base, $returl, $name, $description, $area_name;
+    global $room_name, $starttime, $duration, $dur_units, $end_date, $endtime;
+    global $rep_enddate, $typel, $type, $create_by, $rep_type, $enable_periods;
+    global $rep_opt, $rep_num_weeks;
+    global $tbl_room, $tbl_area, $tbl_entry, $tbl_users, $tbl_repeat;
+    global $mail_previous, $auth;
+    
+    //
+    // $recipients = '';
+    $id_table = ($rep_type > 0) ? "rep" : "e";
+    (MAIL_ADMIN_ON_BOOKINGS) ? $recipientlist[] = MAIL_RECIPIENTS : '';
+    if (MAIL_AREA_ADMIN_ON_BOOKINGS)
+    {
+        // Look for list of area admins emails addresses
+        if ($new_entry) {
+            $sql = "SELECT a.area_admin_email ";
+            $sql .= "FROM $tbl_room r, $tbl_area a, $tbl_entry e ";
+            // If this is a repeating entry...
+            if ($id_table == 'rep')
+            {
+                // ...use the repeat table
+                $sql .= ", $tbl_repeat rep ";
+            }
+            $sql .= "WHERE ${id_table}.id=$new_id AND r.id=${id_table}.room_id AND a.id=r.area_id";
+            $res = sql_query($sql);
+            (! $res) ? fatal_error(0, sql_error()) : '';
+            $row = sql_row($res, 0);
+            if (NULL != $row[0]) { //add only if email address is already not in the string
+                $recipientlist[] = $row[0];
+            }
+        } else {
+        // if this is an edited entry, we already have area_admin_email,
+        // avoiding a database hit.
+           if ('' != $mail_previous['area_admin_email'])  {
+               $recipientlist[] = $mail_previous['area_admin_email'];
+           }
+        }
+    }
+    if (MAIL_ROOM_ADMIN_ON_BOOKINGS)
+    {
+        // Look for list of room admins emails addresses
+        if ($new_entry)
+        {
+            $sql = "SELECT r.room_admin_email ";
+            $sql .= "FROM $tbl_room r, $tbl_entry e ";
+            // If this is a repeating entry...
+            if ($id_table == 'rep')
+            {
+                // ...use the repeat table
+                $sql .= ", $tbl_repeat rep ";
+            }
+            $sql .= "WHERE ${id_table}.id=$new_id AND r.id=${id_table}.room_id";
+            $res = sql_query($sql);
+            (! $res) ? fatal_error(0, sql_error()) : '';
+            $row = sql_row($res, 0);
+            if (NULL != $row[0]) {
+                $recipientlist[] = $row[0];
+            }
+        }
+        else { // if this is an edited entry, we already have room_admin_email, avoiding a database hit.
+           if ('' != $mail_previous['room_admin_email']) {
+               $recipientlist[] = $mail_previous['room_admin_email'];
+           }
+        }
+    }
+    if (MAIL_BOOKER) {
+        if ('moodle' == $auth['type']) { //this was previously for the db authentication type but I am hijacking it for the MRBS Moodle block to lookup the user's email
+            /* It would be possible to move this query within the query in
+               getPreviousEntryData to have all in one central place and to
+               reduce database hits by one. However this is a bad idea. If a
+               user is deleted from your user database, this will prevent all
+               mails to admins when this user previously booked entries will
+               be changed, as no user name will match the booker name */
+               
+            $sql = "SELECT email FROM ";
+            $sql .= $CFG->prefix.'user WHERE username=';
+            $sql .= "'";
+            $sql .= ($new_entry) ? $create_by : $mail_previous['createdby'];
+            $sql .= "'";
+            $res = sql_query($sql);
+            (! $res) ? fatal_error(0, sql_error()) : '';
+            $row = sql_row($res, 0);
+            if (NULL != $row[0]) {
+                $recipientlist[] = $row[0];
+            }
+        }
+        else { //Moodle should always look up the code so this should never execute especially since MAIL_USERNAME_SUFFIX and MAIL_DOMAIN are not defined
+            if ($new_entry) {
+                if ('' != $create_by) {
+                    $recipientlist[] = str_replace(MAIL_USERNAME_SUFFIX, '', $create_by) . MAIL_DOMAIN;
+                }
+            }
+            else {
+                if ('' != $mail_previous['createdby']) {
+                    $recipientlist[] = str_replace(MAIL_USERNAME_SUFFIX, '', $mail_previous['createdby']) . MAIL_DOMAIN;
+                }
+            }
+        }
+    }
+    // If there are no recipients then don't both preparing the email
+    if (sizeof($recipientlist)==0) {
+        return FALSE;
+    }
+    //
+    $subject = get_string('mail_subject_entry','block_mrbs');
+    if ($new_entry)
+    {
+        $body = get_string('mail_body_new_entry','block_mrbs') . ": \n\n";
+    }
+    else
+    {
+        $body = get_string('mail_body_changed_entry','block_mrbs') . ": \n\n";
+    }
+    // Set the link to view entry page
+    if (isset($url_base) && ($url_base != ""))
+    {
+        $body .= "$url_base/view_entry.php?id=$new_id";
+    }
+    else
+    {
+        ('' != $returl) ? $url = explode(basename($returl), $returl) : '';
+        $body .= $url[0] . "view_entry.php?id=$new_id";
+    }
+    if ($rep_type > 0)
+    {
+        $body .= "&series=1";
+    }
+    $body .= "\n";
+    // Displays/don't displays entry details
+    if (MAIL_DETAILS)
+    {
+        $body .= "\n" . get_string('namebooker','block_mrbs') . ": ";
+        $body .= compareEntries(removeMailUnicode($name),
+            removeMailUnicode($mail_previous['namebooker']), $new_entry). "\n";
+        
+        // Description:
+        $body .= get_string('description') . ": ";
+        $body .= compareEntries(removeMailUnicode($description),
+            removeMailUnicode($mail_previous['description']), $new_entry) . "\n";
+        
+        // Room:
+        $body .= get_string('room','block_mrbs') . ": " .
+            compareEntries(removeMailUnicode($area_name),
+            removeMailUnicode($mail_previous['area_name']), $new_entry);
+        $body .= " - " . compareEntries(removeMailUnicode($room_name),
+            removeMailUnicode($mail_previous['room_name']), $new_entry) . "\n";
+        
+        // Start time
+        if ( $enable_periods )
+        {
+            list( $start_period, $start_date) =
+                getMailPeriodDateString($starttime);
+            $body .= get_string('start_date','block_mrbs') . ": ";
+            $body .= compareEntries(unHtmlEntities($start_date),
+                unHtmlEntities($mail_previous['start_date']), $new_entry) . "\n";
+        }
+        else
+        {
+            $start_date = getMailTimeDateString($starttime);
+            $body .= get_string('start_date','block_mrbs') . ": " .
+                compareEntries($start_date, $mail_previous['start_date'], $new_entry) . "\n";
+        }
+        
+        // Duration
+        $body .= get_string('duration','block_mrbs') . ": " .
+            compareEntries($duration, $mail_previous['duration'], $new_entry);
+        $body .= " " . compareEntries($dur_units, $mail_previous['dur_units'], $new_entry) . "\n";
+        
+        // End time
+        if ( $enable_periods )
+        {
+            $myendtime = $endtime;
+            $mod_time = -1;
+            list($end_period, $end_date) =  getMailPeriodDateString($myendtime, $mod_time);
+            $body .= get_string('end_date','block_mrbs') . ": ";
+            $body .= compareEntries(unHtmlEntities($end_date),
+                unHtmlEntities($mail_previous['end_date']), $new_entry) ."\n";
+        }
+        else
+        {
+            $myendtime = $endtime;
+            $end_date = getMailTimeDateString($myendtime);
+            $body .= get_string('end_date','block_mrbs') . ": " .
+                compareEntries($end_date, $mail_previous['end_date'], $new_entry) . "\n";
+        }
+        
+        // Type of booking
+        $body .= get_string('type','block_mrbs') . ": ";
+        if ($new_entry)
+        {
+            $body .= $typel[$type];
+        }
+        else
+        {
+            $temp = $mail_previous['type'];
+            $body .= compareEntries($typel[$type], $typel[$temp], $new_entry);
+        }
+        
+        // Created by
+        $body .= "\n" . get_string('createdby','block_mrbs') . ": " .
+            compareEntries($create_by, $mail_previous['createdby'], $new_entry) . "\n";
+        
+        // Last updated
+        $body .= get_string('lastmodified') . ": " .
+            compareEntries(getMailTimeDateString(time()), $mail_previous['updated'], $new_entry);
+        
+        // Repeat Type
+        $body .= "\n" . get_string('rep_type','block_mrbs');
+        if ($new_entry)
+        {
+            $body .= ": " . get_string('rep_type_'.$rep_type,'block_mrbs');
+        }
+        else
+        {
+            $temp = $mail_previous['rep_type'];
+            $body .=  ": " . compareEntries(get_string('rep_type_'.$rep_type,'block_mrbs'),
+                get_string('rep_type_'.$temp,'block_mrbs'), $new_entry);
+        }
+        
+        // Details if a series
+        if ($rep_type > 0)
+        {
+        $opt = "";
+        if (($rep_type == 2) || ($rep_type == 6))
+        {
+        # Display day names according to language and preferred weekday start.
+        for ($i = 0; $i < 7; $i++)
+        {
+            $daynum = ($i + $weekstarts) % 7;
+            if ($rep_opt[$daynum]) $opt .= day_name($daynum) . " ";
+        }
+        }
+        if ($rep_type == 6)
+        {
+        $body .= "\n" . get_string('rep_num_weeks','block_mrbs');
+        $body .=  ": " . compareEntries($rep_num_weeks, $mail_previous["rep_num_weeks"], $new_entry);
+        }
+    
+        if($opt || $mail_previous["rep_opt"])
+        {
+        $body .= "\n" . get_string('rep_rep_day','block_mrbs');
+        $body .=  ": " . compareEntries($opt, $mail_previous["rep_opt"], $new_entry);
+        }
+
+            $body .= "\n" . get_string('rep_end_date','block_mrbs');
+            if ($new_entry)
+            {
+                $body .= ": " . userdate($rep_enddate, '%A %d %B %Y');
+            }
+            else
+            {
+                $temp = userdate($rep_enddate, '%A %d %B %Y');
+                $body .=  ": " . 
+                    compareEntries($temp, $mail_previous['rep_end_date'], $new_entry) . "\n";
+            }
+        }
+    $body .= "\n";
+    }
+    
+    array_unique($recipientlist);
+
+    $result=1;
+    if (!$fromuser=get_user_by_email(MAIL_FROM)) {
+        $result=0;
+    } 
+    foreach ($recipientlist as $recip) {
+        $recipuser = get_user_by_email($recip);
+        if (($recipuser) && ($result)) {
+            $result = email_to_user($recipuser, $fromuser, $subject, $body);
+        } else {
+            if ($recipuser<1) {
+                $result=0;
+                notice(get_string('no_user_with_email','block_mrbs',$recip));
+            } else {
+                notice(get_string('no_user_with_email','block_mrbs',MAIL_FROM));
+            }
+        }
+    }
+//    $result = sendMail($recipients, $subject, $body, $get_string('charset','block_mrbs') ,MAIL_CC);
+    return $result;
+}
+
+// }}}
+// {{{ notifyAdminOnDelete()
+
+/**
+ * Send email to administrator to notify a new/changed entry.
+ *
+ * @param   array   $mail_previous  contains deleted entry data forr email body
+ * @return  bool    TRUE or PEAR error object if fails
+ */
+function notifyAdminOnDelete($mail_previous)
+{
+    global $typel, $enable_periods, $auth, $tbl_users, $CFG;
+    //
+    $recipients = '';
+    (MAIL_ADMIN_ON_BOOKINGS) ? $recipients = MAIL_RECIPIENTS : '';
+    if (MAIL_AREA_ADMIN_ON_BOOKINGS)
+    {
+        if ('' != $mail_previous['area_admin_email'])
+        {
+            $recipientlist[] = $mail_previous['area_admin_email'];
+        }
+    }
+    if (MAIL_ROOM_ADMIN_ON_BOOKINGS)
+    {
+        if ('' != $mail_previous['room_admin_email'])
+        {
+            $recipientlist[] = $mail_previous['room_admin_email'];
+        }
+    }
+    if (MAIL_BOOKER)
+    {
+        if ('moodle' == $auth['type'])
+        {
+            /* It would be possible to move this query within the query in
+               getPreviousEntryData to have all in one central place and to
+               reduce database hits by one. However this is a bad idea. If a
+               user is deleted from your user database, this will prevent all
+               mails to admins when this user previously booked entries will
+               be changed, as no user name will match the booker name */
+            $sql = "SELECT email FROM ";
+            $sql .= $CFG->prefix.'user WHERE username=';
+            $sql .= "'";
+            $sql .= $mail_previous['createdby'];
+            $sql .= "'";
+            $res = sql_query($sql);
+            (! $res) ? fatal_error(0, sql_error()) : '';
+            $row = sql_row($res, 0);
+            if (NULL != $row[0]) {
+                $recipientlist[] = $row[0];
+            }
+        }
+        else { //this should never be the case with the MRBS Moodle block
+            if ( !empty($recipients) && ('' != $mail_previous['createdby']) ) {
+                if ('' != $mail_previous['createdby']) {
+                    $recipientlist[] = str_replace(MAIL_USERNAME_SUFFIX, '', $mail_previous['createdby']) . MAIL_DOMAIN;
+                }
+            }
+        }
+    }
+    // In case mail is allowed but someone forgot to supply email addresses...
+    if (sizeof($recipientlist)==0) {
+        return FALSE;
+    }
+    //
+    $subject = get_string('mail_subject_delete','block_mrbs');
+    $body = get_string('mail_body_del_entry','block_mrbs') . ": \n\n";
+    // Displays deleted entry details
+    $body .= "\n" . get_string('namebooker','block_mrbs') . ': ';
+    $body .= removeMailUnicode($mail_previous['namebooker']) . "\n";
+    $body .= get_string('description') . ": ";
+    $body .= removeMailUnicode($mail_previous['description']) . "\n";
+    $body .= get_string('room','block_mrbs') . ": ";
+    $body .= removeMailUnicode($mail_previous['area_name']);
+    $body .= " - " . removeMailUnicode($mail_previous['room_name']) . "\n";
+    $body .= get_string('start_date','block_mrbs') . ': ';
+    if ( $enable_periods )
+    {
+        $body .= unHtmlEntities($mail_previous['start_date']) . "\n";
+    }
+    else
+    {
+        $body .= $mail_previous['start_date'] . "\n";
+    }
+    $body .= get_string('duration','block_mrbs') . ': ' . $mail_previous['duration'] . ' ';
+    $body .= $mail_previous['dur_units'] . "\n";
+    if ( $enable_periods )
+    {
+        $body .= get_string('end_date','block_mrbs') . ": ";
+        $body .= unHtmlEntities($mail_previous['end_date']) ."\n";
+    }
+    else
+    {
+        $body .= get_string('end_date','block_mrbs') . ": " . $mail_previous['end_date'];
+        $body .= "\n";
+    }
+    $body .= get_string('type','block_mrbs') . ": ";
+    $body .=  (empty($typel[$mail_previous['type']])) ? "?" .
+        $mail_previous['type'] . "?" : $typel[$mail_previous['type']];
+    $body .= "\n" . get_string('createdby','block_mrbs') . ": ";
+    $body .= $mail_previous['createdby'] . "\n";
+    $body .= get_string('lastmodified') . ": " . $mail_previous['updated'];
+    $body .= "\n" . get_string('rep_type','block_mrbs');
+    $temp = $mail_previous['rep_type'];
+    $body .=  ": " . get_string('rep_type_'.$temp,'block_mrbs');
+    if ($mail_previous['rep_type'] > 0)
+    {
+        if ($mail_previous['rep_type'] == 6)
+        {
+           $body .= "\n" . get_string('rep_num_weeks','block_mrbs');
+           $body .=  ": " . $mail_previous["rep_num_weeks"];
+        }
+   
+        if($mail_previous["rep_opt"])
+        {
+           $body .= "\n" . get_string('rep_rep_day','block_mrbs');
+           $body .=  " " . $mail_previous["rep_opt"];
+        }
+
+        $body .= "\n" . get_string('rep_end_date','block_mrbs');
+        $body .=  " " . $mail_previous['rep_end_date'] . "\n";
+    }
+    $body .= "\n";
+    // End of mail details
+    
+    array_unique($recipientlist);
+
+    $result=1;
+    if (!$fromuser=get_user_by_email(MAIL_FROM)) {
+        $result=0;
+    } 
+    foreach ($recipientlist as $recip) {
+        $recipuser = get_user_by_email($recip);
+        if (($recipuser) && ($result)) {
+            $result = email_to_user($recipuser, $fromuser, $subject, $body);
+            if (!$result) {
+                notice(get_string('error_send_email','block_mrbs',$recip));
+            }
+        } else {
+            if ($recipuser<1) {
+                $result=0;
+                notice(get_string('no_user_with_email','block_mrbs',$recip));
+            } else {
+                notice(get_string('no_user_with_email','block_mrbs',MAIL_FROM));
+            }
+        }
+    }
+//    $result = sendMail($recipients, $subject, $body, $get_string('charset','block_mrbs') ,MAIL_CC);
+    return $result;
+    
+}
+
+// }}}
+// {{{ getPreviousEntryData()
+
+/**
+ * Gather all fields values for an entry. Used for emails to get previous
+ * entry state.
+ *
+ * @param int     $id       entry id to get data
+ * @param int     $series   1 if this is a serie or 0
+ * @return bool             TRUE or PEAR error object if fails
+ */
+function getPreviousEntryData($id, $series)
+{
+    global $tbl_area, $tbl_entry, $tbl_repeat, $tbl_room, $enable_periods;
+    //
+    $sql = "
+    SELECT  e.name,
+            e.description,
+            e.create_by,
+            r.room_name,
+            a.area_name,
+            e.type,
+            e.room_id,
+            e.repeat_id, 
+            e.timestamp,
+            (e.end_time - e.start_time) AS tbl_e_duration,
+            e.start_time AS tbl_e_start_time,
+            e.end_time AS tbl_e_end_time,
+            a.area_admin_email,
+            r.room_admin_email";
+    // Here we could just use $tbl_repeat.start_time, and not use alias,
+    // as the last column will take precedence using mysql_fetch_array,
+    // but for portability purpose I will not use it.
+    if (1 == $series)
+    {
+        $sql .= ", re.rep_type, re.rep_opt, re.rep_num_weeks,
+            (re.end_time - re.start_time) AS tbl_r_duration,
+            re.start_time AS tbl_r_start_time,
+            re.end_time AS tbl_r_end_time,
+            re.end_date AS tbl_r_end_date";
+    }
+    $sql .= "
+    FROM $tbl_entry e, $tbl_room r, $tbl_area a ";
+    (1 == $series) ? $sql .= ', ' . $tbl_repeat . ' re ' : '';
+    $sql .= "
+    WHERE e.room_id = r.id
+    AND r.area_id = a.id
+    AND e.id=$id";
+    (1 == $series) ? $sql .= " AND e.repeat_id = re.id" : '';
+    //
+    $res = sql_query($sql);
+    (! $res) ? fatal_error(0, sql_error()) : '';
+    (sql_count($res) < 1) ? fatal_error(0, get_string('invalid_entry_id','block_mrbs')) : '';
+    $row = sql_row_keyed($res, 0);
+    sql_free($res);
+    // Store all needed values in $mail_previous array to pass to
+    // notifyAdminOnDelete function (shorter than individual variables -:) )
+    $mail_previous['namebooker']    = $row['name'];
+    $mail_previous['description']   = $row['description'];
+    $mail_previous['createdby']     = $row['create_by'];
+    $mail_previous['room_name']     = $row['room_name'];
+    $mail_previous['area_name']     = $row['area_name'];
+    $mail_previous['type']          = $row['type'];
+    $mail_previous['room_id']       = $row['room_id'];
+    $mail_previous['repeat_id']     = $row['repeat_id'];
+    $mail_previous['updated']       = getMailTimeDateString($row[8]);
+    $mail_previous['area_admin_email'] = $row['area_admin_email'];
+    $mail_previous['room_admin_email'] = $row['room_admin_email'];
+    // If we use periods
+    if ( $enable_periods )
+    {
+        // If we delete a serie, start_time and end_time must
+        // come from $tbl_repeat, not $tbl_entry.
+        //
+        // This is not a serie
+        if (1 != $series)
+        {
+            list( $mail_previous['start_period'], $mail_previous['start_date'])
+                =  getMailPeriodDateString($row['tbl_e_start_time']);
+            list( $mail_previous['end_period'] , $mail_previous['end_date']) =
+                getMailPeriodDateString($row['tbl_e_end_time'], -1);
+            // need to make DST correct in opposite direction to entry creation
+            // so that user see what he expects to see
+            $mail_previous['duration'] = $row['tbl_e_duration'] -
+                cross_dst($row['tbl_e_start_time'], $row['tbl_e_end_time']);
+        }
+        // This is a serie
+        else
+        {
+            list( $mail_previous['start_period'], $mail_previous['start_date'])
+                =  getMailPeriodDateString($row['tbl_r_start_time']);
+            list( $mail_previous['end_period'] , $mail_previous['end_date']) =
+                getMailPeriodDateString($row['tbl_r_end_time'], 0);
+            // use getMailTimeDateString as all I want is the date
+        $mail_previous['rep_end_date'] =
+                getMailTimeDateString($row['tbl_r_end_date'], FALSE);
+            // need to make DST correct in opposite direction to entry creation
+            // so that user see what he expects to see
+            $mail_previous['duration'] = $row['tbl_r_duration'] -
+                cross_dst($row['tbl_r_start_time'], $row['tbl_r_end_time']);
+        
+        $mail_previous['rep_opt'] = "";
+        switch($row['rep_type'])
+        {
+        case 2:
+        case 6:
+            $rep_day[0] = $row['rep_opt'][0] != "0";
+            $rep_day[1] = $row['rep_opt'][1] != "0";
+            $rep_day[2] = $row['rep_opt'][2] != "0";
+            $rep_day[3] = $row['rep_opt'][3] != "0";
+            $rep_day[4] = $row['rep_opt'][4] != "0";
+            $rep_day[5] = $row['rep_opt'][5] != "0";
+            $rep_day[6] = $row['rep_opt'][6] != "0";
+
+            if ($row['rep_type'] == 6)
+            {
+                $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
+            }
+            else
+            {
+                $mail_previous['rep_num_weeks'] = "";
+            }
+            
+            break;
+        
+        default:
+            $rep_day = array(0, 0, 0, 0, 0, 0, 0);
+        }
+        for ($i = 0; $i < 7; $i++)
+        {
+        $wday = ($i + $weekstarts) % 7;
+        if ($rep_day[$wday])
+            $mail_previous['rep_opt'] .= day_name($wday) . " ";
+        }
+        
+        $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
+        }
+        toPeriodString($mail_previous['start_period'],
+            $mail_previous['duration'], $mail_previous['dur_units']);
+    }
+    // If we don't use periods
+    else
+    {
+        // This is not a serie
+        if (1 != $series)
+        {
+            $mail_previous['start_date'] =
+                getMailTimeDateString($row['tbl_e_start_time']);
+            $mail_previous['end_date'] =
+                getMailTimeDateString($row['tbl_e_end_time']);
+            // need to make DST correct in opposite direction to entry creation
+            // so that user see what he expects to see
+            $mail_previous['duration'] = $row['tbl_e_duration'] -
+                cross_dst($row['tbl_e_start_time'], $row['tbl_e_end_time']);
+        }
+        // This is a serie
+        else
+        {
+            $mail_previous['start_date'] =
+                getMailTimeDateString($row['tbl_r_start_time']);
+            $mail_previous['end_date'] =
+                getMailTimeDateString($row['tbl_r_end_time']);
+            // use getMailTimeDateString as all I want is the date
+        $mail_previous['rep_end_date'] =
+                getMailTimeDateString($row['tbl_r_end_date'], FALSE);
+            // need to make DST correct in opposite direction to entry creation
+            // so that user see what he expects to see
+            $mail_previous['duration'] = $row['tbl_r_duration'] -
+                cross_dst($row['tbl_r_start_time'], $row['tbl_r_end_time']);
+            
+        $mail_previous['rep_opt'] = "";
+        switch($row['rep_type'])
+        {
+        case 2:
+        case 6:
+            $rep_day[0] = $row['rep_opt'][0] != "0";
+            $rep_day[1] = $row['rep_opt'][1] != "0";
+            $rep_day[2] = $row['rep_opt'][2] != "0";
+            $rep_day[3] = $row['rep_opt'][3] != "0";
+            $rep_day[4] = $row['rep_opt'][4] != "0";
+            $rep_day[5] = $row['rep_opt'][5] != "0";
+            $rep_day[6] = $row['rep_opt'][6] != "0";
+
+            if ($row['rep_type'] == 6)
+            {
+                $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
+            }
+            else
+            {
+                $mail_previous['rep_num_weeks'] = "";
+            }
+            
+            break;
+        
+        default:
+            $rep_day = array(0, 0, 0, 0, 0, 0, 0);
+        }
+        for ($i = 0; $i < 7; $i++)
+        {
+        $wday = ($i + $weekstarts) % 7;
+        if ($rep_day[$wday])
+            $mail_previous['rep_opt'] .= day_name($wday) . " ";
+        }
+        
+        $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
+        }
+        toTimeString($mail_previous['duration'], $mail_previous['dur_units']);
+    }
+    (1 == $series) ? $mail_previous['rep_type'] = $row['rep_type']
+        : $mail_previous['rep_type'] = 0;
+    // return entry previous data as an array
+    return $mail_previous;
+}
+
+// }}}
+// {{{ compareEntries()
+
+/**
+ * Compare entries fields to show in emails.
+ *
+ * @param string  $new_value       new field value
+ * @param string  $previous_value  previous field value
+ * @return string                  new value if no difference, new value and
+ *                                 previous value in brackets otherwise
+ */
+function compareEntries($new_value, $previous_value, $new_entry)
+{
+    $suffix = "";
+    if ($new_entry)
+    {
+        return $new_value;
+    }
+    if ($new_value != $previous_value)
+    {
+        $suffix = " ($previous_value)";
+    }
+    return($new_value . $suffix);
+}
+
+// }}}
+// {{{ sendMail()
+
+/**
+ * Send emails using PEAR::Mail class.
+ * How to use this class -> http://www.pear.php.net/package/Mail then link
+ * "View documentation".
+ * Currently implemented version: Mail 1.1.3 and its dependancies
+ * Net_SMTP 1.2.6 and Net_Socket 1.0.2
+ *
+ * @param string  $recipients       comma separated list of recipients or array
+ * @param string  $subject          email subject
+ * @param string  $body             text message
+ * @param string  $charset          character set used in body
+ * @param string  $cc               Carbon Copy
+ * @param string  $bcc              Blind Carbon Copy
+ * @param string  $from             from field
+ * @param string  $backend          'mail', 'smtp' or 'sendmail'
+ * @param string  $sendmail_path    ie. "/usr/bin/sendmail"
+ * @param string  $sendmail_args    ie. "-t -i"
+ * @param string  $host             smtp server hostname
+ * @param string  $port             smtp server port
+ * @param string  $auth             smtp server authentication, TRUE/FALSE
+ * @param string  $username         smtp server username
+ * @param string  $password         smtp server password
+ * @return bool                     TRUE or PEAR error object if fails
+ */
+function sendMail($recipients, $subject, $body, $charset = 'us-ascii',
+    $cc = NULL, $bcc = NULL, $from = MAIL_FROM, $backend = MAIL_ADMIN_BACKEND,
+    $sendmail_path = SENDMAIL_PATH, $sendmail_args = SENDMAIL_ARGS,
+    $host = SMTP_HOST, $port = SMTP_PORT, $auth = SMTP_AUTH,
+    $username = SMTP_USERNAME, $password = SMTP_PASSWORD)
+{
+    require_once "Mail.php";
+
+    // Headers part
+    $headers['From']         = $from;
+    if( $backend != 'mail' ) {
+        $headers['To']           = $recipients;
+    }
+    (NULL != $cc) ? $headers['Cc'] = $cc : '';
+    (NULL != $bcc) ? $headers['Bcc'] = $bcc : '';
+    $headers['Subject']      = $subject;
+    $headers['MIME-Version'] = '1.0';
+    $headers['Content-Type'] = 'text/plain; charset=' . $charset;
+
+    // Parameters part
+    if( $backend == 'sendmail' ) {
+        $params['sendmail_path'] = $sendmail_path;
+        $params['sendmail_args'] = $sendmail_args;
+    }
+    if( $backend == "smtp" ) {
+        $params['host']          = $host;
+        $params['port']          = $port;
+        $params['auth']          = $auth;
+        $params['username']      = $username;
+        $params['password']      = $password;
+    }
+
+    // Call to the PEAR::Mail class
+    $mail_object =& Mail::factory($backend, $params);
+    $result = $mail_object->send($recipients, $headers, $body);
+
+    if (is_object($result))
+    {
+      error_log("Error sending email: ".$result->getMessage());
+    }
+    return $result;
+}
+
+// }}}
+// {{{ unHtmlEntities()
+
+/**
+ * Convert all HTML entities to their applicable characters.
+ * Added to remove HTML entities that are not suitable for plain text emails.
+ * May be replaced by PHP function 'html_entity_decode()' but this function
+ * only exist since PHP 4.3.0 and is buggy before PHP5.
+ *
+ * @param  string   $string     string to decode
+ * @return string               decoded string
+ */
+function unHtmlEntities($string)
+{
+    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
+    $trans_tbl = array_flip($trans_tbl);
+    return strtr($string, $trans_tbl);
+}
+
+function get_user_by_email ($email) 
+{
+    if ($recipient_user=get_complete_user_data('email',$email)) {
+        return $recipient_user;
+    } else {
+        return false;
+    }
+}
+// }}}
+
 ?>
Index: plugins/blocks/mrbs/web/functions_mail.php
===================================================================
RCS file: plugins/blocks/mrbs/web/functions_mail.php
diff -N plugins/blocks/mrbs/web/functions_mail.php
--- plugins/blocks/mrbs/web/functions_mail.php	4 Aug 2008 01:17:51 -0000	1.6
+++ /dev/null	1 Jan 1970 00:00:00 -0000
@@ -1,893 +0,0 @@
-<?php
-// +---------------------------------------------------------------------------+
-// | Meeting Room Booking System.                                              |
-// +---------------------------------------------------------------------------+
-// | Functions dedicated to emails handling.                                   |
-// |---------------------------------------------------------------------------+
-// | I keeped these functions in a separated file to avoid burden the main     |
-// | function.php files if emails are not used.                                |
-// |                                                                           |
-// | USE : This file should be included in all files where emails functions    |
-// |        are likely to be used.                                             |
-// +---------------------------------------------------------------------------+
-// | @author    thierry_bo.                                                    |
-// | @version   $Revision: 1.6 $.                                              |
-// +---------------------------------------------------------------------------+
-//
-// $Id: functions_mail.php,v 1.6 2008/08/04 01:17:51 arborrow Exp $
-
-require_once("../../../config.php"); //for Moodle integration
-// {{{ removeMailUnicode()
-
-/**
- * Convert already utf-8 encoded strings to charset defined for mails in
- * c.i.php.
- *
- * @param string    $string   string to convert
- * @return string   $string   string converted to $mail_vocab["charset"]
- */
-function removeMailUnicode($string)
-{
-    global $unicode_encoding, $mail_vocab;
-    //
-    if ($unicode_encoding)
-    {
-        return iconv("utf-8", $mail_vocab["charset"], $string);
-    }
-    else
-    {
-        return $string;
-    }
-}
-
-// }}}
-// {{{ getMailPeriodDateString()
-
-/**
- * Format a timestamp in non-unicode output (for emails).
- *
- * @param   timestamp   $t
- * @param   int         $mod_time
- * @return  array
- */
-function getMailPeriodDateString($t, $mod_time=0)
-{
-    global $periods;
-    //
-    $time = getdate($t);
-    $p_num = $time['minutes'] + $mod_time;
-    ( $p_num < 0 ) ? $p_num = 0 : '';
-    ( $p_num >= count($periods) - 1 ) ? $p_num = count($periods ) - 1 : '';
-    // I have made the separater a ',' as a '-' leads to an ambiguious
-    // display in report.php when showing end times.
-    return array($p_num, $periods[$p_num] . userdate($t, ", %A %d %B %Y"));
-}
-
-// }}}
-// {{{ getMailTimeDateString()
-
-/**
- * Format a timestamp in non-unicode output (for emails).
- *
- * @param   timestamp   $t         timestamp to format
- * @param   boolean     $inc_time  include time in return string
- * @return  string                 formated string
- */
-function getMailTimeDateString($t, $inc_time=TRUE)
-{
-    global $twentyfourhour_format;
-    // This bit's necessary, because it seems %p in userdate format
-    // strings doesn't work
-    $ampm = date("a",$t);
-    if ($inc_time)
-    {
-        if ($twentyfourhour_format)
-        {
-            return userdate($t, "%H:%M:%S - %A %d %B %Y");
-        }
-        else
-        {
-            return userdate($t, "%I:%M:%S$ampm - %A %d %B %Y");
-        }
-    }
-    else
-    {
-        return userdate($t, "%A %d %B %Y");
-    }
-}
-
-// }}}
-// {{{ notifyAdminOnBooking()
-
-/**
- * Send email to administrator to notify a new/changed entry.
- *
- * @param bool    $new_entry    to know if this is a new entry or not
- * @param int     $new_id       used for create a link to the new entry
- * @return bool                 TRUE or PEAR error object if fails
- */
-function notifyAdminOnBooking($new_entry , $new_id)
-{
-    global $url_base, $returl, $mail_vocab, $name, $description, $area_name;
-    global $room_name, $starttime, $duration, $dur_units, $end_date, $endtime;
-    global $rep_enddate, $typel, $type, $create_by, $rep_type, $enable_periods;
-    global $rep_opt, $rep_num_weeks;
-    global $tbl_room, $tbl_area, $tbl_entry, $tbl_users, $tbl_repeat;
-    global $mail_previous, $auth;
-    
-    //
-    $recipients = '';
-    $id_table = ($rep_type > 0) ? "rep" : "e";
-    (MAIL_ADMIN_ON_BOOKINGS) ? $recipients = MAIL_RECIPIENTS : '';
-    if (MAIL_AREA_ADMIN_ON_BOOKINGS)
-    {
-        // Look for list of area admins emails addresses
-        if ($new_entry)
-        {
-            $sql = "SELECT a.area_admin_email ";
-            $sql .= "FROM $tbl_room r, $tbl_area a, $tbl_entry e ";
-            // If this is a repeating entry...
-            if ($id_table == 'rep')
-            {
-                // ...use the repeat table
-                $sql .= ", $tbl_repeat rep ";
-            }
-            $sql .= "WHERE ${id_table}.id=$new_id AND r.id=${id_table}.room_id AND a.id=r.area_id";
-            $res = sql_query($sql);
-            (! $res) ? fatal_error(0, sql_error()) : '';
-            $row = sql_row($res, 0);
-            if ( !empty($recipients) && (NULL != $row[0]) )
-            {
-                $recipients .= ',';
-            }
-            if (NULL != $row[0])
-            {
-                $recipients .= $row[0];
-            }
-        }
-        else
-        // if this is an edited entry, we already have area_admin_email,
-        // avoiding a database hit.
-        {
-           if ( !empty($recipients) && ('' != $mail_previous['area_admin_email']) )
-           {
-               $recipients .= ',';
-           }
-           if ('' != $mail_previous['area_admin_email'])
-           {
-               $recipients .= $mail_previous['area_admin_email'];
-           }
-        }
-    }
-    if (MAIL_ROOM_ADMIN_ON_BOOKINGS)
-    {
-        // Look for list of room admins emails addresses
-        if ($new_entry)
-        {
-            $sql = "SELECT r.room_admin_email ";
-            $sql .= "FROM $tbl_room r, $tbl_entry e ";
-            // If this is a repeating entry...
-            if ($id_table == 'rep')
-            {
-                // ...use the repeat table
-                $sql .= ", $tbl_repeat rep ";
-            }
-            $sql .= "WHERE ${id_table}.id=$new_id AND r.id=${id_table}.room_id";
-            $res = sql_query($sql);
-            (! $res) ? fatal_error(0, sql_error()) : '';
-            $row = sql_row($res, 0);
-            if ( !empty($recipients) && (NULL != $row[0]) )
-            {
-                $recipients .= ',';
-            }
-            if (NULL != $row[0])
-            {
-                $recipients .= $row[0];
-            }
-        }
-        else
-        // if this is an edited entry, we already have room_admin_email,
-        // avoiding a database hit.
-        {
-           if ( !empty($recipients) && ('' != $mail_previous['room_admin_email']) )
-           {
-               $recipients .= ',';
-           }
-           if ('' != $mail_previous['room_admin_email'])
-           {
-               $recipients .= $mail_previous['room_admin_email'];
-           }
-        }
-    }
-    if (MAIL_BOOKER)
-    {
-        if ('db' == $auth['type'])
-        {
-            /* It would be possible to move this query within the query in
-               getPreviousEntryData to have all in one central place and to
-               reduce database hits by one. However this is a bad idea. If a
-               user is deleted from your user database, this will prevent all
-               mails to admins when this user previously booked entries will
-               be changed, as no user name will match the booker name */
-            $sql = "SELECT email FROM $tbl_users WHERE name='";
-            $sql .= ($new_entry) ? $create_by : $mail_previous['createdby'];
-            $sql .= "'";
-            $res = sql_query($sql);
-            (! $res) ? fatal_error(0, sql_error()) : '';
-            $row = sql_row($res, 0);
-            if ( !empty($recipients) && (NULL != $row[0]) )
-            {
-                $recipients .= ',';
-            }
-            if (NULL != $row[0])
-            {
-                $recipients .= $row[0];
-            }
-        }
-        else
-        {
-            if ($new_entry)
-            {
-                if ( !empty($recipients) && ('' != $create_by) )
-                {
-                    $recipients .= ',';
-                }
-                if ('' != $create_by)
-                {
-                    $recipients .= str_replace(MAIL_USERNAME_SUFFIX, '',
-                        $create_by) . MAIL_DOMAIN;
-                }
-            }
-            else
-            {
-                if ( !empty($recipients) && ('' != $mail_previous['createdby']) )
-                {
-                    $recipients .= ',';
-                }
-                if ('' != $mail_previous['createdby'])
-                {
-                    $recipients .= str_replace(MAIL_USERNAME_SUFFIX, '',
-                        $mail_previous['createdby']) . MAIL_DOMAIN;
-                }
-            }
-        }
-    }
-    // In case $recipients is empty, no need to go further
-    if ('' == $recipients)
-    {
-        return FALSE;
-    }
-    //
-    $subject = $mail_vocab["mail_subject_entry"];
-    if ($new_entry)
-    {
-        $body = $mail_vocab["mail_body_new_entry"] . "\n\n";
-    }
-    else
-    {
-        $body = $mail_vocab["mail_body_changed_entry"] . "\n\n";
-    }
-    // Set the link to view entry page
-    if (isset($url_base) && ($url_base != ""))
-    {
-        $body .= "$url_base/view_entry.php?id=$new_id";
-    }
-    else
-    {
-        ('' != $returl) ? $url = explode(basename($returl), $returl) : '';
-        $body .= $url[0] . "view_entry.php?id=$new_id";
-    }
-    if ($rep_type > 0)
-    {
-        $body .= "&series=1";
-    }
-    $body .= "\n";
-    // Displays/don't displays entry details
-    if (MAIL_DETAILS)
-    {
-        $body .= "\n" . $mail_vocab["namebooker"] . " ";
-        $body .= compareEntries(removeMailUnicode($name),
-            removeMailUnicode($mail_previous['namebooker']), $new_entry)  . "\n";
-        
-        // Description:
-        $body .= $mail_vocab["description"] . " ";
-        $body .= compareEntries(removeMailUnicode($description),
-            removeMailUnicode($mail_previous['description']), $new_entry) . "\n";
-        
-        // Room:
-        $body .= $mail_vocab["room"] . ": " .
-            compareEntries(removeMailUnicode($area_name),
-            removeMailUnicode($mail_previous['area_name']), $new_entry);
-        $body .= " - " . compareEntries(removeMailUnicode($room_name),
-            removeMailUnicode($mail_previous['room_name']), $new_entry) . "\n";
-        
-        // Start time
-        if ( $enable_periods )
-        {
-            list( $start_period, $start_date) =
-                getMailPeriodDateString($starttime);
-            $body .= $mail_vocab["start_date"] . " ";
-            $body .= compareEntries(unHtmlEntities($start_date),
-                unHtmlEntities($mail_previous['start_date']), $new_entry) . "\n";
-        }
-        else
-        {
-            $start_date = getMailTimeDateString($starttime);
-            $body .= $mail_vocab["start_date"] . " " .
-                compareEntries($start_date, $mail_previous['start_date'], $new_entry) . "\n";
-        }
-        
-        // Duration
-        $body .= $mail_vocab["duration"] . " " .
-            compareEntries($duration, $mail_previous['duration'], $new_entry);
-        $body .= " " . compareEntries($mail_vocab["$dur_units"],
-            $mail_previous['dur_units'], $new_entry) . "\n";
-        
-        // End time
-        if ( $enable_periods )
-        {
-            $myendtime = $endtime;
-            $mod_time = -1;
-            list($end_period, $end_date) =  getMailPeriodDateString($myendtime, $mod_time);
-            $body .= $mail_vocab["end_date"] . " ";
-            $body .= compareEntries(unHtmlEntities($end_date),
-                unHtmlEntities($mail_previous['end_date']), $new_entry) ."\n";
-        }
-        else
-        {
-            $myendtime = $endtime;
-            $end_date = getMailTimeDateString($myendtime);
-            $body .= $mail_vocab["end_date"] . " " .
-                compareEntries($end_date, $mail_previous['end_date'], $new_entry) . "\n";
-        }
-        
-        // Type of booking
-        $body .= $mail_vocab["type"] . " ";
-        if ($new_entry)
-        {
-            $body .= $typel[$type];
-        }
-        else
-        {
-            $temp = $mail_previous['type'];
-            $body .= compareEntries($typel[$type], $typel[$temp], $new_entry);
-        }
-        
-        // Created by
-        $body .= "\n" . $mail_vocab["createdby"] . " " .
-            compareEntries($create_by, $mail_previous['createdby'], $new_entry) . "\n";
-        
-        // Last updated
-        $body .= $mail_vocab["lastupdate"] . " " .
-            compareEntries(getMailTimeDateString(time()), $mail_previous['updated'], $new_entry);
-        
-        // Repeat Type
-        $body .= "\n" . $mail_vocab["rep_type"];
-        if ($new_entry)
-        {
-            $body .= " " . $mail_vocab["rep_type_$rep_type"];
-        }
-        else
-        {
-            $temp = $mail_previous['rep_type'];
-            $body .=  " " . compareEntries($mail_vocab["rep_type_$rep_type"],
-                $mail_vocab["rep_type_$temp"], $new_entry);
-        }
-        
-        // Details if a series
-        if ($rep_type > 0)
-        {
-	    $opt = "";
-	    if (($rep_type == 2) || ($rep_type == 6))
-	    {
-		# Display day names according to language and preferred weekday start.
-		for ($i = 0; $i < 7; $i++)
-		{
-			$daynum = ($i + $weekstarts) % 7;
-			if ($rep_opt[$daynum]) $opt .= day_name($daynum) . " ";
-		}
-	    }
-	    if ($rep_type == 6)
-	    {
-		$body .= "\n" . $mail_vocab["rep_num_weeks"];
-		$body .=  ": " . compareEntries($rep_num_weeks, $mail_previous["rep_num_weeks"], $new_entry);
-	    }
-	
-	    if($opt || $mail_previous["rep_opt"])
-	    {
-		$body .= "\n" . $mail_vocab["rep_rep_day"];
-		$body .=  " " . compareEntries($opt, $mail_previous["rep_opt"], $new_entry);
-	    }
-
-            $body .= "\n" . $mail_vocab["rep_end_date"];
-            if ($new_entry)
-            {
-                $body .= " " . userdate($rep_enddate, '%A %d %B %Y');
-            }
-            else
-            {
-                $temp = userdate($rep_enddate, '%A %d %B %Y');
-                $body .=  " " . 
-                    compareEntries($temp, $mail_previous['rep_end_date'], $new_entry) . "\n";
-            }
-        }
-	$body .= "\n";
-    }
-    $result = sendMail($recipients, $subject, $body, $mail_vocab['charset'] ,MAIL_CC);
-    return $result;
-}
-
-// }}}
-// {{{ notifyAdminOnDelete()
-
-/**
- * Send email to administrator to notify a new/changed entry.
- *
- * @param   array   $mail_previous  contains deleted entry data forr email body
- * @return  bool    TRUE or PEAR error object if fails
- */
-function notifyAdminOnDelete($mail_previous)
-{
-    global $mail_vocab, $typel, $enable_periods, $auth, $tbl_users;
-    //
-    $recipients = '';
-    (MAIL_ADMIN_ON_BOOKINGS) ? $recipients = MAIL_RECIPIENTS : '';
-    if (MAIL_AREA_ADMIN_ON_BOOKINGS)
-    {
-        if ( !empty($recipients) && ('' != $mail_previous['area_admin_email']) )
-        {
-            $recipients .= ',';
-        }
-        if ('' != $mail_previous['area_admin_email'])
-        {
-            $recipients .= $mail_previous['area_admin_email'];
-        }
-    }
-    if (MAIL_ROOM_ADMIN_ON_BOOKINGS)
-    {
-        if ( !empty($recipients) && ('' != $mail_previous['room_admin_email']) )
-        {
-            $recipients .= ',';
-        }
-        if ('' != $mail_previous['room_admin_email'])
-        {
-            $recipients .= $mail_previous['room_admin_email'];
-        }
-    }
-    if (MAIL_BOOKER)
-    {
-        if ('db' == $auth['type'])
-        {
-            /* It would be possible to move this query within the query in
-               getPreviousEntryData to have all in one central place and to
-               reduce database hits by one. However this is a bad idea. If a
-               user is deleted from your user database, this will prevent all
-               mails to admins when this user previously booked entries will
-               be changed, as no user name will match the booker name */
-            $sql = "SELECT email
-                    FROM $tbl_users
-                    WHERE name='" . $mail_previous['createdby'] . "'";
-            $res = sql_query($sql);
-            (! $res) ? fatal_error(0, sql_error()) : '';
-            $row = sql_row($res, 0);
-            if ( !empty($recipients) && (NULL != $row[0]) )
-            {
-                $recipients .= ',';
-            }
-            if (NULL != $row[0])
-            {
-                $recipients .= $row[0];
-            }
-        }
-        else
-        {
-            if ( !empty($recipients) && ('' != $mail_previous['createdby']) )
-            {
-                $recipients .= ',';
-            }
-            if ('' != $mail_previous['createdby'])
-            {
-                $recipients .= str_replace(MAIL_USERNAME_SUFFIX, '',
-                    $mail_previous['createdby']) . MAIL_DOMAIN;
-            }
-        }
-    }
-    // In case mail is allowed but someone forgot to supply email addresses...
-    if ('' == $recipients)
-    {
-        return FALSE;
-    }
-    //
-    $subject = $mail_vocab["mail_subject_delete"];
-    $body = $mail_vocab["mail_body_del_entry"] . "\n\n";
-    // Displays deleted entry details
-    $body .= "\n" . $mail_vocab["namebooker"] . ' ';
-    $body .= removeMailUnicode($mail_previous['namebooker']) . "\n";
-    $body .= $mail_vocab["description"] . " ";
-    $body .= removeMailUnicode($mail_previous['description']) . "\n";
-    $body .= $mail_vocab["room"] . ": ";
-    $body .= removeMailUnicode($mail_previous['area_name']);
-    $body .= " - " . removeMailUnicode($mail_previous['room_name']) . "\n";
-    $body .= $mail_vocab["start_date"] . ' ';
-    if ( $enable_periods )
-    {
-        $body .= unHtmlEntities($mail_previous['start_date']) . "\n";
-    }
-    else
-    {
-        $body .= $mail_previous['start_date'] . "\n";
-    }
-    $body .= $mail_vocab["duration"] . ' ' . $mail_previous['duration'] . ' ';
-    $body .= $mail_previous['dur_units'] . "\n";
-    if ( $enable_periods )
-    {
-        $body .= $mail_vocab["end_date"] . " ";
-        $body .= unHtmlEntities($mail_previous['end_date']) ."\n";
-    }
-    else
-    {
-        $body .= $mail_vocab["end_date"] . " " . $mail_previous['end_date'];
-        $body .= "\n";
-    }
-    $body .= $mail_vocab["type"] . " ";
-    $body .=  (empty($typel[$mail_previous['type']])) ? "?" .
-        $mail_previous['type'] . "?" : $typel[$mail_previous['type']];
-    $body .= "\n" . $mail_vocab["createdby"] . " ";
-    $body .= $mail_previous['createdby'] . "\n";
-    $body .= $mail_vocab["lastupdate"] . " " . $mail_previous['updated'];
-    $body .= "\n" . $mail_vocab["rep_type"];
-    $temp = $mail_previous['rep_type'];
-    $body .=  " " . $mail_vocab["rep_type_$temp"];
-    if ($mail_previous['rep_type'] > 0)
-    {
-        if ($mail_previous['rep_type'] == 6)
-        {
-           $body .= "\n" . $mail_vocab["rep_num_weeks"];
-           $body .=  ": " . $mail_previous["rep_num_weeks"];
-        }
-   
-        if($mail_previous["rep_opt"])
-        {
-           $body .= "\n" . $mail_vocab["rep_rep_day"];
-           $body .=  " " . $mail_previous["rep_opt"];
-        }
-
-        $body .= "\n" . $mail_vocab["rep_end_date"];
-        $body .=  " " . $mail_previous['rep_end_date'] . "\n";
-    }
-    $body .= "\n";
-    // End of mail details
-    $result = sendMail($recipients, $subject, $body, $mail_vocab['charset'], MAIL_CC);
-    return $result;
-}
-
-// }}}
-// {{{ getPreviousEntryData()
-
-/**
- * Gather all fields values for an entry. Used for emails to get previous
- * entry state.
- *
- * @param int     $id       entry id to get data
- * @param int     $series   1 if this is a serie or 0
- * @return bool             TRUE or PEAR error object if fails
- */
-function getPreviousEntryData($id, $series)
-{
-    global $tbl_area, $tbl_entry, $tbl_repeat, $tbl_room, $enable_periods;
-    //
-    $sql = "
-    SELECT  e.name,
-            e.description,
-            e.create_by,
-            r.room_name,
-            a.area_name,
-            e.type,
-            e.room_id,
-            e.repeat_id, " .
-            sql_syntax_timestamp_to_unix("e.timestamp") . ",
-            (e.end_time - e.start_time) AS tbl_e_duration,
-            e.start_time AS tbl_e_start_time,
-            e.end_time AS tbl_e_end_time,
-            a.area_admin_email,
-            r.room_admin_email";
-    // Here we could just use $tbl_repeat.start_time, and not use alias,
-    // as the last column will take precedence using mysql_fetch_array,
-    // but for portability purpose I will not use it.
-    if (1 == $series)
-    {
-        $sql .= ", re.rep_type, re.rep_opt, re.rep_num_weeks,
-            (re.end_time - re.start_time) AS tbl_r_duration,
-            re.start_time AS tbl_r_start_time,
-            re.end_time AS tbl_r_end_time,
-            re.end_date AS tbl_r_end_date";
-    }
-    $sql .= "
-    FROM $tbl_entry e, $tbl_room r, $tbl_area a ";
-    (1 == $series) ? $sql .= ', ' . $tbl_repeat . ' re ' : '';
-    $sql .= "
-    WHERE e.room_id = r.id
-    AND r.area_id = a.id
-    AND e.id=$id";
-    (1 == $series) ? $sql .= " AND e.repeat_id = re.id" : '';
-    //
-    $res = sql_query($sql);
-    (! $res) ? fatal_error(0, sql_error()) : '';
-    (sql_count($res) < 1) ? fatal_error(0, get_string('invalid_entry_id','block_mrbs')) : '';
-    $row = sql_row_keyed($res, 0);
-    sql_free($res);
-    // Store all needed values in $mail_previous array to pass to
-    // notifyAdminOnDelete function (shorter than individual variables -:) )
-    $mail_previous['namebooker']    = $row['name'];
-    $mail_previous['description']   = $row['description'];
-    $mail_previous['createdby']     = $row['create_by'];
-    $mail_previous['room_name']     = $row['room_name'];
-    $mail_previous['area_name']     = $row['area_name'];
-    $mail_previous['type']          = $row['type'];
-    $mail_previous['room_id']       = $row['room_id'];
-    $mail_previous['repeat_id']     = $row['repeat_id'];
-    $mail_previous['updated']       = getMailTimeDateString($row[8]);
-    $mail_previous['area_admin_email'] = $row['area_admin_email'];
-    $mail_previous['room_admin_email'] = $row['room_admin_email'];
-    // If we use periods
-    if ( $enable_periods )
-    {
-        // If we delete a serie, start_time and end_time must
-        // come from $tbl_repeat, not $tbl_entry.
-        //
-        // This is not a serie
-        if (1 != $series)
-        {
-            list( $mail_previous['start_period'], $mail_previous['start_date'])
-                =  getMailPeriodDateString($row['tbl_e_start_time']);
-            list( $mail_previous['end_period'] , $mail_previous['end_date']) =
-                getMailPeriodDateString($row['tbl_e_end_time'], -1);
-            // need to make DST correct in opposite direction to entry creation
-            // so that user see what he expects to see
-            $mail_previous['duration'] = $row['tbl_e_duration'] -
-                cross_dst($row['tbl_e_start_time'], $row['tbl_e_end_time']);
-        }
-        // This is a serie
-        else
-        {
-            list( $mail_previous['start_period'], $mail_previous['start_date'])
-                =  getMailPeriodDateString($row['tbl_r_start_time']);
-            list( $mail_previous['end_period'] , $mail_previous['end_date']) =
-                getMailPeriodDateString($row['tbl_r_end_time'], 0);
-            // use getMailTimeDateString as all I want is the date
-	    $mail_previous['rep_end_date'] =
-                getMailTimeDateString($row['tbl_r_end_date'], FALSE);
-            // need to make DST correct in opposite direction to entry creation
-            // so that user see what he expects to see
-            $mail_previous['duration'] = $row['tbl_r_duration'] -
-                cross_dst($row['tbl_r_start_time'], $row['tbl_r_end_time']);
-	    
-	    $mail_previous['rep_opt'] = "";
-	    switch($row['rep_type'])
-	    {
-		case 2:
-		case 6:
-			$rep_day[0] = $row['rep_opt'][0] != "0";
-			$rep_day[1] = $row['rep_opt'][1] != "0";
-			$rep_day[2] = $row['rep_opt'][2] != "0";
-			$rep_day[3] = $row['rep_opt'][3] != "0";
-			$rep_day[4] = $row['rep_opt'][4] != "0";
-			$rep_day[5] = $row['rep_opt'][5] != "0";
-			$rep_day[6] = $row['rep_opt'][6] != "0";
-
-			if ($row['rep_type'] == 6)
-			{
-				$mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
-			}
-			else
-			{
-				$mail_previous['rep_num_weeks'] = "";
-			}
-			
-			break;
-		
-		default:
-			$rep_day = array(0, 0, 0, 0, 0, 0, 0);
-	    }
-	    for ($i = 0; $i < 7; $i++)
-	    {
-		$wday = ($i + $weekstarts) % 7;
-		if ($rep_day[$wday])
-		    $mail_previous['rep_opt'] .= day_name($wday) . " ";
-	    }
-	    
-	    $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
-        }
-        toPeriodString($mail_previous['start_period'],
-            $mail_previous['duration'], $mail_previous['dur_units']);
-    }
-    // If we don't use periods
-    else
-    {
-        // This is not a serie
-        if (1 != $series)
-        {
-            $mail_previous['start_date'] =
-                getMailTimeDateString($row['tbl_e_start_time']);
-            $mail_previous['end_date'] =
-                getMailTimeDateString($row['tbl_e_end_time']);
-            // need to make DST correct in opposite direction to entry creation
-            // so that user see what he expects to see
-            $mail_previous['duration'] = $row['tbl_e_duration'] -
-                cross_dst($row['tbl_e_start_time'], $row['tbl_e_end_time']);
-        }
-        // This is a serie
-        else
-        {
-            $mail_previous['start_date'] =
-                getMailTimeDateString($row['tbl_r_start_time']);
-            $mail_previous['end_date'] =
-                getMailTimeDateString($row['tbl_r_end_time']);
-            // use getMailTimeDateString as all I want is the date
-	    $mail_previous['rep_end_date'] =
-                getMailTimeDateString($row['tbl_r_end_date'], FALSE);
-            // need to make DST correct in opposite direction to entry creation
-            // so that user see what he expects to see
-            $mail_previous['duration'] = $row['tbl_r_duration'] -
-                cross_dst($row['tbl_r_start_time'], $row['tbl_r_end_time']);
-            
-	    $mail_previous['rep_opt'] = "";
-	    switch($row['rep_type'])
-	    {
-		case 2:
-		case 6:
-			$rep_day[0] = $row['rep_opt'][0] != "0";
-			$rep_day[1] = $row['rep_opt'][1] != "0";
-			$rep_day[2] = $row['rep_opt'][2] != "0";
-			$rep_day[3] = $row['rep_opt'][3] != "0";
-			$rep_day[4] = $row['rep_opt'][4] != "0";
-			$rep_day[5] = $row['rep_opt'][5] != "0";
-			$rep_day[6] = $row['rep_opt'][6] != "0";
-
-			if ($row['rep_type'] == 6)
-			{
-				$mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
-			}
-			else
-			{
-				$mail_previous['rep_num_weeks'] = "";
-			}
-			
-			break;
-		
-		default:
-			$rep_day = array(0, 0, 0, 0, 0, 0, 0);
-	    }
-	    for ($i = 0; $i < 7; $i++)
-	    {
-		$wday = ($i + $weekstarts) % 7;
-		if ($rep_day[$wday])
-		    $mail_previous['rep_opt'] .= day_name($wday) . " ";
-	    }
-	    
-	    $mail_previous['rep_num_weeks'] = $row['rep_num_weeks'];
-        }
-        toTimeString($mail_previous['duration'], $mail_previous['dur_units']);
-    }
-    (1 == $series) ? $mail_previous['rep_type'] = $row['rep_type']
-        : $mail_previous['rep_type'] = 0;
-    // return entry previous data as an array
-    return $mail_previous;
-}
-
-// }}}
-// {{{ compareEntries()
-
-/**
- * Compare entries fields to show in emails.
- *
- * @param string  $new_value       new field value
- * @param string  $previous_value  previous field value
- * @return string                  new value if no difference, new value and
- *                                 previous value in brackets otherwise
- */
-function compareEntries($new_value, $previous_value, $new_entry)
-{
-    $suffix = "";
-    if ($new_entry)
-    {
-        return $new_value;
-    }
-    if ($new_value != $previous_value)
-    {
-        $suffix = " ($previous_value)";
-    }
-    return($new_value . $suffix);
-}
-
-// }}}
-// {{{ sendMail()
-
-/**
- * Send emails using PEAR::Mail class.
- * How to use this class -> http://www.pear.php.net/package/Mail then link
- * "View documentation".
- * Currently implemented version: Mail 1.1.3 and its dependancies
- * Net_SMTP 1.2.6 and Net_Socket 1.0.2
- *
- * @param string  $recipients       comma separated list of recipients or array
- * @param string  $subject          email subject
- * @param string  $body             text message
- * @param string  $charset          character set used in body
- * @param string  $cc               Carbon Copy
- * @param string  $bcc              Blind Carbon Copy
- * @param string  $from             from field
- * @param string  $backend          'mail', 'smtp' or 'sendmail'
- * @param string  $sendmail_path    ie. "/usr/bin/sendmail"
- * @param string  $sendmail_args    ie. "-t -i"
- * @param string  $host             smtp server hostname
- * @param string  $port             smtp server port
- * @param string  $auth             smtp server authentication, TRUE/FALSE
- * @param string  $username         smtp server username
- * @param string  $password         smtp server password
- * @return bool                     TRUE or PEAR error object if fails
- */
-function sendMail($recipients, $subject, $body, $charset = 'us-ascii',
-    $cc = NULL, $bcc = NULL, $from = MAIL_FROM, $backend = MAIL_ADMIN_BACKEND,
-    $sendmail_path = SENDMAIL_PATH, $sendmail_args = SENDMAIL_ARGS,
-    $host = SMTP_HOST, $port = SMTP_PORT, $auth = SMTP_AUTH,
-    $username = SMTP_USERNAME, $password = SMTP_PASSWORD)
-{
-    require_once "Mail.php";
-
-    // Headers part
-    $headers['From']         = $from;
-    if( $backend != 'mail' ) {
-        $headers['To']           = $recipients;
-    }
-    (NULL != $cc) ? $headers['Cc'] = $cc : '';
-    (NULL != $bcc) ? $headers['Bcc'] = $bcc : '';
-    $headers['Subject']      = $subject;
-    $headers['MIME-Version'] = '1.0';
-    $headers['Content-Type'] = 'text/plain; charset=' . $charset;
-
-    // Parameters part
-    if( $backend == 'sendmail' ) {
-        $params['sendmail_path'] = $sendmail_path;
-        $params['sendmail_args'] = $sendmail_args;
-    }
-    if( $backend == "smtp" ) {
-        $params['host']          = $host;
-        $params['port']          = $port;
-        $params['auth']          = $auth;
-        $params['username']      = $username;
-        $params['password']      = $password;
-    }
-
-    // Call to the PEAR::Mail class
-    $mail_object =& Mail::factory($backend, $params);
-    $result = $mail_object->send($recipients, $headers, $body);
-
-    if (is_object($result))
-    {
-      error_log("Error sending email: ".$result->getMessage());
-    }
-    return $result;
-}
-
-// }}}
-// {{{ unHtmlEntities()
-
-/**
- * Convert all HTML entities to their applicable characters.
- * Added to remove HTML entities that are not suitable for plain text emails.
- * May be replaced by PHP function 'html_entity_decode()' but this function
- * only exist since PHP 4.3.0 and is buggy before PHP5.
- *
- * @param  string   $string     string to decode
- * @return string               decoded string
- */
-function unHtmlEntities($string)
-{
-    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
-    $trans_tbl = array_flip($trans_tbl);
-    return strtr($string, $trans_tbl);
-}
-
-// }}}
-?>
Index: plugins/blocks/mrbs/web/del_entry.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/mrbs/web/del_entry.php,v
retrieving revision 1.3
diff -u -r1.3 del_entry.php
--- plugins/blocks/mrbs/web/del_entry.php	4 Aug 2008 01:17:51 -0000	1.3
+++ plugins/blocks/mrbs/web/del_entry.php	5 Aug 2008 04:49:41 -0000
@@ -17,10 +17,7 @@
 	$year  = userdate($info["start_time"], "%Y");
 	$area  = mrbsGetRoomArea($info["room_id"]);
 
-    if (MAIL_ADMIN_ON_DELETE)
-    {
-        include_once "functions_mail.php";
-        // Gather all fields values for use in emails.
+    if (MAIL_ADMIN_ON_DELETE) { // Gather all fields values for use in emails.
         $mail_previous = getPreviousEntryData($id, $series);
     }
     sql_begin();
Index: plugins/blocks/mrbs/web/edit_entry_handler.php
===================================================================
RCS file: /cvsroot/moodle/contrib/plugins/blocks/mrbs/web/edit_entry_handler.php,v
retrieving revision 1.5
diff -u -r1.5 edit_entry_handler.php
--- plugins/blocks/mrbs/web/edit_entry_handler.php	2 Aug 2008 04:44:16 -0000	1.5
+++ plugins/blocks/mrbs/web/edit_entry_handler.php	5 Aug 2008 04:49:41 -0000
@@ -217,10 +217,7 @@
                                       $room_id,   $create_by, $name,     $type,        $description,
                                       isset($rep_num_weeks) ? $rep_num_weeks : 0);
             // Send a mail to the Administrator
-            if (MAIL_ADMIN_ON_BOOKINGS or MAIL_AREA_ADMIN_ON_BOOKINGS or
-                MAIL_ROOM_ADMIN_ON_BOOKINGS or MAIL_BOOKER)
-            {
-                include_once "functions_mail.php";
+            if (MAIL_ADMIN_ON_BOOKINGS or MAIL_AREA_ADMIN_ON_BOOKINGS or MAIL_ROOM_ADMIN_ON_BOOKINGS or MAIL_BOOKER) {
                 // Send a mail only if this a new entry, or if this is an
                 // edited entry but we have to send mail on every change,
                 // and if mrbsCreateRepeatingEntrys is successful
@@ -261,10 +258,7 @@
             $new_id = mrbsCreateSingleEntry($starttime, $endtime, $entry_type, $repeat_id, $room_id,
                                      $create_by, $name, $type, $description);
             // Send a mail to the Administrator
-            if (MAIL_ADMIN_ON_BOOKINGS or MAIL_AREA_ADMIN_ON_BOOKINGS or
-                MAIL_ROOM_ADMIN_ON_BOOKINGS or MAIL_BOOKER)
-            {
-                include_once "functions_mail.php";
+            if (MAIL_ADMIN_ON_BOOKINGS or MAIL_AREA_ADMIN_ON_BOOKINGS or MAIL_ROOM_ADMIN_ON_BOOKINGS or MAIL_BOOKER) {
                 // Send a mail only if this a new entry, or if this is an
                 // edited entry but we have to send mail on every change,
                 // and if mrbsCreateRepeatingEntrys is successful

