static function sendMail(&$username, &$hash, &$email, $approve_only = false, $admin_cc = true)
 {
     global $serendipity;
     if ($approve_only) {
         $activation_url = $serendipity['baseURL'] . $serendipity['indexFile'] . '?r=1&serendipity%5Badduser_activation%5D=' . $hash . '#adduser';
     } else {
         $activation_url = $serendipity['baseURL'] . $serendipity['indexFile'] . '?serendipity%5Badduser_activation%5D=' . $hash . '#adduser';
     }
     $fromName = $serendipity['blogTitle'];
     if ($approve_only) {
         $subject = '[' . $serendipity['blogTitle'] . '] ' . PLUGIN_ADDUSER_MAIL_SUBJECT_APPROVE;
         $message = sprintf(PLUGIN_ADDUSER_MAIL_BODY_APPROVE, $username . ' (' . $email . ')', $serendipity['baseURL'] . 'serendipity_admin.php', $activation_url);
     } else {
         $subject = '[' . $serendipity['blogTitle'] . '] ' . PLUGIN_ADDUSER_MAIL_SUBJECT;
         $message = sprintf(PLUGIN_ADDUSER_MAIL_BODY, $username . ' (' . $email . ')', $serendipity['baseURL'] . 'serendipity_admin.php', $activation_url);
     }
     $admins = serendipity_db_query("SELECT authorid, email FROM {$serendipity['dbPrefix']}authors WHERE userlevel = " . USERLEVEL_ADMIN);
     $admin_cc = array();
     if (is_array($admins)) {
         foreach ($admins as $idx => $admin) {
             if (empty($admin['email'])) {
                 continue;
             }
             $admin_cc[] = $admin['email'];
             serendipity_sendMail($admin['email'], $subject, $message, $email, null, $serendipity['blogTitle']);
         }
     }
     if ($approve_only) {
         // Only Admin-Mails, done in the foreach-loop above already.
     } else {
         // Send out Mails to the actual receiver.
         $mail = serendipity_sendMail($email, $subject, $message, $email, null, $serendipity['blogTitle']);
     }
     return $mail;
 }
/**
 * Send a comment notice to the admin/author of an entry
 *
 * @access public
 * @param  int      ID of the comment that has been made
 * @param  string   Author's email address to send the mail to
 * @param  string   The name of the sender
 * @param  string   The URL of the sender
 * @param  int      The ID of the entry that has been commented
 * @param  string   The title of the entry that has been commented
 * @param  string   The text of the comment
 * @param  string   The type of the comment (normal|trackback)
 * @param  boolean  Toggle Whether comments to this entry need approval
 * @return boolean  Return success of sending the mails
 */
function serendipity_sendComment($comment_id, $to, $fromName, $fromEmail, $fromUrl, $id, $title, $comment, $type = 'NORMAL', $moderate_comment = false)
{
    global $serendipity;
    if (empty($fromName)) {
        $fromName = ANONYMOUS;
    }
    $entryURI = serendipity_archiveURL($id, $title, 'baseURL');
    $path = $type == 'TRACKBACK' ? 'trackback' : 'comment';
    // Check for using Tokens
    if ($serendipity['useCommentTokens']) {
        $token = md5(uniqid(rand(), 1));
        $path = $path . "_token_" . $token;
        //Delete any comment tokens older than 1 week.
        serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}options\n                              WHERE okey LIKE 'comment_%' AND name < " . (time() - 604800));
        // Issue new comment moderation hash
        serendipity_db_query("INSERT INTO {$serendipity['dbPrefix']}options (name, value, okey)\n                              VALUES ('" . time() . "', '" . $token . "', 'comment_" . $comment_id . "')");
    }
    $deleteURI = serendipity_rewriteURL(PATH_DELETE . '/' . $path . '/' . $comment_id . '/' . $id . '-' . serendipity_makeFilename($title) . '.html', 'baseURL');
    $approveURI = serendipity_rewriteURL(PATH_APPROVE . '/' . $path . '/' . $comment_id . '/' . $id . '-' . serendipity_makeFilename($title) . '.html', 'baseURL');
    if ($type == 'TRACKBACK') {
        /******************* TRACKBACKS *******************/
        $subject = ($moderate_comment ? '[' . REQUIRES_REVIEW . '] ' : '') . NEW_TRACKBACK_TO . ' ' . $title;
        $text = sprintf(A_NEW_TRACKBACK_BLAHBLAH, $title) . "\n" . "\n" . REQUIRES_REVIEW . ': ' . ($moderate_comment ? YES : NO) . (isset($serendipity['moderate_reason']) ? ' (' . $serendipity['moderate_reason'] . ')' : '') . "\n" . LINK_TO_ENTRY . ': ' . $entryURI . "\n" . 'Weblog ' . NAME . ': ' . stripslashes($fromName) . "\n" . LINK_TO_REMOTE_ENTRY . ': ' . $fromUrl . "\n" . "\n" . EXCERPT . ':' . "\n" . strip_tags($comment) . "\n" . "\n" . '----' . "\n" . YOU_HAVE_THESE_OPTIONS . ($moderate_comment ? "\n" . str_repeat(' ', 2) . THIS_TRACKBACK_NEEDS_REVIEW : '') . "\n" . str_repeat(' ', 3) . str_pad(VIEW_ENTRY, 15) . ' -- ' . $entryURI . "\n" . str_repeat(' ', 3) . str_pad(DELETE_TRACKBACK, 15) . ' -- ' . $deleteURI . ($moderate_comment ? "\n" . str_repeat(' ', 3) . str_pad(APPROVE_TRACKBACK, 15) . ' -- ' . $approveURI : '');
    } else {
        /******************* COMMENTS *********************/
        $subject = ($moderate_comment ? '[' . REQUIRES_REVIEW . '] ' : '') . NEW_COMMENT_TO . ' ' . $title;
        $text = sprintf(A_NEW_COMMENT_BLAHBLAH, $serendipity['blogTitle'], $title) . "\n" . LINK_TO_ENTRY . ': ' . $entryURI . "\n" . "\n" . REQUIRES_REVIEW . ': ' . ($moderate_comment ? YES : NO) . (isset($serendipity['moderate_reason']) ? ' (' . $serendipity['moderate_reason'] . ')' : '') . "\n" . USER . ' ' . IP_ADDRESS . ': ' . $_SERVER['REMOTE_ADDR'] . "\n" . USER . ' ' . NAME . ': ' . $fromName . "\n" . USER . ' ' . EMAIL . ': ' . $fromEmail . "\n" . USER . ' ' . HOMEPAGE . ': ' . $fromUrl . "\n" . "\n" . COMMENTS . ': ' . "\n" . strip_tags($comment) . "\n" . "\n" . '----' . "\n" . YOU_HAVE_THESE_OPTIONS . ($moderate_comment ? "\n" . str_repeat(' ', 2) . THIS_COMMENT_NEEDS_REVIEW : '') . "\n" . str_repeat(' ', 3) . str_pad(VIEW_COMMENT, 15) . ' -- ' . $entryURI . '#c' . $comment_id . "\n" . str_repeat(' ', 3) . str_pad(DELETE_COMMENT, 15) . ' -- ' . $deleteURI . ($moderate_comment ? "\n" . str_repeat(' ', 3) . str_pad(APPROVE_COMMENT, 15) . ' -- ' . $approveURI : '');
    }
    return serendipity_sendMail($to, $subject, $text, $fromEmail, null, $fromName);
}
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                case 'backend_display':
                    if (isset($serendipity['POST']['properties']['mailto'])) {
                        $mailto = $serendipity['POST']['properties']['mailto'];
                    } else {
                        $mailto = $this->get_config('mailto');
                    }
                    if (isset($serendipity['POST']['properties']['sendentry_all'])) {
                        $sendtoall = $serendipity['POST']['properties']['sendentry_all'];
                    } else {
                        $sendtoall = serendipity_db_bool($this->get_config('sendtoall'));
                    }
                    ?>
                    <fieldset class="entryproperties">
                        <span class="wrap_legend"><legend><?php 
                    echo PLUGIN_EVENT_MAILER_NAME;
                    ?>
</legend></span>

                        <div class="form_check">
                            <input id="properties_sendentry" type="checkbox" name="serendipity[properties][sendentry]" value="true" checked="checked">
                            <label title="<?php 
                    echo PLUGIN_EVENT_MAILER_SENDING;
                    ?>
" for="properties_sendentry"><?php 
                    echo PLUGIN_EVENT_MAILER_ISTOSENDIT;
                    ?>
</label>
                        </div>
                        <div class="form_field">
                            <label title="<?php 
                    echo PLUGIN_EVENT_MAILER_RECIPIENT;
                    ?>
" for="properties_mailto"><?php 
                    echo PLUGIN_EVENT_MAILER_RECIPIENTS;
                    ?>
</label>
                            <input id="properties_mailto" type="text" name="serendipity[properties][mailto]" value="<?php 
                    echo serendipity_specialchars($mailto);
                    ?>
">
                        </div>
                        <div class="form_check">
                            <input id="sendall" type="checkbox" value="true" name="serendipity[properties][sendentry_all]" <?php 
                    echo $sendtoall ? 'checked="checked"' : '';
                    ?>
>
                            <label title="<?php 
                    echo PLUGIN_EVENT_MAILER_SENDTOALL;
                    ?>
" for="sendall"><?php 
                    echo PLUGIN_EVENT_MAILER_SENDTOALL;
                    ?>
</label>
                        </div>
                    </fieldset>
<?php 
                    break;
                case 'backend_publish':
                    if (isset($serendipity['POST']['properties']) && !isset($serendipity['POST']['properties']['sendentry'])) {
                        echo PLUGIN_EVENT_MAILER_NOTSENDDECISION . '<br />';
                    } else {
                        $mails = explode(' ', str_replace(',', '', $this->get_config('mailto')));
                        $to = array();
                        foreach ($mails as $mailto) {
                            $mailto = trim($mailto);
                            if (!empty($mailto)) {
                                $to[] = $mailto;
                            }
                        }
                        $this->performConfig($to);
                        if (is_array($this->data['cat'])) {
                            $selected = array();
                            if (is_array($eventData['categories'])) {
                                foreach ($eventData['categories'] as $idx => $cid) {
                                    $selected[$cid] = true;
                                }
                            }
                            foreach ($this->data['cat'] as $cid => $cat) {
                                $mailto = trim($this->get_config('category_' . $cid));
                                if (!empty($mailto) && isset($selected[$cid])) {
                                    $tos = explode(' ', str_replace(',', '', $mailto));
                                    foreach ($tos as $mailtopart) {
                                        $to[] = trim($mailtopart);
                                    }
                                }
                            }
                        }
                        if ($serendipity['POST']['properties']['sendentry_all']) {
                            $mails = serendipity_db_query("SELECT DISTINCT email FROM {$serendipity['dbPrefix']}authors");
                            foreach ($mails as $mail) {
                                $to[] = trim($mail['email']);
                            }
                        }
                        $mail = array('subject' => $eventData['title'], 'body' => $eventData['body'] . $eventData['extended'], 'from' => $serendipity['serendipityEmail']);
                        switch ($this->get_config('what')) {
                            case 'all':
                                $mail['body'] = $eventData['body'] . $eventData['extended'];
                                break;
                            case 'body':
                                $mail['body'] = $eventData['body'];
                                break;
                            case 'extended':
                                $mail['body'] = $eventData['extended'];
                                break;
                            case 'none':
                                $mail['body'] = '';
                                break;
                        }
                        if (isset($serendipity['POST']['properties']['mailto'])) {
                            $mails = explode(' ', str_replace(',', '', $serendipity['POST']['properties']['mailto']));
                            foreach ($mails as $mailto) {
                                $mailto = trim($mailto);
                                if (!in_array($mailto, $to)) {
                                    $to[] = $mailto;
                                }
                            }
                        }
                        if (serendipity_db_bool($this->get_config('convertp', 'false'))) {
                            $mail['body'] = str_replace('</p>', "</p>\n", $mail['body']);
                        }
                        if (serendipity_db_bool($this->get_config('striptags', 'false'))) {
                            if (serendipity_db_bool($this->get_config('keepstriptags', 'true'))) {
                                $mail['body'] = preg_replace('§<a[^>]+href=["\']([^"\']*)["\'][^>]*>([^<]*)</a>§i', "\$2 [\$1]", $mail['body']);
                                $mail['body'] = preg_replace('§<img[^>]+src=["\']([^"\']*)["\'][^>]*>§i', "[" . IMAGE . ": \$1]", $mail['body']);
                            } else {
                                $mail['body'] = preg_replace('§<a[^>]+href=["\']([^"\']*)["\'][^>]*>([^<]*)</a>§i', "", $mail['body']);
                                $mail['body'] = preg_replace('§<img[^>]+src=["\']([^"\']*)["\'][^>]*>§i', "", $mail['body']);
                            }
                            $mail['body'] = strip_tags($mail['body']);
                        }
                        if (serendipity_db_bool($this->get_config('includelink', 'false'))) {
                            $mail['body'] = serendipity_archiveURL($eventData['id'], $eventData['title'], 'baseURL', true, array('timestamp' => $eventData['timestamp'])) . "\n\n" . $mail['body'];
                        }
                        foreach ($to as $mailto) {
                            if (!empty($mailto)) {
                                echo serendipity_specialchars($mailto) . '...<br />';
                                serendipity_sendMail($mailto, $mail['subject'], $mail['body'], $mail['from']);
                            }
                        }
                    }
                    break;
                default:
                    return false;
            }
            return true;
        } else {
            return false;
        }
    }
 function sendComment($to, $fromName, $fromEmail, $fromUrl, $comment, $dynamic = false)
 {
     global $serendipity;
     if (empty($fromName)) {
         $fromName = ANONYMOUS;
     }
     $title = $this->get_config('pagetitle');
     $subject = sprintf($this->get_config('subject'), $title);
     $text = '';
     if (serendipity_db_bool($this->get_config('counter'))) {
         $this->set_config('counternumber', $this->get_config('counternumber') + 1);
         $subject = '[' . $this->get_config('counternumber') . '] ' . $subject;
         $text .= sprintf(PLUGIN_CONTACTFORM_MAIL_ISSUECOUNTER, $this->get_config('counternumber')) . "\n";
     }
     $text .= sprintf(A_NEW_COMMENT_BLAHBLAH, $serendipity['blogTitle'], $title) . "\n" . "\n" . USER . ' ' . IP_ADDRESS . ': ' . $_SERVER['REMOTE_ADDR'];
     if (!$dynamic) {
         $text = $text . "\n" . USER . ' ' . NAME . ': ' . $fromName . "\n" . USER . ' ' . EMAIL . ': ' . $fromEmail . "\n" . USER . ' ' . HOMEPAGE . ': ' . $fromUrl . "\n" . "\n" . COMMENTS . ': ';
     }
     $text = $text . "\n" . $comment . "\n" . "\n" . '----';
     return serendipity_sendMail($to, $subject, $text, $fromEmail, null, $fromName);
 }
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         switch ($event) {
             case 'cronjob':
                 if ($this->get_config('cronjob') == $eventData) {
                     serendipity_event_cronjob::log('Spartacus', 'plugin');
                     $avail = array();
                     $install = array();
                     $meth = array('event', 'sidebar');
                     $active = serendipity_plugin_api::get_installed_plugins();
                     $avail['event'] = $this->buildList($this->fetchOnline('event'), 'event');
                     $avail['sidebar'] = $this->buildList($this->fetchOnline('sidebar'), 'sidebar');
                     #echo "XAVAIL:<pre>" . print_r($avail, true) . "</pre>";
                     $install['event'] = serendipity_plugin_api::enum_plugin_classes(true);
                     $install['sidebar'] = serendipity_plugin_api::enum_plugin_classes(false);
                     #echo "XINSTALL:<pre>" . print_r($install, true) . "</pre>";
                     $mailtext = '';
                     foreach ($meth as $method) {
                         foreach ($install[$method] as $class_data) {
                             #echo "Probe " . $class_data['name']. "<br />\n"; // DEBUG
                             $pluginFile = serendipity_plugin_api::probePlugin($class_data['name'], $class_data['classname'], $class_data['pluginPath']);
                             $plugin = serendipity_plugin_api::getPluginInfo($pluginFile, $class_data, $method);
                             if (is_object($plugin)) {
                                 #echo "Non cached<br />\n";
                                 #echo "<pre>" . print_r($avail[$method][$class_data['name']], true) . "</pre>";
                                 // Object is returned when a plugin could not be cached.
                                 $bag = new serendipity_property_bag();
                                 $plugin->introspect($bag);
                                 // If a foreign plugin is upgradable, keep the new version number.
                                 if (isset($avail[$method][$class_data['name']])) {
                                     $class_data['upgrade_version'] = $avail[$method][$class_data['name']]['upgrade_version'];
                                 }
                                 $props = serendipity_plugin_api::setPluginInfo($plugin, $pluginFile, $bag, $class_data, 'local', $avail[$method]);
                                 #echo "<pre>" . print_r($props, true) . "</pre>";
                             } elseif (is_array($plugin)) {
                                 // Array is returned if a plugin could be fetched from info cache
                                 $props = $plugin;
                                 #echo "Cached<br />\n";
                             } else {
                                 $props = false;
                                 #echo "Error<br />\n";
                             }
                             if (is_array($props)) {
                                 #echo "<pre>" . print_r($props, true) . "</pre>\n";
                                 if (version_compare($props['version'], $props['upgrade_version'], '<')) {
                                     $mailtext .= ' * ' . $class_data['name'] . " NEW VERSION: " . $props['upgrade_version'] . " - CURRENT VERSION: " . $props['version'] . "\n";
                                 }
                             } else {
                                 $mailtext .= " X ERROR: " . $class_data['true_name'] . "\n";
                             }
                         }
                     }
                     if (!empty($mailtext)) {
                         serendipity_sendMail($serendipity['blogMail'], 'Spartacus update report ' . $serendipity['baseURL'], $mailtext, $serendipity['blogMail']);
                         echo nl2br($mailtext);
                     }
                 } else {
                     $propbag->add('type', 'suboption');
                 }
                 break;
             case 'external_plugin':
                 if (!serendipity_db_bool($this->get_config('enable_remote'))) {
                     return false;
                 }
                 if ($eventData == $this->get_config('remote_url')) {
                     header('Content-Type: text/plain');
                     $avail = array();
                     $install = array();
                     $meth = array('event', 'sidebar');
                     $active = serendipity_plugin_api::get_installed_plugins();
                     $avail['event'] = $this->buildList($this->fetchOnline('event'), 'event');
                     $avail['sidebar'] = $this->buildList($this->fetchOnline('sidebar'), 'sidebar');
                     $install['event'] = serendipity_plugin_api::enum_plugin_classes(true);
                     $install['sidebar'] = serendipity_plugin_api::enum_plugin_classes(false);
                     foreach ($meth as $method) {
                         echo "LISTING: {$method}\n-------------------\n";
                         foreach ($install[$method] as $class_data) {
                             $pluginFile = serendipity_plugin_api::probePlugin($class_data['name'], $class_data['classname'], $class_data['pluginPath']);
                             $plugin = serendipity_plugin_api::getPluginInfo($pluginFile, $class_data, $method);
                             if (is_object($plugin)) {
                                 // Object is returned when a plugin could not be cached.
                                 $bag = new serendipity_property_bag();
                                 $plugin->introspect($bag);
                                 // If a foreign plugin is upgradable, keep the new version number.
                                 if (isset($avail[$method][$class_data['name']])) {
                                     $class_data['upgrade_version'] = $avail[$method][$class_data['name']]['upgrade_version'];
                                 }
                                 $props = serendipity_plugin_api::setPluginInfo($plugin, $pluginFile, $bag, $class_data, 'local', $avail[$method]);
                             } elseif (is_array($plugin)) {
                                 // Array is returned if a plugin could be fetched from info cache
                                 $props = $plugin;
                             } else {
                                 $props = false;
                             }
                             if (is_array($props)) {
                                 #print_r($props);
                                 if (version_compare($props['version'], $props['upgrade_version'], '<')) {
                                     echo "UPGRADE: " . $class_data['name'] . " -- " . $props['upgrade_version'] . "\n";
                                 } else {
                                     echo "OK: " . $class_data['name'] . " -- " . $props['version'] . "\n";
                                 }
                             } else {
                                 echo "ERROR: " . $class_data['true_name'] . "\n";
                             }
                         }
                     }
                 }
                 break;
             case 'backend_pluginlisting_header':
                 if (serendipity_db_bool($this->get_config('enable_plugins'))) {
                     echo '<div id="upgrade_notice" class="clearfix">';
                     echo '    <a id="upgrade_sidebar" class="button_link" href="?serendipity[adminModule]=plugins&amp;serendipity[adminAction]=addnew&amp;serendipity[only_group]=UPGRADE">' . PLUGIN_EVENT_SPARTACUS_CHECK_SIDEBAR . '</a>';
                     echo '    <a id="upgrade_event" class="button_link" href="?serendipity[adminModule]=plugins&amp;serendipity[adminAction]=addnew&amp;serendipity[only_group]=UPGRADE&amp;serendipity[type]=event">' . PLUGIN_EVENT_SPARTACUS_CHECK_EVENT . '</a> ';
                     echo '</div>';
                 }
                 break;
             case 'backend_templates_fetchlist':
                 if (serendipity_db_bool($this->get_config('enable_themes'))) {
                     $eventData = $this->buildTemplateList($this->fetchOnline('template', true), 'template');
                 }
                 break;
             case 'backend_templates_fetchtemplate':
                 if (serendipity_db_bool($this->get_config('enable_themes'))) {
                     if (!empty($eventData['GET']['spartacus_fetch'])) {
                         $this->download($this->fetchOnline('template', true), $eventData['GET']['theme'], 'templates');
                     }
                 }
                 break;
             case 'backend_plugins_fetchlist':
                 if (serendipity_db_bool($this->get_config('enable_plugins'))) {
                     $type = isset($serendipity['GET']['type']) && !empty($serendipity['GET']['type']) ? $serendipity['GET']['type'] : 'sidebar';
                     $eventData = array('pluginstack' => $this->buildList($this->fetchOnline($type), $type), 'errorstack' => array(), 'upgradeURI' => '&amp;serendipity[spartacus_upgrade]=true', 'baseURI' => '&amp;serendipity[spartacus_fetch]=' . $type);
                 }
                 break;
             case 'backend_plugins_fetchplugin':
                 if (serendipity_db_bool($this->get_config('enable_plugins'))) {
                     if (!empty($eventData['GET']['spartacus_fetch'])) {
                         $baseDir = $this->download($this->fetchOnline($eventData['GET']['spartacus_fetch'], true), $eventData['GET']['install_plugin']);
                         if ($baseDir === false) {
                             $eventData['install'] = false;
                         } elseif (!empty($baseDir)) {
                             $eventData['GET']['pluginPath'] = $baseDir;
                         } else {
                             $eventData['GET']['pluginPath'] = $eventData['GET']['install_plugin'];
                         }
                         if ($eventData['GET']['spartacus_upgrade']) {
                             $eventData['install'] = false;
                         }
                     }
                 }
                 break;
             case 'backend_directory_create':
                 if (serendipity_db_bool($this->get_config('use_ftp')) && !is_dir($eventData)) {
                     return $this->make_dir_via_ftp($eventData);
                 }
                 break;
             default:
                 return false;
         }
         return true;
     } else {
         return false;
     }
 }
 /**
  * Insert guestbook entry into database and send mail
  *
  * @param  int       $id
  * @param  string    $ip
  * @param  string    $name
  * @param  string    $url
  * @param  string    $email
  * @param  string    $body
  * @param  int       $app    approved
  * @param  int       $ts     timestamp
  * @param  boolean   $old    Insert/Replace
  * @return boolean
  */
 function insertEntriesDB($id = false, $ip = false, $name, $url, $email, $body, $app = false, $ts = false, $old = false)
 {
     global $serendipity;
     // make php to current unix timestamp to insert into db
     $ip = isset($ip) ? $ip : serendipity_db_escape_string($_SERVER['REMOTE_ADDR']);
     $app = isset($app) ? (int) $app : (serendipity_db_bool($this->get_config('showapp')) ? 0 : 1);
     $ts = isset($ts) ? $ts : time();
     $name = serendipity_db_escape_string(substr($name, 0, 29));
     $url = serendipity_db_escape_string(substr($url, 0, 99));
     $email = serendipity_db_escape_string(substr($email, 0, 99));
     $body = serendipity_db_escape_string($body);
     if ($old === false) {
         // normal setting
         $sql = sprintf("INSERT\n                    INTO %sguestbook ( ip, name, homepage, email, body, approved, timestamp )\n                    VALUES          ( '%s', '%s', '%s', '%s', '%s', %s,  %s)", $serendipity['dbPrefix'], $ip, $name, $url, $email, $body, $app, $ts);
     } else {
         // replace settings
         $sql = "REPLACE {$serendipity['dbPrefix']}guestbook SET id={$id}, ip='{$ip}', name='{$name}', homepage='{$url}', email='{$email}', body='{$body}', approved='{$app}', timestamp='{$ts}'";
     }
     $dbdone = serendipity_db_query($sql, true, 'both', true);
     if ($dbdone) {
         // if set, send an Email to the Admin $serendipity['email']
         if (!serendipity_db_bool($this->get_config('emailadmin'))) {
             return false;
         } elseif (!$this->get_config('targetmail') || $this->get_config('targetmail') != '') {
             $headers[] = 'X-SentBy: Serendipity Guestbook';
             $headers[] = 'X-Priority: 2';
             // prevent sent emails
             $headers[] = 'X-MSmail-Priority: high';
             // treated as junk mails
             $body = str_replace(array('\\r\\n', '\\n'), "\n", $body);
             // without search = single and replace = double quotes, this won't work!!!
             // does $serendipity['csuccess'] ever return to be moderate?
             if (serendipity_db_bool($this->get_config('showapp')) === false && ($app == 0 || $serendipity['csuccess'] == 'moderate')) {
                 $body = $body . sprintf(TEXT_EMAILMODERATE, $serendipity['moderate_reason']);
             }
             return @serendipity_sendMail($this->get_config('targetmail'), TEXT_EMAILSUBJECT, sprintf(TEXT_EMAILTEXT, $name, $body, TEXT_EMAILFOOTER), $email, $headers, $name);
         }
         return true;
     }
 }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                case 'backend_login_page':
                    // first LINK
                    if (!isset($_GET['forgotpassword']) && !isset($_GET['username']) && !isset($_POST['username'])) {
                        $eventData['footer'] = '
                        <table cellspacing="10" cellpadding="0" border="0" align="center">
                            <tr>
                                <td colspan="2" align="right"><a href="?forgotpassword=1">' . PLUGIN_EVENT_FORGOTPASSWORD_LOST_PASSWORD . '</a></td>
                            </tr>
                        </table>';
                        return true;
                        // first FORM
                    } elseif (!isset($_POST['username']) && !isset($_GET['uid'])) {
                        $eventData['footer'] = '
                        <form action="serendipity_admin.php" method="post">
                            <table cellspacing="10" cellpadding="0" border="0" align="center">
                                <tr>
                                    <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_ENTER_USERNAME . '</td>
                                </tr>

                                <tr>
                                    <td>' . USERNAME . '</td>
                                    <td><input class="input_textbox" type="text" name="username" /></td>
                                </tr>

                                <tr>
                                    <td colspan="2" align="right"><input type="submit" name="forgot" value="' . PLUGIN_EVENT_FORGOTPASSWORD_SEND_EMAIL . '" class="serendipityPrettyButton input_button" /></td>
                                </tr>
                            </table>
                        </form>';
                        return true;
                        // submitted FORM (send an email to user and show a simple page)
                    } elseif (!isset($_POST['uid']) && isset($_POST['username'])) {
                        $q = 'SELECT email, authorid FROM ' . $serendipity['dbPrefix'] . 'authors where username = \'' . serendipity_db_escape_string($_POST['username']) . '\'';
                        $sql = serendipity_db_query($q);
                        if (!is_array($sql) || count($sql) < 1) {
                            $eventData['footer'] = '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . PLUGIN_EVENT_FORGOTPASSWORD_USER_NOT_EXIST . '</div>';
                            return true;
                        }
                        if ($sql && is_array($sql)) {
                            if (empty($sql[0]['email'])) {
                                $eventData['footer'] = '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . $this->get_config('nomailinfo') . '</div>';
                                if ($this->get_config('nomailadd') != '') {
                                    $sent = serendipity_sendMail($this->get_config('nomailadd'), PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_SUBJECT, sprintf($this->get_config('nomailtxt'), $_POST['username']), NULL);
                                }
                                return true;
                            }
                            $res = $sql[0];
                            $email = $res['email'];
                            $authorid = $res['authorid'];
                            $md5 = md5(uniqid(time()));
                            $q = 'INSERT INTO ' . $serendipity['dbPrefix'] . 'forgotpassword VALUES (\'' . $md5 . '\', \'' . $authorid . '\')';
                            $sql = serendipity_db_query($q);
                            if (!$sql) {
                                $eventData['footer'] = '
                                <table cellspacing="10" cellpadding="0" border="0" align="center">
                                    <tr>
                                        <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_DB_ERROR . '</td>
                                    </tr>
                                </table>';
                                return true;
                            }
                            $sent = serendipity_sendMail($email, PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_SUBJECT, PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_BODY . $serendipity['baseURL'] . 'serendipity_admin.php?username='******'&uid=' . $md5, NULL);
                            if ($sent) {
                                $eventData['footer'] = '
                                <table cellspacing="10" cellpadding="0" border="0" align="center">
                                    <tr>
                                        <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_SENT . '</td>
                                    </tr>
                                </table>';
                            } else {
                                $eventData['footer'] = '
                                <table cellspacing="10" cellpadding="0" border="0" align="center">
                                    <tr>
                                        <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_CANNOT_SEND . '</td>
                                    </tr>
                                </table>';
                            }
                            return true;
                        } else {
                            $eventData['footer'] = '
                            <table cellspacing="10" cellpadding="0" border="0" align="center">
                                <tr>
                                    <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_DB_ERROR . '</td>
                                </tr>
                            </table>';
                            return true;
                        }
                        // clicked link in user email
                    } elseif (isset($_GET['uid']) && isset($_GET['username']) && !isset($_POST['password'])) {
                        $eventData['footer'] = '
                        <form action="serendipity_admin.php" method="post">
                            <table cellspacing="10" cellpadding="0" border="0" align="center">
                                <tr>
                                    <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_ENTER_PASSWORD . '</td>
                                </tr>

                                <tr>
                                    <td>' . PASSWORD . '</td>
                                    <td><input class="input_textbox" type="password" name="password" />
                                        <input type="hidden" name="username" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($_GET['username']) : htmlspecialchars($_GET['username'], ENT_COMPAT, LANG_CHARSET)) . '" />
                                        <input type="hidden" name="uid" value="' . (function_exists('serendipity_specialchars') ? serendipity_specialchars($_GET['uid']) : htmlspecialchars($_GET['uid'], ENT_COMPAT, LANG_CHARSET)) . '" /></td>
                                </tr>

                                <tr>
                                    <td colspan="2" align="right"><input type="submit" name="forgot" value="' . PLUGIN_EVENT_FORGOTPASSWORD_CHANGE_PASSWORD . '" class="serendipityPrettyButton input_button" /></td>
                                </tr>
                            </table>
                        </form>';
                        return true;
                        // changed password page
                    } elseif (isset($_POST['uid']) && isset($_POST['username']) && isset($_POST['password'])) {
                        $q = 'SELECT * FROM ' . $serendipity['dbPrefix'] . 'forgotpassword where authorid = \'' . serendipity_db_escape_string($_POST['username']) . '\' and uid = \'' . serendipity_db_escape_string($_POST['uid']) . '\'';
                        $sql = serendipity_db_query($q);
                        if ($sql && is_array($sql)) {
                            $res = $sql[0];
                            $authorid = $res['authorid'];
                            if (function_exists('serendipity_hash')) {
                                $password = serendipity_hash($_POST['password']);
                                $q = 'UPDATE ' . $serendipity['dbPrefix'] . 'authors SET hashtype=1, password=\'' . $password . '\' where authorid = \'' . serendipity_db_escape_string($_POST['username']) . '\'';
                            } else {
                                $password = md5($_POST['password']);
                                $q = 'UPDATE ' . $serendipity['dbPrefix'] . 'authors SET password=\'' . $password . '\' where authorid = \'' . serendipity_db_escape_string($_POST['username']) . '\'';
                            }
                            $sql = serendipity_db_query($q);
                            if (!$sql) {
                                $eventData['footer'] = '
                                <table cellspacing="10" cellpadding="0" border="0" align="center">
                                    <tr>
                                        <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_DB_ERROR . '</td>
                                    </tr>
                                </table>';
                                return true;
                            }
                            $q = 'DELETE FROM ' . $serendipity['dbPrefix'] . 'forgotpassword where authorid = \'' . serendipity_db_escape_string($_POST['username']) . '\'';
                            $sql = serendipity_db_query($q);
                            $eventData['footer'] = '
                            <table cellspacing="10" cellpadding="0" border="0" align="center">
                                <tr>
                                    <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_PASSWORD_CHANGED . '</td>
                                </tr>
                            </table>';
                            return true;
                        } else {
                            $eventData['footer'] = '
                            <table cellspacing="10" cellpadding="0" border="0" align="center">
                                <tr>
                                    <td colspan="2" align="right">' . PLUGIN_EVENT_FORGOTPASSWORD_EMAIL_DB_ERROR . '</td>
                                </tr>
                            </table>';
                            return true;
                        }
                    }
                    break;
                default:
                    return false;
            }
        } else {
            return false;
        }
        return false;
    }
 function event_hook($event, &$bag, &$eventData, $addData = null)
 {
     global $serendipity;
     $hooks =& $bag->get('event_hooks');
     if (isset($hooks[$event])) {
         if ($timeout === null) {
             $timeout = $this->get_config('timeout', '300');
         }
         if ($path === null) {
             $path = $this->get_config('path', '');
         }
         if (!empty($path) && $path != 'default' && $path != 'none' && $path != 'empty') {
             $path_defined = true;
         } else {
             $path_defined = false;
         }
         if ($mail == null) {
             $mail = $this->get_config('mail', false);
         }
         switch ($event) {
             case 'external_plugin':
                 switch ($eventData) {
                     case 'commentedit.js':
                         header('Content-Type: text/javascript');
                         echo file_get_contents(dirname(__FILE__) . '/serendipity_event_commentedit.js');
                         break;
                     case 'jquery.jeditable.js':
                         header('Content-Type: text/javascript');
                         echo file_get_contents(dirname(__FILE__) . '/jquery.jeditable.js');
                         break;
                     case 'commentedit':
                         global $serendipity;
                         //the js sent us the comment and an id json-encrypted,
                         //so they are named
                         $comment = $_REQUEST['comment'];
                         $comment_id = $_REQUEST['cid'];
                         $entry_id = $_REQUEST['entry_id'];
                         //Break when comment_id !=> session
                         if ($this->get_cached_commentid($timeout) == $comment_id) {
                             $this->editComment($comment_id, $comment, $entry_id);
                             $data = array('comment' => $comment);
                             serendipity_plugin_api::hook_event('frontend_display', $data);
                             //send mail with edit-notification to blogowner, only if normal notification is enabled and config, too
                             if ($serendipity['mail_comments'] == 1 && $mail) {
                                 serendipity_sendMail($serendipity['email'], 'Comment ' . $comment_id . ' edited', 'New comment: ' . $comment, $serendipity['blogMail']);
                             }
                             echo $data['comment'];
                         }
                         break;
                     case 'commentedit_load':
                         //load a comment from the db
                         $comment = $this->getComment($_REQUEST['cid'], $_REQUEST['entry_id']);
                         echo $comment[0]['body'];
                         break;
                     case 'commentedit_time':
                         //echo the remaining time
                         if ($_SESSION['comment_made_time'] > time() - $timeout) {
                             echo $_SESSION['comment_made_time'] + $timeout - time();
                         } else {
                             echo 0;
                         }
                         break;
                     case 'commentedit_language':
                         $language = array('editlink' => EDIT, 'edittooltip' => PLUGIN_EVENT_COMMENTEDIT_EDITTOOLTIP, 'edittimer' => PLUGIN_EVENT_COMMENTEDIT_EDITTIMER, 'editsubmit' => SAVE, 'editcancel' => ABORT_NOW);
                         //For json to work, the strings has to be utf8-encoded
                         echo json_encode(array_map(utf8_encode, $language));
                         break;
                 }
                 return true;
                 break;
             case 'frontend_saveComment_finish':
                 //save corresponding sessionid because we later fetch a comment
                 //and check if the current session_id() belongs to the comment_cid
                 $this->cache_commentid($addData['comment_cid']);
                 return true;
                 break;
             case 'fetchcomments':
                 $postBase = false;
                 $cids = array();
                 foreach ($eventData as $comment) {
                     if ($this->get_cached_commentid($timeout) == $comment['id']) {
                         //we now know that the comment is from the
                         //user and created within the last minutes,
                         //so add comment_id
                         $cids[] = $comment['id'];
                         $postBase = true;
                     }
                 }
                 if ($postBase) {
                     //cebase is used for the POST of the edited
                     //comment to the external_plugin-call
                     echo '<script>var cebase = "' . $serendipity['baseURL'] . 'index.php?/plugin/";</script>';
                     foreach ($cids as $cid) {
                         //add edit-ability:
                         echo '<script>makeEditable(' . $comment['id'] . ',' . $eventData['0']['entry_id'] . ') </script>' . "\n";
                     }
                 }
                 return true;
                 break;
             case 'frontend_header':
                 if ($path_defined) {
                     echo '<script type="text/javascript" src="' . $path . 'jquery.jeditable.js"></script>' . "\n";
                     echo '<script type="text/javascript" src="' . $path . 'serendipity_event_commentedit.js"></script>' . "\n";
                 } else {
                     echo '<script type="text/javascript" src="' . $serendipity['baseURL'] . 'index.php?/plugin/jquery.jeditable.js"></script>' . "\n";
                     echo '<script type="text/javascript" src="' . $serendipity['baseURL'] . 'index.php?/plugin/commentedit.js"></script>' . "\n";
                 }
             default:
                 return false;
         }
     } else {
         return false;
     }
 }
    function event_hook($event, &$bag, &$eventData, $addData = null)
    {
        global $serendipity;
        $hooks =& $bag->get('event_hooks');
        if (isset($hooks[$event])) {
            switch ($event) {
                case 'external_plugin':
                    $events = explode('_', $eventData);
                    if ($events[0] != 'copycop') {
                        return false;
                    }
                    // TODO: Call CopyCop here somehow.
                    break;
                case 'genpage':
                    $args = implode('/', serendipity_getUriArguments($eventData, true));
                    if ($serendipity['rewrite'] != 'none') {
                        $nice_url = $serendipity['serendipityHTTPPath'] . $args;
                    } else {
                        $nice_url = $serendipity['serendipityHTTPPath'] . $serendipity['indexFile'] . '?/' . $args;
                    }
                    if (empty($serendipity['GET']['subpage'])) {
                        $serendipity['GET']['subpage'] = $nice_url;
                    }
                    break;
                case 'entry_display':
                    if ($this->selected()) {
                        if (is_array($eventData)) {
                            $eventData['clean_page'] = true;
                            // This is important to not display an entry list!
                        } else {
                            $eventData = array('clean_page' => true);
                        }
                    }
                    return true;
                    break;
                case 'entries_header':
                    $this->show();
                    return true;
                    break;
                case 'backend_publish':
                    if (!$eventData['id']) {
                        return false;
                    }
                    $res = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}suggestmails WHERE entry_id = " . (int) $eventData['id'], true, 'assoc');
                    if (!is_array($res)) {
                        $res = array();
                    }
                    if (!$res['id']) {
                        return false;
                    }
                    //  CUSTOMIZE
                    serendipity_sendMail($res['email'], PLUGIN_SUGGEST_TITLE, PLUGIN_SUGGEST_PUBLISHED, $serendipity['blogMail'], null, $serendipity['blog']);
                    echo PLUGIN_SUGGEST_INFORM . "<br />\n";
                    serendipity_db_query("REPLACE INTO {$serendipity['dbPrefix']}entryproperties\n                                                       (entryid, property, value)\n                                                VALUES (" . (int) $eventData['id'] . ", 'ep_suggest_name', '" . serendipity_db_escape_string($res['name']) . "')");
                    break;
                case 'backend_display':
                    if (!$eventData['id']) {
                        return false;
                    }
                    $res = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}suggestmails WHERE entry_id = " . (int) $eventData['id'], true, 'assoc');
                    if (!is_array($res)) {
                        $res = array();
                        ?>
                    <fieldset style="margin: 5px">
                        <legend><?php 
                        echo PLUGIN_SUGGEST_TITLE;
                        ?>
</legend>
                        <div><?php 
                        echo PLUGIN_SUGGEST_INTERNAL;
                        ?>
</div>
                    </fieldset>

<?php 
                    } else {
                        //  CUSTOMIZE
                        ?>
                    <fieldset style="margin: 5px">
                        <legend><?php 
                        echo PLUGIN_SUGGEST_TITLE;
                        ?>
</legend>
                        <div>
                            <?php 
                        printf(PLUGIN_SUGGEST_META, function_exists('serendipity_specialchars') ? serendipity_specialchars($res['name']) : htmlspecialchars($res['name'], ENT_COMPAT, LANG_CHARSET), strftime('%d.%m.%Y %H:%M', $res['submitted']), function_exists('serendipity_specialchars') ? serendipity_specialchars($res['ip']) : htmlspecialchars($res['ip'], ENT_COMPAT, LANG_CHARSET), function_exists('serendipity_specialchars') ? serendipity_specialchars($res['email']) : htmlspecialchars($res['email'], ENT_COMPAT, LANG_CHARSET));
                        ?>
                        </div>
                    </fieldset>
<?php 
                    }
                    return true;
                    break;
                default:
                    return false;
                    break;
            }
        } else {
            return false;
        }
    }
 /**
  * Write the iLog file and/or send an iCal request log notice to the admin via email
  *
  * @access 
  * @param  string   Admins email address to send the mail to
  * @param  string   The name of the sender - unknown
  * @param  string   If REQUEST via email, email address to send the mail to
  * @param  int      The ID request that has been sent
  * @param  string   The year-month ARRAY request that has been sent
  * @param  string   The title which type of request the user ordered
  * @param  string   The request type which has been sent
  * @param  boolean  If true function is used to send email, else just log to file
  * @return boolean  Return success of sending the mails
  **/
 function send_ical_log_email($to, $fromName, $fromEmail, $id, $monthdate, $title, $type, $smail = true)
 {
     global $serendipity;
     if (empty($fromName)) {
         $fromName = ANONYMOUS;
     }
     if ($monthdate > 0) {
         list($y, $m) = explode('-', $monthdate);
         $getid = isset($id) && $id > 0 ? '&calendar[ev]=' . $id : '';
         // frontend request - uri to frontend
         $entryURI = 'http://' . $_SERVER['HTTP_HOST'] . $this->fetchPluginUri() . ($serendipity['rewrite'] == 'rewrite' ? '?' : '&') . 'calendar[cm]=' . $m . '&calendar[cy]=' . $y . $getid;
     } else {
         // admin panel request - uri to ical backend
         $entryURI = 'http://' . $_SERVER['HTTP_HOST'] . $serendipity['serendipityHTTPPath'] . 'serendipity_admin.php?serendipity[adminModule]=event_display&serendipity[adminAction]=eventcal&serendipity[eventcalcategory]=adevplad&serendipity[eventcaldbclean]=dbicalall';
     }
     // set the log vars
     $info = 'iCal REQUEST via ' . $type;
     $sub = date('Y-m-d H:i:s');
     $sub2 = 'serendipity_event_cal plugin // iCal request LOG';
     $sid = isset($id) && $id > 0 ? $id : 'none';
     $monthdate = $monthdate > 0 ? $monthdate : 'app-all';
     $fromEmail = $fromEmail ? $fromEmail : 'none';
     // write to ical.log file
     $logstring = "{$sub}, ID={$sid}, MONTH={$monthdate}, {$info}, IP=" . $_SERVER['REMOTE_ADDR'] . ", EMAIL={$fromEmail}, PATH={$entryURI}\n";
     $fullpath = $serendipity['serendipityPath'] . 'templates_c/eventcal/ical.log';
     $filename = 'ical.log';
     $filepath = 'templates_c/eventcal/';
     $directory = "eventcal";
     if (!is_dir('templates_c/' . $directory)) {
         @mkdir('templates_c/' . $directory, 0777);
     }
     if (false === ($wicl = $this->backend_file_write($logstring, $fullpath, $filename, $filepath, 'a'))) {
         $nolog = true;
     }
     if ($nolog === true) {
         $serendipity['eventcal']['ilogerror'] = true;
     }
     $subject = ' // ' . $sub . ' // ' . $sub2 . ' // ' . $title;
     $text = "\n" . USER . ' ' . REQUEST_DATE . ': ' . $sub . ', ' . $serendipity['blogTitle'] . ', ' . $title . "\n" . "\n" . USER . ' ' . ARCHIVE_LINK . ': ' . '<a href="' . $entryURI . '">link</a>' . "\n" . USER . ' ' . INFO . ': ' . $info . "\n" . "\n" . USER . ' ' . IP_ADDRESS . ': ' . $_SERVER['REMOTE_ADDR'] . "\n" . USER . ' ' . TO_EMAIL . ': ' . $fromEmail . "\n" . USER . ' ' . ICAL_ID . ': ' . $sid . "\n" . USER . ' ' . YEAR_MONTH . ': ' . $monthdate . "\n" . "\n" . REQUEST_DATE . ': ' . $sub;
     $text = $nolog === true ? $text . "\n" . PLUGIN_EVENTCAL_ADMIN_LOG_ERROR : $text;
     $text = $text . "\n" . '----' . "\n" . 'brought to you by S9y.org serendipity_event_cal plugin v.' . $serendipity['plugin_eventcal_version'];
     if ($smail === true || $nolog === true) {
         return serendipity_sendMail($to, $subject, $text, $fromEmail, null, $fromName);
     } else {
         return false;
     }
 }