Example #1
0
    protected function outputHTML()
    {
        $user = UserRepository::getUserByID($this->message['senderid']);
        ?>

        <div class="container">

            <div class="panel panel-info" id="comments">
                <div class="panel-heading">
                    <h3 class="panel-title">Message</h3>
                </div>

                <div class="panel-body">
                    <p>From: <?php 
        echo $user['username'];
        ?>
</p>
                    <p>Content: <?php 
        echo parseText($this->message['content']);
        ?>
</p>
                    <p><a href="<?php 
        echo \route\Route::get("sendMessage")->generate(array("id" => $user['userid']));
        ?>
" class="btn btn-info">Reply</a></p>
                </div>
            </div>
        </div>

        <?php 
    }
Example #2
0
 function parse($args, $page)
 {
     global $pagestore, $ParseEngine, $ParseObject;
     static $visited_array = array();
     static $visited_count = 0;
     if (!validate_page($args)) {
         return '[[Transclude ' . $args . ']]';
     }
     $visited_array[$visited_count++] = $ParseObject;
     for ($i = 0; $i < $visited_count; $i++) {
         if ($visited_array[$i] == $args) {
             $visited_count--;
             return '[[Transclude ' . $args . ']]';
         }
     }
     $pg = $pagestore->page($args);
     $pg->read();
     if (!$pg->exists) {
         $visited_count--;
         return '[[Transclude ' . $args . ']]';
     }
     $result = parseText($pg->text, $ParseEngine, $args);
     $visited_count--;
     return $result;
 }
 function get_content(&$arguments, $properties)
 {
     if (!is_readable(PHPGW_SERVER_ROOT . '/wiki') || !@$GLOBALS['phpgw_info']['user']['apps']['wiki']) {
         return lang('You have no rights to view wiki content or the wiki is not installed at all !!!');
     }
     $wikipage = empty($_GET[$this->wikipage_param]) ? empty($arguments['startpage']) ? $GLOBALS['HomePage'] : $arguments['startpage'] : stripslashes(urldecode($_GET['wikipage']));
     $parts = explode(':', $wikipage);
     if (count($parts) > 1) {
         $lang = array_pop($parts);
         if (strlen($lang) == 2 || strlen($lang) == 5 && $lang[2] == '-') {
             $wikipage = implode(':', $parts);
         } else {
             $lang = '';
         }
     }
     $pg = $GLOBALS['pagestore']->page($wikipage, $lang);
     $pg->read();
     // we need to set ViewBase to the name of the actual page, to get wiki to stay inside this page
     global $ViewBase;
     $ViewBase = $_SERVER['PHP_SELF'] . '?';
     foreach ($_GET as $name => $val) {
         if ($name != $this->wikipage_param) {
             $ViewBase .= $name . '=' . urlencode($val) . '&';
         }
     }
     $ViewBase .= $this->wikipage_param . '=';
     return parseText($pg->text, $GLOBALS['ParseEngine'], $wikipage);
 }
Example #4
0
function niceVarDump($obj, $ident = 0)
{
    $data = '';
    $data .= str_repeat(' ', $ident);
    $original_ident = $ident;
    $toClose = false;
    switch (gettype($obj)) {
        case 'object':
            $vars = (array) $obj;
            $data .= gettype($obj) . ' (' . get_class($obj) . ') (' . count($vars) . ") {\n";
            $ident += 2;
            foreach ($vars as $key => $var) {
                $type = '';
                $k = bin2hex($key);
                if (strpos($k, '002a00') === 0) {
                    $k = str_replace('002a00', '', $k);
                    $type = ':protected';
                } elseif (strpos($k, bin2hex("" . get_class($obj) . "")) === 0) {
                    $k = str_replace(bin2hex("" . get_class($obj) . ""), '', $k);
                    $type = ':private';
                }
                $k = hex2bin($k);
                if (is_subclass_of($obj, 'ProtobufMessage') && $k == 'values') {
                    $r = new ReflectionClass($obj);
                    $constants = $r->getConstants();
                    $newVar = [];
                    foreach ($constants as $ckey => $cval) {
                        if (substr($ckey, 0, 3) != 'PB_') {
                            $newVar[$ckey] = $var[$cval];
                        }
                    }
                    $var = $newVar;
                }
                $data .= str_repeat(' ', $ident) . "[{$k}{$type}]=>\n" . niceVarDump($var, $ident) . "\n";
            }
            $toClose = true;
            break;
        case 'array':
            $data .= 'array (' . count($obj) . ") {\n";
            $ident += 2;
            foreach ($obj as $key => $val) {
                $data .= str_repeat(' ', $ident) . '[' . (is_int($key) ? $key : "\"{$key}\"") . "]=>\n" . niceVarDump($val, $ident) . "\n";
            }
            $toClose = true;
            break;
        case 'string':
            $data .= 'string "' . parseText($obj) . "\"\n";
            break;
        case 'NULL':
            $data .= gettype($obj);
            break;
        default:
            $data .= gettype($obj) . '(' . strval($obj) . ")\n";
            break;
    }
    if ($toClose) {
        $data .= str_repeat(' ', $original_ident) . "}\n";
    }
    return $data;
}
Example #5
0
function action_view()
{
    global $page, $pagestore, $ParseEngine, $version, $UserName;
    global $document, $redirect_from, $view_source;
    $pg = $pagestore->page($page);
    if (file_exists("modules/" . $page . ".php")) {
        require_once "modules/" . $page . ".php";
        if (function_exists($page . "_content")) {
            eval("\$pg->text=" . $page . "_content();");
        }
        $pg->mutable = 0;
    } else {
        if ($version != '') {
            $pg->version = $version;
        }
        $pg->read();
    }
    $document = $pg->text;
    gen_headers($pg->time);
    if ($view_source) {
        $html = wordwrap($pg->text, 80, "\n", true);
        $html = '<pre>' . htmlspecialchars($html) . '</pre>';
    } else {
        $html = parseText($pg->text, $ParseEngine, $page);
    }
    template_view(array('page' => $page, 'page_length' => strlen($pg->text), 'html' => $html, 'view_source' => $view_source, 'editable' => $UserName && $pg->mutable, 'timestamp' => $pg->time, 'archive' => $version != '', 'version' => $pg->version, 'edituser' => $pg->username, 'redirect_from' => $redirect_from, 'editver' => $UserName && $pg->mutable ? $version == '' ? 0 : $version : -1));
}
Example #6
0
function action_conflict()
{
    global $document, $merge, $page, $pagestore, $ParseEngine;
    $pg = $pagestore->page($page);
    $pg->read();
    template_conflict(array('page' => $page, 'text' => $pg->text, 'html' => parseText($pg->text, $ParseEngine, $page), 'usertext' => $document, 'merge' => $merge, 'timestamp' => $pg->time, 'nextver' => $pg->version + 1));
}
function add_to_category($page, $catlist)
{
    global $pagestore, $Entity, $UserName, $REMOTE_ADDR, $FlgChr;
    // Parse the category list for category names.
    $parsed = parseText($catlist, array('parse_wikiname', 'parse_freelink'), '');
    $pagenames = array();
    preg_replace('/' . $FlgChr . '(\\d+)' . $FlgChr . '/e', '$pagenames[]=$Entity[\\1][1]', $parsed);
    if (validate_page($page) == 2) {
        $page = '((' . $page . '))';
    }
    // Add it to each category.
    foreach ($pagenames as $category) {
        $pg = $pagestore->page($category);
        $pg->read();
        if ($pg->exists) {
            if (preg_match('/\\[\\[!.*\\]\\]/', $pg->text)) {
                if (!preg_match("/\\[\\[!.*{$page}.*\\]\\]/", $pg->text)) {
                    $pg->text = preg_replace('/(\\[\\[!.*)\\]\\]/', "\\1 {$page}]]", $pg->text);
                } else {
                    continue;
                }
            } else {
                $pg->text = $pg->text . "\n[[! {$page}]]\n";
            }
            $pg->text = str_replace("\\", "\\\\", $pg->text);
            $pg->text = str_replace("'", "\\'", $pg->text);
            $pg->version++;
            $pg->comment = '';
            $pg->hostname = gethostbyaddr($REMOTE_ADDR);
            $pg->username = $UserName;
            $pg->write();
        }
    }
}
Example #8
0
function parseFile($path, $baseUrl, $docID)
{
    echo "  parse file  ";
    $content = file_get_contents($path, true);
    $title = getTitle($content);
    deleteFacts($title);
    $GLOBALS["paragraphs"] = array();
    $contentParse = $content;
    while ($contentParse != null) {
        $contentParse = parseText($contentParse);
    }
    echo "got paragraphs,  ";
    $paragraphs = $GLOBALS["paragraphs"];
    $factsExist = count($paragraphs) > 0;
    logSubject($title, $factsExist);
    foreach ($paragraphs as $text) {
        logFact($text, $title, $docID);
    }
    echo "logged facts";
    /*$GLOBALS["urls"] = array();
    	$contentParse = $content;
    	while($contentParse != null) {
    		$contentParse = parseURL($contentParse, $baseUrl);
    	}/*/
    //logURLs($GLOBALS["urls"]);
    //echo "<pre>"; print_r($GLOBALS["urls"]); echo "</pre>";
}
Example #9
0
function action_preview()
{
    global $ParseEngine, $archive;
    global $page, $document, $nextver, $pagestore;
    $document = str_replace("\r", "", $document);
    $pg = $pagestore->page($page);
    $pg->read();
    template_preview(array('page' => $page, 'text' => $document, 'html' => parseText($document, $ParseEngine, $page), 'timestamp' => $pg->time, 'nextver' => $nextver, 'archive' => $archive));
}
Example #10
0
function action_diff()
{
    global $pagestore, $page, $ver1, $ver2, $ParseEngine;
    $p1 = $pagestore->page($page);
    $p1->version = $ver1;
    $p2 = $pagestore->page($page);
    $p2->version = $ver2;
    $diff = diff_compute($p1->read(), $p2->read());
    template_diff(array('page' => $p2->as_array(), 'diff_html' => diff_parse($diff), 'html' => parseText($p2->text, $ParseEngine, $page), 'editable' => $p2->acl_check(), 'timestamp' => $p2->time));
}
Example #11
0
function action_diff()
{
    global $page, $pagestore, $ParseEngine, $UserName, $ver1, $ver2;
    $p1 = $pagestore->page($page);
    $p1->version = $ver1;
    $p2 = $pagestore->page($page);
    $p2->version = $ver2;
    $diff = diff_compute($p1->read(), $p2->read());
    template_diff(array('page' => $page, 'diff_html' => diff_parse($diff), 'html' => parseText($p2->text, $ParseEngine, $page), 'editable' => $p2->mutable, 'timestamp' => $p2->time, 'editver' => $UserName && $p2->mutable ? 0 : -1));
}
Example #12
0
function action_tablecsv()
{
    global $page, $pagestore, $tablenum;
    $pg = $pagestore->page($page);
    $pg->read();
    $parse_engine = array('parse_htmlpre', 'parse_nowiki', 'parse_tablecsv');
    $csv = parseText($pg->text, $parse_engine, $page);
    header('Content-Type: text/csv');
    header('Content-Disposition: filename="' . $page . '_' . $tablenum . '.csv"');
    print $csv;
}
Example #13
0
function action_view()
{
    global $page, $pagestore, $ParseEngine, $version;
    $pg = $pagestore->page($page);
    if ($version != '') {
        $pg->version = $version;
    }
    $pg->read();
    gen_headers($pg->time);
    template_view(array('page' => $pg->as_array(), 'title' => $pg->title, 'html' => parseText($pg->text, $ParseEngine, $page), 'editable' => $pg->acl_check(), 'timestamp' => $pg->time, 'archive' => $version != '', 'version' => $pg->version));
}
Example #14
0
function text_to_export($input)
{
    $emailuser = parseText($input);
    $validuser = $emailuser['valid_email'];
    $handle = fopen("export/valid_emails.txt", "w");
    foreach ($validuser as $value) {
        $content .= "{$value}\n";
    }
    fwrite($handle, $content);
    fclose($handle);
}
Example #15
0
 function parse($args, $page)
 {
     global $pagestore, $MinEntries, $DayLimit, $full, $page, $Entity;
     global $FlgChr, $UserName, $UseHotPages;
     list($args, $ignoreRegExp) = explode(' ', $args, 2);
     $text = '';
     if (strstr($args, '*')) {
         $list = $pagestore->allpages();
     } else {
         if (strstr($args, '?')) {
             $list = $pagestore->newpages();
         } else {
             if (strstr($args, '~')) {
                 $list = $pagestore->emptypages();
             } else {
                 $parsed = parseText($args, array('parse_wikiname', 'parse_freelink'), '');
                 $pagenames = array();
                 preg_replace('/' . $FlgChr . '(\\d+)' . $FlgChr . '/e', '$pagenames[]=$Entity[\\1][1]', $parsed);
                 $list = $pagestore->givenpages($pagenames);
             }
         }
     }
     if (count($list) == 0) {
         return '';
     }
     usort($list, 'catSort');
     if ($UseHotPages) {
         $hotPagesList = $pagestore->getHotPages();
     } else {
         $hotPagesList = array();
     }
     $newPages = $pagestore->getNewPages();
     $now = time();
     for ($i = 0; $i < count($list); $i++) {
         if ($ignoreRegExp) {
             if (@preg_match($ignoreRegExp, $list[$i][1])) {
                 continue;
             }
         }
         if ($DayLimit && $i >= $MinEntries && !$full && $now - $list[$i][0] > $DayLimit * 24 * 60 * 60) {
             break;
         }
         $text = $text . html_category($list[$i][0], $list[$i][1], $list[$i][2], $list[$i][3], $list[$i][5], $list[$i][7], $hotPagesList, $newPages);
         // Do not put a newline on the last one.
         if ($i < count($list) - 1) {
             $text = $text . html_newline();
         }
     }
     if ($i < count($list)) {
         $text = $text . html_fulllist($page, count($list));
     }
     return $text;
 }
Example #16
0
function action_save()
{
    global $pagestore, $comment, $categories, $archive;
    global $Save, $page, $document, $nextver, $REMOTE_ADDR;
    global $MaxPostLen, $UserName, $SaveMacroEngine;
    if (empty($Save)) {
        include 'action/preview.php';
        action_preview();
        return;
    }
    $pagestore->lock();
    // Ensure atomicity.
    $pg = $pagestore->page($page);
    $pg->read();
    if (!$pg->mutable) {
        die(ACTION_ErrorPageLocked);
    }
    if ($pg->exists() && $pg->version >= $nextver && $pg->hostname != gethostbyaddr($REMOTE_ADDR) && !$archive) {
        $pagestore->unlock();
        include 'action/conflict.php';
        action_conflict();
        return;
    }
    // Silently trim string to $MaxPostLen chars.
    $document = substr($document, 0, $MaxPostLen);
    $document = str_replace("\r", "", $document);
    $esc_doc = str_replace("\\", "\\\\", $document);
    $esc_doc = str_replace("'", "\\'", $esc_doc);
    $comment = str_replace("\\", "\\\\", $comment);
    $comment = str_replace("'", "\\'", $comment);
    $pg->text = $esc_doc;
    $pg->hostname = gethostbyaddr($REMOTE_ADDR);
    $pg->username = $UserName;
    $pg->comment = $comment;
    if ($pg->exists) {
        $pg->version++;
    } else {
        $pg->version = 1;
    }
    $pg->write();
    if (!empty($categories)) {
        //   a category or categories.
        add_to_category($page, $categories);
    }
    template_save(array('page' => $page, 'text' => $document));
    // Process save macros (e.g., to define interwiki entries).
    parseText($document, $SaveMacroEngine, $page);
    $pagestore->unlock();
    // End "transaction".
}
Example #17
0
function parse_define_links($text)
{
    global $pagestore, $page, $ParseEngine, $Entity, $ParseObject;
    static $called = 0;
    $macros_index = -1;
    $transclude_index = -1;
    $elements_index = -1;
    for ($i = 0; $i < count($ParseEngine); $i++) {
        if ($ParseEngine[$i] == 'parse_macros') {
            $macros_index = $i;
        }
        if ($ParseEngine[$i] == 'parse_transclude') {
            $transclude_index = $i;
        }
        if ($ParseEngine[$i] == 'parse_elements') {
            $elements_index = $i;
        }
    }
    if ($macros_index != -1) {
        $ParseEngine[$macros_index] = 'parse_noop';
    }
    if ($transclude_index != -1) {
        $ParseEngine[$transclude_index] = 'parse_noop';
    }
    if ($elements_index != -1) {
        $ParseEngine[$elements_index] = 'parse_noop';
    }
    if (!$called) {
        $pagestore->clear_link($page);
        $called = 1;
    }
    $j = count($Entity);
    parseText($text, $ParseEngine, $ParseObject);
    for (; $j < count($Entity); $j++) {
        if ($Entity[$j][0] == 'ref') {
            $pagestore->new_link($page, $Entity[$j][1]);
        }
    }
    if ($macros_index != -1) {
        $ParseEngine[$macros_index] = 'parse_macros';
    }
    if ($transclude_index != -1) {
        $ParseEngine[$transclude_index] = 'parse_transclude';
    }
    if ($elements_index != -1) {
        $ParseEngine[$elements_index] = 'parse_elements';
    }
    return $text;
}
Example #18
0
function action_preview()
{
    global $archive, $diff_mode, $document, $minoredit, $nextver, $page;
    global $pagefrom, $pagestore, $ParseEngine, $section, $template, $text_after;
    global $text_before;
    $document = str_replace("\r", "", $document);
    $text_before = str_replace("\r", "", $text_before);
    $text_after = str_replace("\r", "", $text_after);
    $pg = $pagestore->page($page);
    $pg->read();
    // computes the diff of the current changes
    $body1_pg = $pagestore->page($page);
    $body1_pg->version = $nextver - 1;
    $body1 = $body1_pg->read();
    $body2 = $document;
    if ($section) {
        $body2 = $text_before . "\n\n" . trim($document) . "\n\n" . $text_after;
    }
    $diff = do_diff($body1, $body2);
    template_preview(array('page' => $page, 'pagefrom' => $pagefrom, 'text' => $document, 'section' => $section, 'text_before' => $text_before, 'text_after' => $text_after, 'html' => parseText($document, $ParseEngine, $page), 'diff' => $diff, 'diff_mode' => $diff_mode, 'timestamp' => $pg->time, 'nextver' => $nextver, 'archive' => $archive, 'minoredit' => $minoredit, 'template' => $template, 'edituser' => $pg->username));
}
Example #19
0
 public function postTweetComment()
 {
     checkUnauthorizedAccess();
     $id = getIdFromURL();
     checkIntValueOfId($id);
     if (post('comment')) {
         $tweetid = $id;
         $username = $_SESSION['username'];
         $userid = UserRepository::getIdByUsername($username);
         $content = htmlentities(trim(post('comment')));
         $comment = new TweetComment();
         $comment->setTweetid($tweetid);
         $comment->setUserid($userid);
         $comment->setContent($content);
         try {
             TweetCommentRepository::postComment($comment);
             echo json_encode(['comment' => parseText($comment->getContent()), 'user' => $username]);
         } catch (\PDOException $e) {
             $e->getMessage();
         }
     }
 }
Example #20
0
function action_latex()
{
    global $page, $pagestore, $ParseEngine, $DisplayEngine, $HTTP_IF_MODIFIED_SINCE;
    global $version;
    $pg = $pagestore->page($page);
    if ($version != '') {
        $pg->version = $version;
    }
    $pg->read();
    //  if(!empty($HTTP_IF_MODIFIED_SINCE))
    //    { if_modified($pg->time); }
    //  gen_headers($pg->time);
    // $pg->text is the raw stuff from the database
    //  print $pg->text;
    // $DisplayEngine indicates what functions will be used to translate wiki
    //   markup elements into actual HTML.  See parse/html.php
    $DisplayEngine = array('bold_start' => 'latex_bold_start', 'bold_end' => 'latex_bold_end', 'italic_start' => 'latex_italic_start', 'italic_end' => 'latex_italic_end', 'tt_start' => 'latex_tt_start', 'tt_end' => 'latex_tt_end', 'head_start' => 'latex_head_start', 'head_end' => 'latex_head_end', 'newline' => 'latex_newline', 'ref' => 'latex_ref', 'url' => 'latex_url', 'interwiki' => 'latex_interwiki', 'raw' => 'latex_raw', 'code' => 'latex_code', 'hr' => 'latex_hr', 'nowiki' => 'latex_nowiki', 'bullet_list_start' => 'latex_ul_start', 'bullet_list_end' => 'latex_ul_end', 'bullet_item_start' => 'latex_li_start', 'bullet_item_end' => 'latex_li_end', 'indent_list_start' => 'latex_dl_start', 'indent_list_end' => 'latex_dl_end', 'indent_item_start' => 'latex_dd_start', 'indent_item_end' => 'latex_dd_end', 'numbered_list_start' => 'latex_ol_start', 'numbered_list_end' => 'latex_ol_end', 'numbered_item_start' => 'latex_li_start', 'numbered_item_end' => 'latex_li_end', 'diff_old_start' => 'latex_diff_old_start', 'diff_old_end' => 'latex_diff_end', 'diff_new_start' => 'latex_diff_new_start', 'diff_new_end' => 'latex_diff_end', 'diff_change' => 'latex_diff_change', 'diff_add' => 'latex_diff_add', 'diff_delete' => 'latex_diff_delete');
    $rawtext = $pg->text;
    $parseText = parseText($rawtext, $ParseEngine, "OBJECTNAMEHERE");
    $newtext = backslashit($parseText);
    template_view($page, $newtext);
}
Example #21
0
function template_common_prologue($args)
{
    global $AdditionalHeader, $CommonScript, $FindScript, $HomePage;
    global $MetaDescription, $MetaKeywords, $page, $pagestore, $ScriptBase;
    global $SeparateHeaderWords, $SeparateTitleWords, $ShortcutIcon;
    global $StyleScript, $TableSortScript, $UserName, $UseSpamRevert, $WikiLogo;
    global $WikiName;
    if ($SeparateTitleWords) {
        $args['title'] = html_split_name($args['title']);
    }
    ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<meta name="KEYWORDS" content="<?php 
    print $MetaKeywords;
    ?>
">
<meta name="DESCRIPTION" content="<?php 
    print $MetaDescription;
    ?>
">
<?php 
    if ($args['norobots']) {
        ?>
    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
<?php 
    }
    ?>
<link type="text/css" rel="stylesheet" href="<?php 
    print $StyleScript;
    ?>
">
<link type="text/css" rel="stylesheet" media="print" href="<?php 
    print $StyleScript;
    ?>
&amp;csstype=print">
<script src="<?php 
    print $TableSortScript;
    ?>
" type="text/javascript"></script>
<script src="<?php 
    print $CommonScript;
    ?>
" type="text/javascript"></script>
<?php 
    if ($ShortcutIcon) {
        ?>
    <link rel="SHORTCUT ICON" href="<?php 
        echo $ShortcutIcon;
        ?>
">
<?php 
    }
    ?>
<link rel="ALTERNATE" title="<?php 
    echo htmlspecialchars($WikiName);
    ?>
" href="<?php 
    echo $ScriptBase;
    ?>
?action=rss&page=<?php 
    echo htmlspecialchars($page);
    ?>
" TYPE="application/rss+xml">
<title><?php 
    print $args['title'] . ' - ' . htmlspecialchars($WikiName);
    ?>
</title>
</head>

<body onLoad="bodyOnLoad();">
<NOINDEX>

<?php 
    if ($AdditionalHeader) {
        print '<span class="printhide">';
        include $AdditionalHeader;
        print '</span>';
    }
    ?>

<div id="header">

  <div id="toprightbox" class="printhide">
    <div class="jumpsearch">
        <form method="get" action="<?php 
    print $FindScript;
    ?>
">
        <input type="hidden" name="action" value="find">

        Search:&nbsp;<input 
	type="text" name="find" size="20" accesskey=","><?php 
    $jumpSearchPage = $pagestore->page('JumpSearch');
    if ($jumpSearchPage->exists()) {
        print '&nbsp;<a href="' . viewURL('JumpSearch') . '">JumpSearch&nbsp;Help</a>';
    }
    ?>

        <?php 
    if ($args['headlink'] && $args['headlink'] != $HomePage && $args['headlink'] != 'RecentChanges' && $pagestore->getChildren($args['headlink'])) {
        ?>
        <br><input type="checkbox" name="branch_search" value="<?php 
        print htmlspecialchars($args['headlink']);
        ?>
">
        <label name="branch_search">Search only children of <b><?php 
        echo $args['headlink'];
        ?>
</b></label>
        <?php 
    }
    ?>
	
        </form>
    </div>
	
    <?php 
    if (isset($args['tree'])) {
        $tree = $pagestore->getTreeFromLeaves($HomePage, $args['headlink']);
        drawTree($tree, true, $args['headlink']);
    }
    ?>

  </div>

  <div id="topleftbox">
    <div class="logo printhide">
    <a href="<?php 
    print viewURL($HomePage);
    ?>
"><img src="<?php 
    print $WikiLogo;
    ?>
" alt="[Home]"></a>
    </div>
    <h1>
	
    <?php 
    print $args['heading'];
    if ($args['headlink'] != '') {
        if ($SeparateHeaderWords) {
            print html_split_name($args['headlink']);
        } else {
            print $args['headlink'];
        }
    }
    if (count($twin = $pagestore->twinpages($args['headlink']))) {
        // point at the sisterwiki's version
        print '<sup class="printhide">';
        foreach ($twin as $site) {
            print " " . html_twin($site[0], $site[1]);
        }
        print '</sup>';
    }
    print $args['headsufx'] . "</h1>\n";
    if (isset($args['redirect_from']) && $args['redirect_from']) {
        print '(Redirected from <a href="' . viewURL($args['redirect_from']) . '&no_redirect=1">';
        if ($SeparateHeaderWords) {
            print htmlspecialchars(html_split_name($args['redirect_from']));
        } else {
            print htmlspecialchars($args['redirect_from']);
        }
        print "</a>)\n";
    }
    ?>
	
    <div class="quote printhide">
    <?php 
    if (isset($args['quote'])) {
        $quotepage = $pagestore->page('AnnoyingQuote');
        $quote = $quotepage->read();
        if ($quotepage->exists()) {
            global $ParseEngine;
            $paragraphs = explode("\n\n", $quotepage->text);
            $last_paragraph = parseText(trim(array_pop($paragraphs)), $ParseEngine, $page);
            print $last_paragraph;
        }
    }
    ?>
    </div>
  </div>

</div>
</NOINDEX>
	
<div id="contentbox">

 <?php 
    if (isset($args["toolbar"])) {
        ?>
  <div class="toolbar" id="toolbar-top">
    <?php 
        if ($args['spam_revert'] && $UseSpamRevert && $UserName) {
            ?>
        <form name="revertForm" method="post" action="<?php 
            print revertURL($page);
            ?>
"></form>
        <?php 
            print toolbar_button('javascript:spamRevert();', 'Spam Revert', 0);
            ?>
    <?php 
        }
        ?>
    <td><?php 
        toolbar($page, $args);
        ?>
  </div>
 <?php 
    }
    ?>

<?php 
}
Example #22
0
 function decryptMessage($from, $ciphertext, $type, $id, $t, $retry_from = null, $skip_unpad = false)
 {
     $version = "1";
     $this->parent->debugPrint("\n-> Decrypted Message: ");
     if ($type == "pkmsg") {
         if (in_array(ExtractNumber($from), $this->parent->getv2Jids())) {
             $version = "2";
         }
         try {
             $preKeyWhisperMessage = new PreKeyWhisperMessage(null, null, null, null, null, null, null, $ciphertext);
             $sessionCipher = $this->parent->getSessionCipher(ExtractNumber($from));
             $plaintext = $sessionCipher->decryptPkmsg($preKeyWhisperMessage);
             if ($version == "2" && !$skip_unpad) {
                 $plaintext = unpadV2Plaintext($plaintext);
             }
             $this->parent->debugPrint(parseText($plaintext) . "\n\n");
             return $plaintext;
         } catch (Exception $e) {
             $this->parent->debugPrint($e->getMessage() . " - " . $e->getFile() . " - " . $e->getLine());
             if ($e->getMessage() != "Null values!") {
                 $this->parent->debugPrint("Message {$id} could not be decrypted, sending retry.\n\n");
                 $participant = null;
                 if ($retry_from != null) {
                     if (strpos($retry_from, "-") !== false) {
                         $participant = $from;
                     }
                     $from = $retry_from;
                 }
                 //$this->sendRetry($from, $id, $t, $participant);
                 return false;
             }
         }
     } else {
         if ($type == "msg") {
             if (in_array(ExtractNumber($from), $this->parent->getv2Jids())) {
                 $version = "2";
             }
             try {
                 $whisperMessage = new WhisperMessage(null, null, null, null, null, null, null, null, $ciphertext);
                 $sessionCipher = $this->parent->getSessionCipher(ExtractNumber($from));
                 $plaintext = $sessionCipher->decryptMsg($whisperMessage);
                 if ($version == "2" && !$skip_unpad) {
                     $plaintext = unpadV2Plaintext($plaintext);
                 }
                 $this->parent->debugPrint(parseText($plaintext) . "\n\n");
                 return $plaintext;
             } catch (Exception $e) {
                 $this->parent->debugPrint($e->getMessage() . " - " . $e->getFile() . " - " . $e->getLine());
                 $this->parent->debugPrint("Message {$id} could not be decrypted, sending retry.\n\n");
                 if ($retry_from != null) {
                     $from = $retry_from;
                 }
                 //$this->sendRetry($from, $id, $t);
                 return false;
             }
         } else {
             if ($type == "skmsg") {
                 if (in_array($from[1], $this->v2Jids)) {
                     $version = "2";
                 }
                 try {
                     $groupCipher = $this->parent->getGroupCipher(ExtractNumber($from[0]) . ":" . $from[1]);
                     $plaintext = $groupCipher->decrypt($ciphertext);
                     if ($version == "2" && !$skip_unpad) {
                         $plaintext = unpadV2Plaintext($plaintext);
                     }
                     $this->parent->debugPrint("Message {$id} decrypted to " . parseText($plaintext) . "\n\n");
                     return $plaintext;
                 } catch (Exception $e) {
                     $this->parent->debugPrint($e->getMessage() . " - " . $e->getFile() . " - " . $e->getLine());
                     if ($retry_from != null) {
                         $from = $retry_from;
                     }
                     $this->parent->sendRetry($this->parent->getJID($from[0]), $id, $t);
                     return false;
                 }
             }
         }
     }
 }
Example #23
0
function action_save()
{
    global $Admin, $AllowAnonymousPosts, $AllowAnonymousPostsHtml, $archive;
    global $captcha, $categories, $comment, $Diff3Cmd, $document, $EmailSuffix;
    global $EnableCaptcha, $EnableDiff3, $EnableSubscriptions;
    global $ErrorPageLocked, $HTTP_POST_VARS, $MaxPostLen, $merge, $minoredit;
    global $nextver, $NickName, $page, $pagefrom, $pagestore, $REMOTE_ADDR;
    global $Save, $SaveMacroEngine, $section, $template, $text_after;
    global $text_before, $UserName, $validationcode, $WorkingDirectory;
    if (!$UserName && !$AllowAnonymousPosts) {
        global $ErrorNoAnonComments;
        die($ErrorNoAnonComments);
    }
    if (isset($HTTP_POST_VARS['quickadd'])) {
        $quickadd = $HTTP_POST_VARS['quickadd'];
    }
    if (isset($HTTP_POST_VARS['appending'])) {
        $appending = $HTTP_POST_VARS['appending'];
    }
    // added for "Add a Quote" feature for AnnoyingQuote page
    if (isset($HTTP_POST_VARS['quoteAuthor'])) {
        $quoteAuthor = $HTTP_POST_VARS['quoteAuthor'];
    }
    if (isset($HTTP_POST_VARS['appendingQuote'])) {
        $appendingQuote = $HTTP_POST_VARS['appendingQuote'];
    }
    if (get_magic_quotes_gpc()) {
        if (isset($quickadd)) {
            $quickadd = stripslashes($quickadd);
        }
        if (isset($quoteAuthor)) {
            $quoteAuthor = stripslashes($quoteAuthor);
        }
    }
    // validations for unlogged users
    if (!$UserName) {
        if ($EnableCaptcha) {
            $captcha_d = strtolower(decode_captcha_md5($captcha));
            $captcha_v = trim(strtolower($validationcode));
            if ($captcha_v == '' || $captcha_v !== $captcha_d) {
                global $ErrorValidationCode;
                die($ErrorValidationCode);
            }
        }
        // prevent empty posts
        if (strlen(trim($quickadd)) <= 75) {
            $ptrn = '/^----\\s+\'\'\'.+?@\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} ' . '\\(\\d{4}\\/\\d{2}\\/\\d{2}\\)\'\'\':$/';
            if (preg_match($ptrn, trim($quickadd))) {
                global $ErrorEmptyComment;
                die($ErrorEmptyComment);
            }
        }
    }
    if (empty($Save)) {
        include 'action/preview.php';
        action_preview();
        return;
    }
    $pagestore->lock();
    // Ensure atomicity.
    $pg = $pagestore->page($page);
    $pg->read();
    $pageWasEmpty = strlen($pg->text) <= 1;
    if (isset($appending)) {
        $document = $pg->text;
        $nextver = $pg->version + 1;
    } else {
        if ($section) {
            $document = $text_before . "\n\n" . trim($document) . "\n\n" . $text_after;
        }
        $pg->template = $template;
    }
    // Edit disallowed.
    if (!$pg->mutable || !$UserName && (!isset($appending) || !$pg->exists())) {
        $pagestore->unlock();
        die($ErrorPageLocked);
    }
    // gets the hostname without the nickname
    $page_hostname = array_pop(explode('@', $pg->hostname));
    if ($UserName && $pg->exists() && $pg->version >= $nextver && ($page_hostname != gethostbyaddr($REMOTE_ADDR) || $pg->username != $UserName) && !$archive) {
        $merge_conflict = 1;
        $merge = '';
        $diff3_test = array();
        if ($EnableDiff3) {
            exec($Diff3Cmd . ' --help', $diff3_test);
        }
        if (count($diff3_test)) {
            // page conflict, try to merge
            $your_file_text = $pg->text;
            $my_file_text = str_replace("\r", "", $document);
            $pg_old = $pagestore->page($page);
            $pg_old->version = $nextver - 1;
            $pg_old->read();
            $old_file_text = $pg_old->text;
            global $TempDir;
            $num = posix_getpid();
            // Comment if running on Windows.
            // $num = rand();       // Uncomment if running on Windows.
            $my_file = $TempDir . '/wiki_' . $num . '_my_file.txt';
            $old_file = $TempDir . '/wiki_' . $num . '_old_file.txt';
            $your_file = $TempDir . '/wiki_' . $num . '_your_file.txt';
            if (!($h_my = fopen($my_file, 'w')) || !($h_old = fopen($old_file, 'w')) || !($h_your = fopen($your_file, 'w'))) {
                die("ErrorCreatingTemp");
            }
            if (fwrite($h_my, $my_file_text) < 0 || fwrite($h_old, $old_file_text) < 0 || fwrite($h_your, $your_file_text) < 0) {
                die("ErrorWritingTemp");
            }
            fclose($h_my);
            fclose($h_old);
            fclose($h_your);
            $diff3_options = '-mE -L "Your modifications" -L "Original file" ' . '-L "Someone else\'s modifications"';
            exec($Diff3Cmd . ' ' . $diff3_options . ' ' . $my_file . ' ' . $old_file . ' ' . $your_file, $merge);
            unlink($my_file);
            unlink($old_file);
            unlink($your_file);
            $merge = implode("\n", $merge);
            $regexp = '/<{7} Your modifications/s';
            $merge_conflict = preg_match($regexp, $merge);
        }
        if ($merge_conflict) {
            $pagestore->unlock();
            include 'action/conflict.php';
            action_conflict();
            return;
        } else {
            $document = $merge;
        }
    }
    // "Add a Comment" is "Add a Quote" for specific pages like AnnoyingQuote
    if (isset($quickadd) && isset($appendingQuote)) {
        // if we're appending a quote, instead of a comment
        $quoteAuthor = trim($quoteAuthor);
        if ($quoteAuthor != '') {
            // Add author to quote if author provided. Add a leading dash if
            // needed. See strpos help for information about "=== false".
            $pos = strpos($quoteAuthor, '-');
            if ($pos === false || $pos > 0) {
                $quoteAuthor = "-- {$quoteAuthor}";
            }
            $quickadd .= " {$quoteAuthor}";
        }
    }
    // Silently trim string to $MaxPostLen chars.
    $document = substr($document, 0, $MaxPostLen);
    if (isset($appending)) {
        $document = str_replace("\\\\'", '"', $document);
    }
    $document = str_replace("\\", "\\\\", $document);
    $document = str_replace("'", "\\'", $document);
    $document = str_replace("\r", "", $document);
    $comment = str_replace("\\", "\\\\", $comment);
    $comment = str_replace("'", "\\'", $comment);
    if (isset($appending) && isset($quickadd)) {
        // Add new lines if document is not empty.
        if ($document) {
            $document = trim($document) . "\n\n";
        }
        $quickadd = str_replace("\\", "\\\\", $quickadd);
        $quickadd = str_replace("'", "\\'", $quickadd);
        $quickadd = str_replace("\r", "", $quickadd);
        if (!$AllowAnonymousPostsHtml) {
            $quickadd = htmlspecialchars($quickadd);
        }
        $document .= $quickadd;
    }
    $pg->text = $document;
    $pg->hostname = gethostbyaddr($REMOTE_ADDR);
    if (!$UserName && $NickName) {
        $nick_sql = str_replace("\\", "\\\\", $NickName);
        $nick_sql = str_replace("'", "\\'", $nick_sql);
        $pg->hostname = $nick_sql . '@' . $pg->hostname;
    }
    $pg->username = $UserName;
    $pg->comment = $comment;
    if ($pg->exists) {
        $pg->version++;
    } else {
        $pg->version = 1;
    }
    if (!$pg->write($minoredit)) {
        $pagestore->unlock();
        die("Error saving a page.");
    }
    // Parenting stuff for new pages.
    if ($pageWasEmpty) {
        // Ensures that $pagefrom is really a backlink.
        if ($pagefrom) {
            $backlinks = $pagestore->getBacklinks($page);
            if (!in_array($pagefrom, $backlinks)) {
                $pagefrom = '';
            }
        }
        // If no parent is specified, tries to find one.
        if (!$pagefrom) {
            $pagefrom = $pagestore->findFosterParent($page);
        }
        // The $pagefrom page becomes the new page's parent.
        if ($pagefrom) {
            $tempPage = $pagestore->page($pagefrom);
            if ($tempPage->exists()) {
                $pagestore->reparent($page, $pagefrom);
            }
        }
    }
    // Editor asked page to be added to a category or categories.
    if (!empty($categories)) {
        add_to_category($page, $categories);
    }
    // Process save macros (e.g., to define interwiki entries).
    parseText($document, $SaveMacroEngine, $page);
    // Remove any parenting if the page is empty.
    if (strlen(trim($document)) == 0) {
        $pagestore->reparent_emptypage($page);
    }
    $pagestore->unlock();
    // End "transaction".
    // Handles page subscriptions
    if ($EnableSubscriptions && isset($EmailSuffix)) {
        if ($subscribed_users = $pg->getSubscribedUsers($UserName)) {
            global $ScriptBase, $WikiName;
            foreach ($subscribed_users as $user) {
                $msg = "This is your friendly neighbourhood wiki ({$WikiName}) " . "letting you know that the page {$page} has changed!\n\n";
                if ($minoredit) {
                    $msg .= "This was a minor edit.\n\n";
                }
                $msg .= "View page: {$ScriptBase}?{$page}\n\n" . "History: {$ScriptBase}?action=history&page={$page}\n\n";
                // friendly diff
                $history = $pagestore->history($page);
                if (count($history) > 1) {
                    $previous_ver = $history[1][2];
                    $latest_ver = $history[0][2];
                    $p1 = $pagestore->page($page);
                    $p1->version = $previous_ver;
                    $p2 = $pagestore->page($page);
                    $p2->version = $latest_ver;
                    $diff = diff_compute($p1->read(), $p2->read());
                    $msg .= "Friendly diff:\n\n{$diff}";
                }
                mail($user . $EmailSuffix, "{$WikiName}: {$page} has changed", $msg, "From: {$Admin}");
            }
        }
    }
    // Aligns the browser with an HTML anchor, showing the last added comment (or quote)
    // See: action/save.php, template/save.php, template/view.php
    if (isset($quickadd)) {
        // if Add a Comment or Add a Quote
        template_save(array('page' => $page, 'text' => $document, 'anchor' => 'pageContentBottom'));
    } else {
        // Standard save
        template_save(array('page' => $page, 'text' => $document));
    }
}
Example #24
0
function precacheMessage($messageid, $forwardContent = 0)
{
    global $cached;
    $domain = getConfig('domain');
    #    $message = Sql_query("select * from {$GLOBALS["tables"]["message"]} where id = $messageid");
    #    $cached[$messageid] = array();
    #    $message = Sql_fetch_array($message);
    $message = loadMessageData($messageid);
    ## the reply to is actually not in use
    if (preg_match("/([^ ]+@[^ ]+)/", $message["replyto"], $regs)) {
        # if there is an email in the from, rewrite it as "name <email>"
        $message["replyto"] = str_replace($regs[0], "", $message["replyto"]);
        $cached[$messageid]["replytoemail"] = $regs[0];
        # if the email has < and > take them out here
        $cached[$messageid]["replytoemail"] = str_replace("<", "", $cached[$messageid]["replytoemail"]);
        $cached[$messageid]["replytoemail"] = str_replace(">", "", $cached[$messageid]["replytoemail"]);
        # make sure there are no quotes around the name
        $cached[$messageid]["replytoname"] = str_replace('"', "", ltrim(rtrim($message["replyto"])));
    } elseif (strpos($message["replyto"], " ")) {
        # if there is a space, we need to add the email
        $cached[$messageid]["replytoname"] = $message["replyto"];
        $cached[$messageid]["replytoemail"] = "listmaster@{$domain}";
    } else {
        if (!empty($message["replyto"])) {
            $cached[$messageid]["replytoemail"] = $message["replyto"] . "@{$domain}";
            ## makes more sense not to add the domain to the word, but the help says it does
            ## so let's keep it for now
            $cached[$messageid]["replytoname"] = $message["replyto"] . "@{$domain}";
        }
    }
    $cached[$messageid]["fromname"] = $message["fromname"];
    $cached[$messageid]["fromemail"] = $message["fromemail"];
    $cached[$messageid]["to"] = $message["tofield"];
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]["subject"] = $forwardContent ? stripslashes($message["forwardsubject"]) : $message["subject"];
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]["content"] = $forwardContent ? stripslashes($message["forwardmessage"]) : $message["message"];
    if (USE_MANUAL_TEXT_PART && !$forwardContent) {
        $cached[$messageid]["textcontent"] = $message["textmessage"];
    } else {
        $cached[$messageid]["textcontent"] = '';
    }
    #  var_dump($cached);exit;
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]["footer"] = $forwardContent ? stripslashes($message["forwardfooter"]) : $message["footer"];
    if (strip_tags($cached[$messageid]["footer"]) != $cached[$messageid]["footer"]) {
        $cached[$messageid]["textfooter"] = HTML2Text($cached[$messageid]["footer"]);
        $cached[$messageid]["htmlfooter"] = $cached[$messageid]["footer"];
    } else {
        $cached[$messageid]["textfooter"] = $cached[$messageid]["footer"];
        $cached[$messageid]["htmlfooter"] = parseText($cached[$messageid]["footer"]);
    }
    $cached[$messageid]["htmlformatted"] = strip_tags($cached[$messageid]["content"]) != $cached[$messageid]["content"];
    $cached[$messageid]["sendformat"] = $message["sendformat"];
    if ($message["template"]) {
        $req = Sql_Fetch_Row_Query("select template from {$GLOBALS["tables"]["template"]} where id = {$message["template"]}");
        $cached[$messageid]["template"] = stripslashes($req[0]);
        $cached[$messageid]["templateid"] = $message["template"];
        #   dbg("TEMPLATE: ".$req[0]);
    } else {
        $cached[$messageid]["template"] = '';
        $cached[$messageid]["templateid"] = 0;
    }
    ## @@ put this here, so it can become editable per email sent out at a later stage
    $cached[$messageid]["html_charset"] = 'UTF-8';
    #getConfig("html_charset");
    ## @@ need to check on validity of charset
    if (!$cached[$messageid]["html_charset"]) {
        $cached[$messageid]["html_charset"] = 'UTF-8';
        #'iso-8859-1';
    }
    $cached[$messageid]["text_charset"] = 'UTF-8';
    #getConfig("text_charset");
    if (!$cached[$messageid]["text_charset"]) {
        $cached[$messageid]["text_charset"] = 'UTF-8';
        #'iso-8859-1';
    }
    ## if we are sending a URL that contains user attributes, we cannot pre-parse the message here
    ## but that has quite some impact on speed. So check if that's the case and apply
    $cached[$messageid]['userspecific_url'] = preg_match('/\\[.+\\]/', $message['sendurl']);
    if (!$cached[$messageid]['userspecific_url']) {
        ## Fetch external content here, because URL does not contain placeholders
        if ($GLOBALS["can_fetchUrl"] && preg_match("/\\[URL:([^\\s]+)\\]/i", $cached[$messageid]["content"], $regs)) {
            $remote_content = fetchUrl($regs[1], array());
            #  $remote_content = fetchUrl($message['sendurl'],array());
            # @@ don't use this
            #      $remote_content = includeStyles($remote_content);
            if ($remote_content) {
                $cached[$messageid]['content'] = str_replace($regs[0], $remote_content, $cached[$messageid]['content']);
                #  $cached[$messageid]['content'] = $remote_content;
                $cached[$messageid]["htmlformatted"] = strip_tags($remote_content) != $remote_content;
                ## 17086 - disregard any template settings when we have a valid remote URL
                $cached[$messageid]["template"] = NULL;
                $cached[$messageid]["templateid"] = NULL;
            } else {
                #print Error(s('unable to fetch web page for sending'));
                logEvent("Error fetching URL: " . $message['sendurl'] . ' cannot proceed');
                return false;
            }
        }
        if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
            output('fetch URL end');
        }
        /*
        print $message['sendurl'];
        print $remote_content;exit;
        */
    }
    // end if not userspecific url
    if ($cached[$messageid]["htmlformatted"]) {
        #   $cached[$messageid]["content"] = compressContent($cached[$messageid]["content"]);
    }
    $cached[$messageid]['google_track'] = $message['google_track'];
    /*
        else {
    print $message['sendurl'];
    exit;
    }
    */
    if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
        output('parse config start');
    }
    /*
     * this is not a good idea, as it'll replace eg "unsubscribeurl" with a general one instead of personalised
     *   if (is_array($GLOBALS["default_config"])) {
      foreach($GLOBALS["default_config"] as $key => $val) {
        if (is_array($val)) {
          $cached[$messageid]['content'] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['content']);
          $cached[$messageid]["textcontent"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]["textcontent"]);
          $cached[$messageid]["textfooter"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['textfooter']);
          $cached[$messageid]["htmlfooter"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['htmlfooter']);
        }
      }
    }
    */
    if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
        output('parse config end');
    }
    ## ##17233 not that many fields are actually useful, so don't blatantly use all
    #  foreach($message as $key => $val) {
    foreach (array('subject', 'id', 'fromname', 'fromemail') as $key) {
        $val = $message[$key];
        if (!is_array($val)) {
            $cached[$messageid]['content'] = str_ireplace("[{$key}]", $val, $cached[$messageid]['content']);
            $cached[$messageid]["textcontent"] = str_ireplace("[{$key}]", $val, $cached[$messageid]["textcontent"]);
            $cached[$messageid]["textfooter"] = str_ireplace("[{$key}]", $val, $cached[$messageid]['textfooter']);
            $cached[$messageid]["htmlfooter"] = str_ireplace("[{$key}]", $val, $cached[$messageid]['htmlfooter']);
        }
    }
    if (preg_match("/##LISTOWNER=(.*)/", $cached[$messageid]['content'], $regs)) {
        $cached[$messageid]['listowner'] = $regs[1];
        $cached[$messageid]['content'] = str_replace($regs[0], "", $cached[$messageid]['content']);
    } else {
        $cached[$messageid]['listowner'] = 0;
    }
    if (!empty($cached[$messageid]['listowner'])) {
        $att_req = Sql_Query("select name,value from {$GLOBALS["tables"]["adminattribute"]},{$GLOBALS["tables"]["admin_attribute"]} where {$GLOBALS["tables"]["adminattribute"]}.id = {$GLOBALS["tables"]["admin_attribute"]}.adminattributeid and {$GLOBALS["tables"]["admin_attribute"]}.adminid = " . $cached[$messageid]['listowner']);
        while ($att = Sql_Fetch_Array($att_req)) {
            $cached[$messageid]['content'] = preg_replace("#\\[LISTOWNER." . strtoupper(preg_quote($att["name"])) . "\\]#", $att["value"], $cached[$messageid]['content']);
        }
    }
    $baseurl = $GLOBALS['website'];
    if (defined('UPLOADIMAGES_DIR') && UPLOADIMAGES_DIR) {
        ## escape subdirectories, otherwise this renders empty
        $dir = str_replace('/', '\\/', UPLOADIMAGES_DIR);
        $cached[$messageid]['content'] = preg_replace('/<img(.*)src="\\/' . $dir . '(.*)>/iU', '<img\\1src="' . $GLOBALS['public_scheme'] . '://' . $baseurl . '/' . UPLOADIMAGES_DIR . '\\2>', $cached[$messageid]['content']);
    }
    //if (defined('FCKIMAGES_DIR') && FCKIMAGES_DIR) {
    //$cached[$messageid]['content'] = preg_replace('/<img(.*)src="\/lists\/'.FCKIMAGES_DIR.'(.*)>/iU','<img\\1src="'.$GLOBALS['public_scheme'].'://'.$baseurl.'/lists/'.FCKIMAGES_DIR.'\\2>',$cached[$messageid]['content']);
    //}
    return 1;
}
Example #25
0
function precacheMessage($messageid, $forwardContent = 0)
{
    global $cached, $tables;
    $domain = getConfig('domain');
    #    $message = Sql_query("select * from {$GLOBALS["tables"]["message"]} where id = $messageid");
    #    $cached[$messageid] = array();
    #    $message = Sql_fetch_array($message);
    $message = loadMessageData($messageid);
    ## the reply to is actually not in use
    if (preg_match('/([^ ]+@[^ ]+)/', $message['replyto'], $regs)) {
        # if there is an email in the from, rewrite it as "name <email>"
        $message['replyto'] = str_replace($regs[0], '', $message['replyto']);
        $cached[$messageid]['replytoemail'] = $regs[0];
        # if the email has < and > take them out here
        $cached[$messageid]['replytoemail'] = str_replace('<', '', $cached[$messageid]['replytoemail']);
        $cached[$messageid]['replytoemail'] = str_replace('>', '', $cached[$messageid]['replytoemail']);
        # make sure there are no quotes around the name
        $cached[$messageid]['replytoname'] = str_replace('"', '', ltrim(rtrim($message['replyto'])));
    } elseif (strpos($message['replyto'], ' ')) {
        # if there is a space, we need to add the email
        $cached[$messageid]['replytoname'] = $message['replyto'];
        $cached[$messageid]['replytoemail'] = "listmaster@{$domain}";
    } else {
        if (!empty($message['replyto'])) {
            $cached[$messageid]['replytoemail'] = $message['replyto'] . "@{$domain}";
            ## makes more sense not to add the domain to the word, but the help says it does
            ## so let's keep it for now
            $cached[$messageid]['replytoname'] = $message['replyto'] . "@{$domain}";
        }
    }
    $cached[$messageid]['fromname'] = $message['fromname'];
    $cached[$messageid]['fromemail'] = $message['fromemail'];
    $cached[$messageid]['to'] = $message['tofield'];
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]['subject'] = $forwardContent ? stripslashes($message['forwardsubject']) : $message['subject'];
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]['content'] = $forwardContent ? stripslashes($message['forwardmessage']) : $message['message'];
    if (USE_MANUAL_TEXT_PART && !$forwardContent) {
        $cached[$messageid]['textcontent'] = $message['textmessage'];
    } else {
        $cached[$messageid]['textcontent'] = '';
    }
    #  var_dump($cached);exit;
    #0013076: different content when forwarding 'to a friend'
    $cached[$messageid]['footer'] = $forwardContent ? stripslashes($message['forwardfooter']) : $message['footer'];
    if (strip_tags($cached[$messageid]['footer']) != $cached[$messageid]['footer']) {
        $cached[$messageid]['textfooter'] = HTML2Text($cached[$messageid]['footer']);
        $cached[$messageid]['htmlfooter'] = $cached[$messageid]['footer'];
    } else {
        $cached[$messageid]['textfooter'] = $cached[$messageid]['footer'];
        $cached[$messageid]['htmlfooter'] = parseText($cached[$messageid]['footer']);
    }
    $cached[$messageid]['htmlformatted'] = strip_tags($cached[$messageid]['content']) != $cached[$messageid]['content'];
    $cached[$messageid]['sendformat'] = $message['sendformat'];
    if ($message['template']) {
        $req = Sql_Fetch_Row_Query("select template from {$GLOBALS['tables']['template']} where id = {$message['template']}");
        $cached[$messageid]['template'] = stripslashes($req[0]);
        $cached[$messageid]['templateid'] = $message['template'];
        #   dbg("TEMPLATE: ".$req[0]);
    } else {
        $cached[$messageid]['template'] = '';
        $cached[$messageid]['templateid'] = 0;
    }
    ## @@ put this here, so it can become editable per email sent out at a later stage
    $cached[$messageid]['html_charset'] = 'UTF-8';
    #getConfig("html_charset");
    ## @@ need to check on validity of charset
    if (!$cached[$messageid]['html_charset']) {
        $cached[$messageid]['html_charset'] = 'UTF-8';
        #'iso-8859-1';
    }
    $cached[$messageid]['text_charset'] = 'UTF-8';
    #getConfig("text_charset");
    if (!$cached[$messageid]['text_charset']) {
        $cached[$messageid]['text_charset'] = 'UTF-8';
        #'iso-8859-1';
    }
    ## if we are sending a URL that contains user attributes, we cannot pre-parse the message here
    ## but that has quite some impact on speed. So check if that's the case and apply
    $cached[$messageid]['userspecific_url'] = preg_match('/\\[.+\\]/', $message['sendurl']);
    if (!$cached[$messageid]['userspecific_url']) {
        ## Fetch external content here, because URL does not contain placeholders
        if ($GLOBALS['can_fetchUrl'] && preg_match("/\\[URL:([^\\s]+)\\]/i", $cached[$messageid]['content'], $regs)) {
            $remote_content = fetchUrl($regs[1], array());
            #  $remote_content = fetchUrl($message['sendurl'],array());
            # @@ don't use this
            #      $remote_content = includeStyles($remote_content);
            if ($remote_content) {
                $cached[$messageid]['content'] = str_replace($regs[0], $remote_content, $cached[$messageid]['content']);
                #  $cached[$messageid]['content'] = $remote_content;
                $cached[$messageid]['htmlformatted'] = strip_tags($remote_content) != $remote_content;
                ## 17086 - disregard any template settings when we have a valid remote URL
                $cached[$messageid]['template'] = null;
                $cached[$messageid]['templateid'] = null;
            } else {
                #print Error(s('unable to fetch web page for sending'));
                logEvent('Error fetching URL: ' . $message['sendurl'] . ' cannot proceed');
                return false;
            }
        }
        if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
            output('fetch URL end');
        }
        /*
        print $message['sendurl'];
        print $remote_content;exit;
        */
    }
    // end if not userspecific url
    if ($cached[$messageid]['htmlformatted']) {
        #   $cached[$messageid]["content"] = compressContent($cached[$messageid]["content"]);
    }
    $cached[$messageid]['google_track'] = $message['google_track'];
    /*
        else {
    print $message['sendurl'];
    exit;
    }
    */
    foreach ($GLOBALS['plugins'] as $plugin) {
        $plugin->processPrecachedCampaign($messageid, $cached[$messageid]);
    }
    if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
        output('parse config start');
    }
    /*
     * this is not a good idea, as it'll replace eg "unsubscribeurl" with a general one instead of personalised
     *   if (is_array($GLOBALS["default_config"])) {
      foreach($GLOBALS["default_config"] as $key => $val) {
        if (is_array($val)) {
          $cached[$messageid]['content'] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['content']);
          $cached[$messageid]["textcontent"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]["textcontent"]);
          $cached[$messageid]["textfooter"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['textfooter']);
          $cached[$messageid]["htmlfooter"] = str_ireplace("[$key]",getConfig($key),$cached[$messageid]['htmlfooter']);
        }
      }
    }
    */
    if (VERBOSE && !empty($GLOBALS['getspeedstats'])) {
        output('parse config end');
    }
    ## ##17233 not that many fields are actually useful, so don't blatantly use all
    #  foreach($message as $key => $val) {
    foreach (array('subject', 'id', 'fromname', 'fromemail') as $key) {
        $val = $message[$key];
        if (!is_array($val)) {
            $cached[$messageid]['content'] = str_ireplace("[{$key}]", $val, $cached[$messageid]['content']);
            $cached[$messageid]['textcontent'] = str_ireplace("[{$key}]", $val, $cached[$messageid]['textcontent']);
            $cached[$messageid]['textfooter'] = str_ireplace("[{$key}]", $val, $cached[$messageid]['textfooter']);
            $cached[$messageid]['htmlfooter'] = str_ireplace("[{$key}]", $val, $cached[$messageid]['htmlfooter']);
        }
    }
    /*
     *  cache message owner and list owner attribute values
     */
    $cached[$messageid]['adminattributes'] = array();
    $result = Sql_Query("SELECT a.name, aa.value\n        FROM {$tables['adminattribute']} a\n        JOIN {$tables['admin_attribute']} aa ON a.id = aa.adminattributeid\n        JOIN {$tables['message']} m ON aa.adminid = m.owner\n        WHERE m.id = {$messageid}");
    if ($result !== false) {
        while ($att = Sql_Fetch_Array($result)) {
            $cached[$messageid]['adminattributes']['OWNER.' . $att['name']] = $att['value'];
        }
    }
    $result = Sql_Query("SELECT DISTINCT l.owner\n        FROM {$tables['list']} AS l\n        JOIN  {$tables['listmessage']} AS lm ON lm.listid = l.id\n        WHERE lm.messageid = {$messageid}");
    if ($result !== false && Sql_Num_Rows($result) == 1) {
        $row = Sql_Fetch_Assoc($result);
        $listOwner = $row['owner'];
        $att_req = Sql_Query("SELECT a.name, aa.value\n            FROM {$tables['adminattribute']} a\n            JOIN {$tables['admin_attribute']} aa ON a.id = aa.adminattributeid\n            WHERE aa.adminid = {$listOwner}");
        while ($att = Sql_Fetch_Array($att_req)) {
            $cached[$messageid]['adminattributes']['LISTOWNER.' . $att['name']] = $att['value'];
        }
    }
    $baseurl = $GLOBALS['website'];
    if (defined('UPLOADIMAGES_DIR') && UPLOADIMAGES_DIR) {
        ## escape subdirectories, otherwise this renders empty
        $dir = str_replace('/', '\\/', UPLOADIMAGES_DIR);
        $cached[$messageid]['content'] = preg_replace('/<img(.*)src="\\/' . $dir . '(.*)>/iU', '<img\\1src="' . $GLOBALS['public_scheme'] . '://' . $baseurl . '/' . UPLOADIMAGES_DIR . '\\2>', $cached[$messageid]['content']);
    }
    foreach (array('content', 'template', 'htmlfooter') as $element) {
        $cached[$messageid][$element] = parseLogoPlaceholders($cached[$messageid][$element]);
    }
    return 1;
}
function niceVarDump($obj, $ident = 0)
{
    $data = "";
    $data .= str_repeat(" ", $ident);
    $original_ident = $ident;
    $toClose = false;
    switch (gettype($obj)) {
        case "object":
            $vars = (array) $obj;
            $data .= gettype($obj) . " (" . get_class($obj) . ") (" . count($vars) . ") {\n";
            $ident += 2;
            foreach ($vars as $key => $var) {
                $type = "";
                $k = bin2hex($key);
                if (strpos($k, "002a00") === 0) {
                    $k = str_replace("002a00", "", $k);
                    $type = ":protected";
                } else {
                    if (strpos($k, bin2hex("" . get_class($obj) . "")) === 0) {
                        $k = str_replace(bin2hex("" . get_class($obj) . ""), "", $k);
                        $type = ":private";
                    }
                }
                $k = hex2bin($k);
                if (is_subclass_of($obj, "ProtobufMessage") && $k == "values") {
                    $r = new ReflectionClass($obj);
                    $constants = $r->getConstants();
                    $newVar = [];
                    foreach ($constants as $ckey => $cval) {
                        if (substr($ckey, 0, 3) != "PB_") {
                            $newVar[$ckey] = $var[$cval];
                        }
                    }
                    $var = $newVar;
                }
                $data .= str_repeat(" ", $ident) . "[{$k}{$type}]=>\n" . niceVarDump($var, $ident) . "\n";
            }
            $toClose = true;
            break;
        case "array":
            $data .= "array (" . count($obj) . ") {\n";
            $ident += 2;
            foreach ($obj as $key => $val) {
                $data .= str_repeat(" ", $ident) . "[" . (is_integer($key) ? $key : "\"{$key}\"") . "]=>\n" . niceVarDump($val, $ident) . "\n";
            }
            $toClose = true;
            break;
        case "string":
            $data .= "string \"" . parseText($obj) . "\"\n";
            break;
        case "NULL":
            $data .= gettype($obj);
            break;
        default:
            $data .= gettype($obj) . "(" . strval($obj) . ")\n";
            break;
    }
    if ($toClose) {
        $data .= str_repeat(" ", $original_ident) . "}\n";
    }
    return $data;
}
Example #27
0
// Open the database
mysql_connect($DBServer, $DBUser, $DBPasswd);
mysql_select_db($DBName);
// Report
echo 'Processing configuration page <a href="', "index.php?page={$page}", '">', $page, "</a>.<br />\n";
echo 'Using template <a href="', $TDTemplateFile, '">', $TDTemplateFile, "</a>.<br />\n";
echo 'Output into path <a href="', $TDOutputPath, '">', $TDOutputPath, "</a>.<br />\n", '<ol>';
$TDPageQueue[] = $page;
$i = 0;
while ($i < count($TDPageQueue)) {
    $Title = $TDPageQueue[$i];
    $Messages = array();
    $PageCount = count($TDPageQueue);
    // Render using Tavi
    $Entity = array();
    $body = parseText(query_page_body($Title), $CustomParseEngine, '');
    // Macros
    $body = str_replace(array('[TITLE]', '[BODY]', '[TIMESTAMP]', '[YEAR]'), array($Title, $body, date('w, F jS Y, G:i'), date('Y')), $TDTemplate);
    // Write file
    $filename = $TDOutputPath . filename($Title);
    $fid = fopen($filename, 'w');
    fwrite($fid, $body);
    fclose($fid);
    // Report
    $dif = count($TDPageQueue) - $PageCount;
    echo '<li>', 'Writing page <a href="index.php?page=', $Title, '">', $Title, '</a>', ' to file <a href="' . $filename . '">', $filename, '</a>', $dif > 0 ? ", {$dif} new pages found" : '';
    if (count($Messages) > 0) {
        echo '<ol>';
        foreach ($Messages as $Message) {
            echo '<li>' . $Message . '</li>';
        }
Example #28
0
function sendEmail($messageid, $email, $hash, $htmlpref = 0, $rssitems = array(), $forwardedby = array())
{
    global $strThisLink, $PoweredByImage, $PoweredByText, $cached, $website;
    if ($email == "") {
        return 0;
    }
    #0013076: different content when forwarding 'to a friend'
    if (FORWARD_ALTERNATIVE_CONTENT) {
        $forwardContent = sizeof($forwardedby) > 0;
        $messagedata = loadMessageData($messageid);
    } else {
        $forwardContent = 0;
    }
    if (empty($cached[$messageid])) {
        $domain = getConfig("domain");
        $message = Sql_query("select * from {$GLOBALS["tables"]["message"]} where id = {$messageid}");
        $cached[$messageid] = array();
        $message = Sql_fetch_array($message);
        if (ereg("([^ ]+@[^ ]+)", $message["fromfield"], $regs)) {
            # if there is an email in the from, rewrite it as "name <email>"
            $message["fromfield"] = ereg_replace($regs[0], "", $message["fromfield"]);
            $cached[$messageid]["fromemail"] = $regs[0];
            # if the email has < and > take them out here
            $cached[$messageid]["fromemail"] = ereg_replace("<", "", $cached[$messageid]["fromemail"]);
            $cached[$messageid]["fromemail"] = ereg_replace(">", "", $cached[$messageid]["fromemail"]);
            # make sure there are no quotes around the name
            $cached[$messageid]["fromname"] = ereg_replace('"', "", ltrim(rtrim($message["fromfield"])));
        } elseif (ereg(" ", $message["fromfield"], $regs)) {
            # if there is a space, we need to add the email
            $cached[$messageid]["fromname"] = $message["fromfield"];
            $cached[$messageid]["fromemail"] = "listmaster@{$domain}";
        } else {
            $cached[$messageid]["fromemail"] = $message["fromfield"] . "@{$domain}";
            ## makes more sense not to add the domain to the word, but the help says it does
            ## so let's keep it for now
            $cached[$messageid]["fromname"] = $message["fromfield"] . "@{$domain}";
        }
        # erase double spacing
        while (ereg("  ", $cached[$messageid]["fromname"])) {
            $cached[$messageid]["fromname"] = eregi_replace("  ", " ", $cached[$messageid]["fromname"]);
        }
        ## this has weird effects when used with only one word, so take it out for now
        #    $cached[$messageid]["fromname"] = eregi_replace("@","",$cached[$messageid]["fromname"]);
        $cached[$messageid]["fromname"] = trim($cached[$messageid]["fromname"]);
        $cached[$messageid]["to"] = $message["tofield"];
        #0013076: different content when forwarding 'to a friend'
        $cached[$messageid]["subject"] = $forwardContent ? stripslashes($messagedata["forwardsubject"]) : $message["subject"];
        $cached[$messageid]["replyto"] = $message["replyto"];
        #0013076: different content when forwarding 'to a friend'
        $cached[$messageid]["content"] = $forwardContent ? stripslashes($messagedata["forwardmessage"]) : $message["message"];
        if (USE_MANUAL_TEXT_PART && !$forwardContent) {
            $cached[$messageid]["textcontent"] = $message["textmessage"];
        } else {
            $cached[$messageid]["textcontent"] = '';
        }
        #0013076: different content when forwarding 'to a friend'
        $cached[$messageid]["footer"] = $forwardContent ? stripslashes($messagedata["forwardfooter"]) : $message["footer"];
        $cached[$messageid]["htmlformatted"] = $message["htmlformatted"];
        $cached[$messageid]["sendformat"] = $message["sendformat"];
        if ($message["template"]) {
            $req = Sql_Fetch_Row_Query("select template from {$GLOBALS["tables"]["template"]} where id = {$message["template"]}");
            $cached[$messageid]["template"] = stripslashes($req[0]);
            $cached[$messageid]["templateid"] = $message["template"];
            #   dbg("TEMPLATE: ".$req[0]);
        } else {
            $cached[$messageid]["template"] = '';
            $cached[$messageid]["templateid"] = 0;
        }
        ## @@ put this here, so it can become editable per email sent out at a later stage
        $cached[$messageid]["html_charset"] = getConfig("html_charset");
        ## @@ need to check on validity of charset
        if (!$cached[$messageid]["html_charset"]) {
            $cached[$messageid]["html_charset"] = 'iso-8859-1';
        }
        $cached[$messageid]["text_charset"] = getConfig("text_charset");
        if (!$cached[$messageid]["text_charset"]) {
            $cached[$messageid]["text_charset"] = 'iso-8859-1';
        }
    }
    # else
    #  dbg("Using cached {$cached[$messageid]["fromemail"]}");
    if (VERBOSE) {
        output($GLOBALS['I18N']->get('sendingmessage') . ' ' . $messageid . ' ' . $GLOBALS['I18N']->get('withsubject') . ' ' . $cached[$messageid]["subject"] . ' ' . $GLOBALS['I18N']->get('to') . ' ' . $email);
    }
    # erase any placeholders that were not found
    #  $msg = ereg_replace("\[[A-Z ]+\]","",$msg);
    #0011857: forward to friend, retain attributes
    if ($hash == 'forwarded' && defined('KEEPFORWARDERATTRIBUTES') && KEEPFORWARDERATTRIBUTES) {
        $user_att_values = getUserAttributeValues($forwardedby['email']);
    } else {
        $user_att_values = getUserAttributeValues($email);
    }
    $userdata = Sql_Fetch_Assoc_Query(sprintf('select * from %s where email = "%s"', $GLOBALS["tables"]["user"], $email));
    $url = getConfig("unsubscribeurl");
    $sep = ereg('\\?', $url) ? '&' : '?';
    $html["unsubscribe"] = sprintf('<a href="%s%suid=%s">%s</a>', $url, $sep, $hash, $strThisLink);
    $text["unsubscribe"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    $html["unsubscribeurl"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    $text["unsubscribeurl"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    #0013076: Blacklisting posibility for unknown users
    $url = getConfig("blacklisturl");
    $sep = ereg('\\?', $url) ? '&' : '?';
    $html["blacklist"] = sprintf('<a href="%s%semail=%s">%s</a>', $url, $sep, $email, $strThisLink);
    $text["blacklist"] = sprintf('%s%semail=%s', $url, $sep, $email);
    $html["blacklisturl"] = sprintf('%s%semail=%s', $url, $sep, $email);
    $text["blacklisturl"] = sprintf('%s%semail=%s', $url, $sep, $email);
    #0013076: Problem found during testing: mesage part must be parsed correctly as well.
    if ($forwardContent) {
        $html["unsubscribe"] = $html["blacklist"];
        $text["unsubscribe"] = $text["blacklist"];
    }
    $url = getConfig("subscribeurl");
    $sep = ereg('\\?', $url) ? '&' : '?';
    $html["subscribe"] = sprintf('<a href="%s">%s</a>', $url, $strThisLink);
    $text["subscribe"] = sprintf('%s', $url);
    $html["subscribeurl"] = sprintf('%s', $url);
    $text["subscribeurl"] = sprintf('%s', $url);
    #?mid=1&id=1&uid=a9f35f130593a3d6b89cfe5cfb32a0d8&p=forward&email=michiel%40tincan.co.uk&
    $url = getConfig("forwardurl");
    $sep = ereg('\\?', $url) ? '&' : '?';
    $html["forward"] = sprintf('<a href="%s%suid=%s&mid=%d">%s</a>', $url, $sep, $hash, $messageid, $strThisLink);
    $text["forward"] = sprintf('%s%suid=%s&mid=%d', $url, $sep, $hash, $messageid);
    $html["forwardurl"] = sprintf('%s%suid=%s&mid=%d', $url, $sep, $hash, $messageid);
    $text["forwardurl"] = $text["forward"];
    $url = getConfig("forwardurl");
    # make sure there are no newlines, otherwise they get turned into <br/>s
    $html["forwardform"] = sprintf('<form method="get" action="%s" name="forwardform" class="forwardform"><input type=hidden name="uid" value="%s" /><input type=hidden name="mid" value="%d" /><input type=hidden name="p" value="forward" /><input type=text name="email" value="" class="forwardinput" /><input name="Send" type="submit" value="%s" class="forwardsubmit"/></form>', $url, $hash, $messageid, $GLOBALS['strForward']);
    $text["signature"] = "\n\n--\nPowered by PHPlist, www.phplist.com --\n\n";
    $url = getConfig("preferencesurl");
    $sep = ereg('\\?', $url) ? '&' : '?';
    $html["preferences"] = sprintf('<a href="%s%suid=%s">%s</a>', $url, $sep, $hash, $strThisLink);
    $text["preferences"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    $html["preferencesurl"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    $text["preferencesurl"] = sprintf('%s%suid=%s', $url, $sep, $hash);
    /*
      We request you retain the signature below in your emails including the links.
      This not only gives respect to the large amount of time given freely
      by the developers  but also helps build interest, traffic and use of
      PHPlist, which is beneficial to it's future development.
    
      You can configure how the credits are added to your pages and emails in your
      config file.
    
      Michiel Dethmers, Tincan Ltd 2003, 2004, 2005, 2006
    */
    if (!EMAILTEXTCREDITS) {
        $html["signature"] = $PoweredByImage;
        #'<div align="center" id="signature"><a href="http://www.phplist.com"><img src="powerphplist.png" width=88 height=31 title="Powered by PHPlist" alt="Powered by PHPlist" border="0"></a></div>';
        # oops, accidentally became spyware, never intended that, so take it out again :-)
        $html["signature"] = preg_replace('/src=".*power-phplist.png"/', 'src="powerphplist.png"', $html["signature"]);
    } else {
        $html["signature"] = $PoweredByText;
    }
    $content = $cached[$messageid]["content"];
    if (preg_match("/##LISTOWNER=(.*)/", $content, $regs)) {
        $listowner = $regs[1];
        $content = ereg_replace($regs[0], "", $content);
    } else {
        $listowner = 0;
    }
    ## Fetch external content
    if ($GLOBALS["has_pear_http_request"] && preg_match("/\\[URL:([^\\s]+)\\]/i", $content, $regs)) {
        while (isset($regs[1]) && strlen($regs[1])) {
            $url = $regs[1];
            if (!preg_match('/^http/i', $url)) {
                $url = 'http://' . $url;
            }
            $remote_content = fetchUrl($url, $userdata);
            if ($remote_content) {
                $content = eregi_replace(preg_quote($regs[0]), $remote_content, $content);
                $cached[$messageid]["htmlformatted"] = strip_tags($content) != $content;
            } else {
                logEvent("Error fetching URL: {$regs['1']} to send to {$email}");
                return 0;
            }
            preg_match("/\\[URL:([^\\s]+)\\]/i", $content, $regs);
        }
    }
    #~Bas 0008857
    // @@ Switched off for now, needs rigid testing, or config setting
    // $content = mailto2href($content);
    // $content = encodeLinks($content);
    ## Fill text and html versions depending on given versions.
    if ($cached[$messageid]["htmlformatted"]) {
        if (!$cached[$messageid]["textcontent"]) {
            $textcontent = stripHTML($content);
        } else {
            $textcontent = $cached[$messageid]["textcontent"];
        }
        $htmlcontent = $content;
    } else {
        #    $textcontent = $content;
        if (!$cached[$messageid]["textcontent"]) {
            $textcontent = $content;
        } else {
            $textcontent = $cached[$messageid]["textcontent"];
        }
        $htmlcontent = parseText($content);
    }
    $defaultstyle = getConfig("html_email_style");
    $adddefaultstyle = 0;
    if ($cached[$messageid]["template"]) {
        # template used
        $htmlmessage = eregi_replace("\\[CONTENT\\]", $htmlcontent, $cached[$messageid]["template"]);
    } else {
        # no template used
        $htmlmessage = $htmlcontent;
        $adddefaultstyle = 1;
    }
    $textmessage = $textcontent;
    ## Parse placeholders
    #0013076: Blacklisting posibility for unknown users
    foreach (array("forwardform", "subscribe", "preferences", "unsubscribe", "signature", 'blacklist') as $item) {
        if (eregi('\\[' . $item . '\\]', $htmlmessage, $regs)) {
            $htmlmessage = eregi_replace('\\[' . $item . '\\]', $html[$item], $htmlmessage);
            //      unset($html[$item]); //ASK: Why was this done? It breaks placeholders in the footer
        }
        if (eregi('\\[' . $item . '\\]', $textmessage, $regs)) {
            $textmessage = eregi_replace('\\[' . $item . '\\]', $text[$item], $textmessage);
            //      unset($text[$item]);
        }
    }
    #0013076: Blacklisting posibility for unknown users
    foreach (array("forward", "forwardurl", "subscribeurl", "preferencesurl", "unsubscribeurl", 'blacklisturl') as $item) {
        if (eregi('\\[' . $item . '\\]', $htmlmessage, $regs)) {
            $htmlmessage = eregi_replace('\\[' . $item . '\\]', $html[$item], $htmlmessage);
        }
        if (eregi('\\[' . $item . '\\]', $textmessage, $regs)) {
            $textmessage = eregi_replace('\\[' . $item . '\\]', $text[$item], $textmessage);
        }
    }
    if ($hash != 'forwarded') {
        $text['footer'] = $cached[$messageid]["footer"];
        $html['footer'] = $cached[$messageid]["footer"];
    } else {
        #0013076: different content when forwarding 'to a friend'
        if (FORWARD_ALTERNATIVE_CONTENT) {
            $text['footer'] = stripslashes($messagedata["forwardfooter"]);
        } else {
            $text['footer'] = getConfig('forwardfooter');
        }
        $html['footer'] = $text['footer'];
    }
    $text["footer"] = eregi_replace("\\[SUBSCRIBE\\]", $text["subscribe"], $text['footer']);
    $html["footer"] = eregi_replace("\\[SUBSCRIBE\\]", $html["subscribe"], $html['footer']);
    $text["footer"] = eregi_replace("\\[PREFERENCES\\]", $text["preferences"], $text["footer"]);
    $html["footer"] = eregi_replace("\\[PREFERENCES\\]", $html["preferences"], $html["footer"]);
    $text["footer"] = eregi_replace("\\[FORWARD\\]", $text["forward"], $text["footer"]);
    $html["footer"] = eregi_replace("\\[FORWARD\\]", $html["forward"], $html["footer"]);
    $html["footer"] = eregi_replace("\\[FORWARDFORM\\]", $html["forwardform"], $html["footer"]);
    if (sizeof($forwardedby) && isset($forwardedby['email'])) {
        $htmlmessage = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $htmlmessage);
        $textmessage = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $textmessage);
        $html["footer"] = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $html["footer"]);
        $text["footer"] = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $text["footer"]);
        $text["footer"] = eregi_replace("\\[BLACKLIST\\]", $text["blacklist"], $text['footer']);
        $html["footer"] = eregi_replace("\\[BLACKLIST\\]", $html["blacklist"], $html['footer']);
        $text["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $text["blacklist"], $text['footer']);
        $html["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $html["blacklist"], $html['footer']);
    } else {
        $text["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $text["unsubscribe"], $text['footer']);
        $html["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $html["unsubscribe"], $html['footer']);
    }
    $html["footer"] = '<div class="emailfooter">' . nl2br($html["footer"]) . '</div>';
    if (eregi("\\[FOOTER\\]", $htmlmessage)) {
        $htmlmessage = eregi_replace("\\[FOOTER\\]", $html["footer"], $htmlmessage);
    } elseif ($html["footer"]) {
        $htmlmessage = addHTMLFooter($htmlmessage, '<br /><br />' . $html["footer"]);
    }
    if (eregi("\\[SIGNATURE\\]", $htmlmessage)) {
        $htmlmessage = eregi_replace("\\[SIGNATURE\\]", $html["signature"], $htmlmessage);
    } elseif ($html["signature"]) {
        $htmlmessage .= '<br />' . $html["signature"];
    }
    if (eregi("\\[FOOTER\\]", $textmessage)) {
        $textmessage = eregi_replace("\\[FOOTER\\]", $text["footer"], $textmessage);
    } else {
        $textmessage .= "\n\n" . $text["footer"];
    }
    if (eregi("\\[SIGNATURE\\]", $textmessage)) {
        $textmessage = eregi_replace("\\[SIGNATURE\\]", $text["signature"], $textmessage);
    } else {
        $textmessage .= "\n" . $text["signature"];
    }
    #  $req = Sql_Query(sprintf('select filename,data from %s where template = %d',
    #    $GLOBALS["tables"]["templateimage"],$cached[$messageid]["templateid"]));
    $htmlmessage = eregi_replace("\\[USERID\\]", $hash, $htmlmessage);
    $textmessage = eregi_replace("\\[USERID\\]", $hash, $textmessage);
    $htmlmessage = preg_replace("/\\[USERTRACK\\]/i", '<img src="' . $GLOBALS['scheme'] . '://' . $website . $GLOBALS["pageroot"] . '/ut.php?u=' . $hash . '&m=' . $messageid . '" width="1" height="1" border="0">', $htmlmessage, 1);
    $htmlmessage = eregi_replace("\\[USERTRACK\\]", '', $htmlmessage);
    if ($listowner) {
        $att_req = Sql_Query("select name,value from {$GLOBALS["tables"]["adminattribute"]},{$GLOBALS["tables"]["admin_attribute"]} where {$GLOBALS["tables"]["adminattribute"]}.id = {$GLOBALS["tables"]["admin_attribute"]}.adminattributeid and {$GLOBALS["tables"]["admin_attribute"]}.adminid = {$listowner}");
        while ($att = Sql_Fetch_Array($att_req)) {
            $htmlmessage = preg_replace("#\\[LISTOWNER." . strtoupper(preg_quote($att["name"])) . "\\]#", $att["value"], $htmlmessage);
        }
    }
    if (is_array($GLOBALS["default_config"])) {
        foreach ($GLOBALS["default_config"] as $key => $val) {
            if (is_array($val)) {
                $htmlmessage = eregi_replace("\\[{$key}\\]", getConfig($key), $htmlmessage);
                $textmessage = eregi_replace("\\[{$key}\\]", getConfig($key), $textmessage);
            }
        }
    }
    ## RSS
    if (ENABLE_RSS && sizeof($rssitems)) {
        $rssentries = array();
        $request = join(",", $rssitems);
        $texttemplate = getConfig("rsstexttemplate");
        $htmltemplate = getConfig("rsshtmltemplate");
        $textseparatortemplate = getConfig("rsstextseparatortemplate");
        $htmlseparatortemplate = getConfig("rsshtmlseparatortemplate");
        $req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem"]} where id in ({$request}) order by list,added");
        $curlist = "";
        while ($row = Sql_Fetch_array($req)) {
            if ($curlist != $row["list"]) {
                $row["listname"] = ListName($row["list"]);
                $curlist = $row["list"];
                $rssentries["text"] .= parseRSSTemplate($textseparatortemplate, $row);
                $rssentries["html"] .= parseRSSTemplate($htmlseparatortemplate, $row);
            }
            $data_req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem_data"]} where itemid = {$row["id"]}");
            while ($data = Sql_Fetch_Array($data_req)) {
                $row[$data["tag"]] = $data["data"];
            }
            $rssentries["text"] .= stripHTML(parseRSSTemplate($texttemplate, $row));
            $rssentries["html"] .= parseRSSTemplate($htmltemplate, $row);
        }
        $htmlmessage = eregi_replace("\\[RSS\\]", $rssentries["html"], $htmlmessage);
        $textmessage = eregi_replace("\\[RSS\\]", $rssentries["text"], $textmessage);
    }
    if (is_array($userdata)) {
        foreach ($userdata as $name => $value) {
            if (eregi("\\[" . $name . "\\]", $htmlmessage, $regs)) {
                $htmlmessage = eregi_replace("\\[" . $name . "\\]", $value, $htmlmessage);
            }
            if (eregi("\\[" . $name . "\\]", $textmessage, $regs)) {
                $textmessage = eregi_replace("\\[" . $name . "\\]", $value, $textmessage);
            }
        }
    }
    $destinationemail = '';
    if (is_array($user_att_values)) {
        foreach ($user_att_values as $att_name => $att_value) {
            if (eregi("\\[" . $att_name . "\\]", $htmlmessage, $regs)) {
                # the value may be a multiline textarea field
                $htmlatt_value = str_replace("\n", "<br/>\n", $att_value);
                $htmlmessage = eregi_replace("\\[" . $att_name . "\\]", $htmlatt_value, $htmlmessage);
            }
            if (eregi("\\[" . $att_name . "\\]", $textmessage, $regs)) {
                $textmessage = eregi_replace("\\[" . $att_name . "\\]", $att_value, $textmessage);
            }
            # @@@ undocumented, use alternate field for real email to send to
            if (isset($GLOBALS["alternate_email"]) && strtolower($att_name) == strtolower($GLOBALS["alternate_email"])) {
                $destinationemail = $att_value;
            }
        }
    }
    if (!$destinationemail) {
        $destinationemail = $email;
    }
    if (!ereg('@', $destinationemail) && isset($GLOBALS["expand_unqualifiedemail"])) {
        $destinationemail .= $GLOBALS["expand_unqualifiedemail"];
    }
    if (eregi("\\[LISTS\\]", $htmlmessage)) {
        $lists = "";
        $listsarr = array();
        $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d', $GLOBALS["tables"]["list"], $GLOBALS["tables"]["listuser"], $user_system_values["id"]));
        while ($row = Sql_Fetch_Row($req)) {
            array_push($listsarr, $row[0]);
        }
        $lists_html = join('<br/>', $listsarr);
        $lists_text = join("\n", $listsarr);
        $htmlmessage = ereg_replace("\\[LISTS\\]", $lists_html, $htmlmessage);
        $textmessage = ereg_replace("\\[LISTS\\]", $lists_text, $textmessage);
    }
    ## click tracking
    # for now we won't click track forwards, as they are not necessarily users, so everything would fail
    if (CLICKTRACK && $hash != 'forwarded') {
        $urlbase = '';
        # let's leave this for now
        /*
        if (preg_match('/<base href="(.*)"([^>]*)>/Umis',$htmlmessage,$regs)) {
          $urlbase = $regs[1];
        } else {
          $urlbase = '';
        }
        #    print "URLBASE: $urlbase<br/>";
        */
        # convert html message
        #    preg_match_all('/<a href="?([^> "]*)"?([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links);
        preg_match_all('/<a(.*)href=["\'](.*)["\']([^>]*)>(.*)<\\/a>/Umis', $htmlmessage, $links);
        # to process the Yahoo webpage with base href and link like <a href=link> we'd need this one
        #    preg_match_all('/<a href=([^> ]*)([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links);
        $clicktrack_root = sprintf('%s://%s/lt.php', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"]);
        for ($i = 0; $i < count($links[2]); $i++) {
            $link = cleanUrl($links[2][$i]);
            $link = str_replace('"', '', $link);
            if (preg_match('/\\.$/', $link)) {
                $link = substr($link, 0, -1);
            }
            $linkid = 0;
            #      print "LINK: $link<br/>";
            if ((preg_match('/^http|ftp/', $link) || preg_match('/^http|ftp/', $urlbase)) && $link != 'http://www.phplist.com' && !strpos($link, $clicktrack_root)) {
                # take off personal uids
                $url = cleanUrl($link, array('PHPSESSID', 'uid'));
                #        $url = preg_replace('/&uid=[^\s&]+/','',$link);
                #        if (!strpos('http:',$link)) {
                #          $link = $urlbase . $link;
                #        }
                $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
          values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, addslashes($link)));
                $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
        ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link));
                $linkid = $req[0];
                $masked = "H|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask;
                $masked = urlencode(base64_encode($masked));
                $newlink = sprintf('<a%shref="%s://%s/lt.php?id=%s" %s>%s</a>', $links[1][$i], $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked, $links[3][$i], $links[4][$i]);
                $htmlmessage = str_replace($links[0][$i], $newlink, $htmlmessage);
            }
        }
        # convert Text message
        # first find occurances of our top domain, to avoid replacing them later
        # hmm, this is no point, it's not just *our* topdomain, but any
        if (0) {
            preg_match_all('#(https?://' . $GLOBALS['website'] . '/?)\\s+#mis', $textmessage, $links);
            #    preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links);
            #    preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links);
            for ($i = 0; $i < count($links[1]); $i++) {
                # not entirely sure why strtolower was used, but it seems to break things http://mantis.tincan.co.uk/view.php?id=4406
                #      $link = strtolower(cleanUrl($links[1][$i]));
                $link = cleanUrl($links[1][$i]);
                if (preg_match('/\\.$/', $link)) {
                    $link = substr($link, 0, -1);
                }
                $linkid = 0;
                if (preg_match('/^http|ftp/', $link) && $link != 'http://www.phplist.com' && !strpos($link, $clicktrack_root)) {
                    $url = cleanUrl($link, array('PHPSESSID', 'uid'));
                    $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
          values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, $link));
                    $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
        ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link));
                    $linkid = $req[0];
                    $masked = "T|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask;
                    $masked = urlencode(base64_encode($masked));
                    $newlink = sprintf('%s://%s/lt.php?id=%s', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked);
                    $textmessage = str_replace($links[0][$i], '<' . $newlink . '>', $textmessage);
                }
            }
        }
        #now find the rest
        # @@@ needs to expand to find complete urls like:
        #http://user:password@www.web-site.com:1234/document.php?parameter=something&otherpar=somethingelse#anchor
        # or secure
        #https://user:password@www.website.com:2345/document.php?parameter=something%20&otherpar=somethingelse#anchor
        preg_match_all('#(https?://[^\\s\\>\\}\\,]+)#mis', $textmessage, $links);
        #    preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links);
        #    preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links);
        ## sort the results in reverse order, so that they are replaced correctly
        rsort($links[1]);
        $newlinks = array();
        for ($i = 0; $i < count($links[1]); $i++) {
            $link = cleanUrl($links[1][$i]);
            if (preg_match('/\\.$/', $link)) {
                $link = substr($link, 0, -1);
            }
            $linkid = 0;
            if (preg_match('/^http|ftp/', $link) && $link != 'http://www.phplist.com') {
                # && !strpos($link,$clicktrack_root)) {
                $url = cleanUrl($link, array('PHPSESSID', 'uid'));
                $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward)
          values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, $link));
                $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s"
        ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link));
                $linkid = $req[0];
                $masked = "T|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask;
                $masked = urlencode(base64_encode($masked));
                $newlinks[$linkid] = sprintf('%s://%s/lt.php?id=%s', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked);
                #        print $links[0][$i] .' -> '.$newlink.'<br/>';
                $textmessage = str_replace($links[1][$i], '[%%%' . $linkid . '%%%]', $textmessage);
            }
        }
        foreach ($newlinks as $linkid => $newlink) {
            $textmessage = str_replace('[%%%' . $linkid . '%%%]', $newlink, $textmessage);
        }
    }
    #
    if (eregi("\\[LISTS\\]", $htmlmessage)) {
        $lists = "";
        $listsarr = array();
        $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d', $tables["list"], $tables["listuser"], $user_system_values["id"]));
        while ($row = Sql_Fetch_Row($req)) {
            array_push($listsarr, $row[0]);
        }
        $lists_html = join('<br/>', $listsarr);
        $lists_text = join("\n", $listsarr);
        $htmlmessage = ereg_replace("\\[LISTS\\]", $lists_html, $htmlmessage);
        $textmessage = ereg_replace("\\[LISTS\\]", $lists_text, $textmessage);
    }
    #0011996: forward to friend - personal message
    if (FORWARD_PERSONAL_NOTE_SIZE && ($hash = 'forwarded' && !empty($forwardedby['personalNote']))) {
        $htmlmessage = nl2br($forwardedby['personalNote']) . '<br/>' . $htmlmessage;
        $textmessage = $forwardedby['personalNote'] . "\n" . $textmessage;
    }
    ## remove any existing placeholders
    $htmlmessage = eregi_replace("\\[[A-Z\\. ]+\\]", "", $htmlmessage);
    $textmessage = eregi_replace("\\[[A-Z\\. ]+\\]", "", $textmessage);
    ## check that the HTML message as proper <head> </head> and <body> </body> tags
    # some readers fail when it doesn't
    if (!preg_match("#<body.*</body>#ims", $htmlmessage)) {
        $htmlmessage = '<body>' . $htmlmessage . '</body>';
    }
    if (!preg_match("#<head>.*</head>#ims", $htmlmessage)) {
        if (!$adddefaultstyle) {
            $defaultstyle = "";
        }
        $htmlmessage = '<head>
        <meta content="text/html;charset=' . $cached[$messageid]["html_charset"] . '" http-equiv="Content-Type">
        <title></title>' . $defaultstyle . '</head>' . $htmlmessage;
    }
    if (!preg_match("#<html>.*</html>#ims", $htmlmessage)) {
        $htmlmessage = '<html>' . $htmlmessage . '</html>';
    }
    # particularly Outlook seems to have trouble if it is not \r\n
    # reports have come that instead this creates lots of trouble
    # this is now done in the global sendMail function, so it is not
    # necessary here
    #  if (USE_CARRIAGE_RETURNS) {
    #    $htmlmessage = preg_replace("/\r?\n/", "\r\n", $htmlmessage);
    #    $textmessage = preg_replace("/\r?\n/", "\r\n", $textmessage);
    #  }
    ## build the email
    if (!PHPMAILER) {
        $mail = new html_mime_mail(array('X-Mailer: PHPlist v' . VERSION, "X-MessageId: {$messageid}", "X-ListMember: {$email}", "Precedence: bulk", "List-Help: <" . $text["preferences"] . ">", "List-Unsubscribe: <" . $text["unsubscribe"] . ">", "List-Subscribe: <" . getConfig("subscribeurl") . ">", "List-Owner: <mailto:" . getConfig("admin_address") . ">"));
    } else {
        $mail = new PHPlistMailer($messageid, $destinationemail);
        if ($forwardedby) {
            $mail->add_timestamp();
        }
        #$mail->IsSMTP();
    }
    list($dummy, $domaincheck) = split('@', $destinationemail);
    $text_domains = explode("\n", trim(getConfig("alwayssendtextto")));
    if (in_array($domaincheck, $text_domains)) {
        $htmlpref = 0;
        if (VERBOSE) {
            output($GLOBALS['I18N']->get('sendingtextonlyto') . " {$domaincheck}");
        }
    }
    list($dummy, $domaincheck) = split('@', $email);
    $text_domains = explode("\n", trim(getConfig("alwayssendtextto")));
    if (in_array($domaincheck, $text_domains)) {
        $htmlpref = 0;
        if (VERBOSE) {
            output("Sending text only to {$domaincheck}");
        }
    }
    # so what do we actually send?
    switch ($cached[$messageid]["sendformat"]) {
        case "HTML":
            //      # send html to users who want it and text to everyone else
            //      if ($htmlpref) {
            //        Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid");
            //        if (ENABLE_RSS && sizeof($rssitems))
            //          updateRSSStats($rssitems,"ashtml");
            //      #  dbg("Adding HTML ".$cached[$messageid]["templateid"]);
            //        $mail->add_html($htmlmessage,"",$cached[$messageid]["templateid"]);
            //        addAttachments($messageid,$mail,"HTML");
            //      } else {
            //        Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
            //        if (ENABLE_RSS && sizeof($rssitems))
            //          updateRSSStats($rssitems,"astext");
            //        $mail->add_text($textmessage);
            //        addAttachments($messageid,$mail,"text");
            //      }
            //      break;
        //      # send html to users who want it and text to everyone else
        //      if ($htmlpref) {
        //        Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid");
        //        if (ENABLE_RSS && sizeof($rssitems))
        //          updateRSSStats($rssitems,"ashtml");
        //      #  dbg("Adding HTML ".$cached[$messageid]["templateid"]);
        //        $mail->add_html($htmlmessage,"",$cached[$messageid]["templateid"]);
        //        addAttachments($messageid,$mail,"HTML");
        //      } else {
        //        Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid");
        //        if (ENABLE_RSS && sizeof($rssitems))
        //          updateRSSStats($rssitems,"astext");
        //        $mail->add_text($textmessage);
        //        addAttachments($messageid,$mail,"text");
        //      }
        //      break;
        case "both":
        case "text and HTML":
            # send one big file to users who want html and text to everyone else
            if ($htmlpref) {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = {$messageid}");
                if (ENABLE_RSS && sizeof($rssitems)) {
                    updateRSSStats($rssitems, "ashtml");
                }
                #  dbg("Adding HTML ".$cached[$messageid]["templateid"]);
                $mail->add_html($htmlmessage, $textmessage, $cached[$messageid]["templateid"]);
                addAttachments($messageid, $mail, "HTML");
            } else {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}");
                if (ENABLE_RSS && sizeof($rssitems)) {
                    updateRSSStats($rssitems, "astext");
                }
                $mail->add_text($textmessage);
                addAttachments($messageid, $mail, "text");
            }
            break;
        case "PDF":
            # send a PDF file to users who want html and text to everyone else
            if (ENABLE_RSS && sizeof($rssitems)) {
                updateRSSStats($rssitems, "astext");
            }
            if ($htmlpref) {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set aspdf = aspdf + 1 where id = {$messageid}");
                $pdffile = createPdf($textmessage);
                if (is_file($pdffile) && filesize($pdffile)) {
                    $fp = fopen($pdffile, "r");
                    if ($fp) {
                        $contents = fread($fp, filesize($pdffile));
                        fclose($fp);
                        unlink($pdffile);
                        $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
              <html>
              <head>
                <title></title>
              </head>
              <body>
              <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed>
              </body>
              </html>';
                        #            $mail->add_html($html,$textmessage);
                        #            $mail->add_text($textmessage);
                        $mail->add_attachment($contents, "message.pdf", "application/pdf");
                    }
                }
                addAttachments($messageid, $mail, "HTML");
            } else {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}");
                $mail->add_text($textmessage);
                addAttachments($messageid, $mail, "text");
            }
            break;
        case "text and PDF":
            if (ENABLE_RSS && sizeof($rssitems)) {
                updateRSSStats($rssitems, "astext");
            }
            # send a PDF file to users who want html and text to everyone else
            if ($htmlpref) {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set astextandpdf = astextandpdf + 1 where id = {$messageid}");
                $pdffile = createPdf($textmessage);
                if (is_file($pdffile) && filesize($pdffile)) {
                    $fp = fopen($pdffile, "r");
                    if ($fp) {
                        $contents = fread($fp, filesize($pdffile));
                        fclose($fp);
                        unlink($pdffile);
                        $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
              <html>
              <head>
                <title></title>
              </head>
              <body>
              <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed>
              </body>
              </html>';
                        #           $mail->add_html($html,$textmessage);
                        $mail->add_text($textmessage);
                        $mail->add_attachment($contents, "message.pdf", "application/pdf");
                    }
                }
                addAttachments($messageid, $mail, "HTML");
            } else {
                Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}");
                $mail->add_text($textmessage);
                addAttachments($messageid, $mail, "text");
            }
            break;
        case "text":
        default:
            # send as text
            if (ENABLE_RSS && sizeof($rssitems)) {
                updateRSSStats($rssitems, "astext");
            }
            Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}");
            $mail->add_text($textmessage);
            addAttachments($messageid, $mail, "text");
            break;
    }
    $mail->build_message(array("html_charset" => $cached[$messageid]["html_charset"], "html_encoding" => HTMLEMAIL_ENCODING, "text_charset" => $cached[$messageid]["text_charset"], "text_encoding" => TEXTEMAIL_ENCODING));
    if (!TEST) {
        if ($hash != 'forwarded' || !sizeof($forwardedby)) {
            $fromname = $cached[$messageid]["fromname"];
            $fromemail = $cached[$messageid]["fromemail"];
            $subject = $cached[$messageid]["subject"];
        } else {
            $fromname = '';
            $fromemail = $forwardedby['email'];
            $subject = $GLOBALS['strFwd'] . ': ' . $cached[$messageid]["subject"];
        }
        if (!$mail->send("", $destinationemail, $fromname, $fromemail, $subject)) {
            logEvent("Error sending message {$messageid} to {$email} ({$destinationemail})");
            return 0;
        } else {
            return 1;
        }
    }
    return 0;
}
Example #29
0
 public function decryptMessage($from, $ciphertext, $type, $id, $t, $retry_from = null, $skip_unpad = false)
 {
     $version = '1';
     $this->parent->debugPrint("\n-> Decrypted Message: ");
     if ($type == 'pkmsg') {
         if (in_array(ExtractNumber($from), $this->parent->getv2Jids())) {
             $version = '2';
         }
         try {
             $preKeyWhisperMessage = new PreKeyWhisperMessage(null, null, null, null, null, null, null, $ciphertext);
             $sessionCipher = $this->parent->getSessionCipher(ExtractNumber($from));
             $plaintext = $sessionCipher->decryptPkmsg($preKeyWhisperMessage);
             if ($version == '2' && !$skip_unpad) {
                 $plaintext = unpadV2Plaintext($plaintext);
             }
             $this->parent->debugPrint(parseText($plaintext) . "\n\n");
             return $plaintext;
         } catch (Exception $e) {
             if ($e instanceof UntrustedIdentityException) {
                 $this->parent->getAxolotlStore()->clearRecipient(ExtractNumber($from));
             }
             $this->parent->debugPrint($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
             // if ($e->getMessage() != "Null values!"){
             $this->parent->debugPrint("Message {$id} could not be decrypted, sending retry.\n\n");
             $participant = null;
             if ($retry_from != null) {
                 if (strpos($retry_from, '-') !== false) {
                     $participant = $from;
                 }
                 $from = $retry_from;
             }
             //$this->sendRetry($from, $id, $t, $participant);
             return false;
             //}
         }
     } elseif ($type == 'msg') {
         if (in_array(ExtractNumber($from), $this->parent->getv2Jids())) {
             $version = '2';
         }
         try {
             $whisperMessage = new WhisperMessage(null, null, null, null, null, null, null, null, $ciphertext);
             $sessionCipher = $this->parent->getSessionCipher(ExtractNumber($from));
             $plaintext = $sessionCipher->decryptMsg($whisperMessage);
             if ($version == '2' && !$skip_unpad) {
                 $plaintext = unpadV2Plaintext($plaintext);
             }
             $this->parent->debugPrint(parseText($plaintext) . "\n\n");
             return $plaintext;
         } catch (Exception $e) {
             $this->parent->debugPrint($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
             $this->parent->debugPrint("Message {$id} could not be decrypted, sending retry.\n\n");
             if ($retry_from != null) {
                 $from = $retry_from;
             }
             //$this->sendRetry($from, $id, $t);
             return false;
         }
     } elseif ($type == 'skmsg') {
         if (in_array($from[1], $this->parent->v2Jids)) {
             $version = '2';
         }
         try {
             $groupCipher = $this->parent->getGroupCipher(ExtractNumber($from[0]) . ':' . $from[1]);
             $plaintext = $groupCipher->decrypt($ciphertext);
             if ($version == '2' && !$skip_unpad) {
                 $plaintext = unpadV2Plaintext($plaintext);
             }
             $this->parent->debugPrint("Message {$id} decrypted to " . parseText($plaintext) . "\n\n");
             return $plaintext;
         } catch (Exception $e) {
             $this->parent->debugPrint($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
             if ($retry_from != null) {
                 $from = $retry_from;
             }
             $this->parent->sendRetry($this->node, $this->parent->getJID($from[0]), $id, $t);
             return false;
         }
     }
 }
Example #30
0
 function parse($args, $page)
 {
     global $action, $OdtParseEngine, $odtUrlImages;
     global $OpenOfficeMacroUnzipCmd, $OpenOfficeMacroZipCmd, $pagestore;
     global $parseOdtTableStyle, $ScriptBase, $ScriptName, $TempDir;
     global $UserName, $WorkingDirectory;
     if ($action != 'macro') {
         return;
     }
     if (!$this->enable) {
         die('Save as OpenOffice Error: This feature has not yet been ' . 'enabled by the administrator.');
     }
     require 'parse/main.php';
     require 'parse/openofficeparse.php';
     # read page
     $pg = $pagestore->page($page);
     $pg->read();
     # creates temporary directory
     $uniqueDir = uniqid($page);
     $dir = $TempDir . '/' . $uniqueDir;
     if (!mkdir($dir)) {
         die('Save as OpenOffice Error: Failed to create temporary ' . 'directory.');
     }
     # unzip template file
     if (!file_exists("{$WorkingDirectory}/template/OpenOffice.odt")) {
         $this->tempFileCleanup($dir);
         die('Save as OpenOffice Error: Missing OpenOffice.odt template ' . 'file.');
     }
     exec("cd {$dir}; {$OpenOfficeMacroUnzipCmd} {$WorkingDirectory}/template/OpenOffice.odt;");
     if (!file_exists($dir . '/meta.xml') || !file_exists($dir . '/content.xml')) {
         $this->tempFileCleanup($dir);
         die('Save as OpenOffice Error: Missing meta.xml or content.xml ' . 'files from unzipped template.');
     }
     # meta.xml
     $content = file_get_contents($dir . '/meta.xml');
     $content = str_replace('<meta:initial-creator>', '<meta:initial-creator>' . $UserName, $content);
     $content = str_replace('<dc:creator>', '<dc:creator>' . $UserName, $content);
     $content = str_replace('<meta:creation-date>', '<meta:creation-date>' . date('Y-m-dTG:i:s'), $content);
     $content = str_replace('<dc:date>', '<dc:date>' . date('Y-m-dTG:i:s'), $content);
     $content = str_replace('<dc:title>', '<dc:title>' . $page, $content);
     $content = str_replace('<meta:generator>', '<meta:generator>GracefulTavi ' . GRACEFULTAVI_VERSION, $content);
     $description = "Generated by GracefulTavi " . GRACEFULTAVI_VERSION . " on " . date('F j, Y') . "\n" . "From: {$ScriptBase}?{$page}\n" . "Revision number: " . $pg->version . "\n\n" . "About GracefulTavi: http://open.nit.ca/wiki/?GracefulTavi\n";
     $content = str_replace('<dc:description>', '<dc:description>' . $description, $content);
     if ($handle = fopen($dir . '/meta.xml', 'w')) {
         $fw = fwrite($handle, $content);
     }
     if ($handle === false || $fw === false || $fw == 0) {
         $this->tempFileCleanup($dir);
         die('Save as OpenOffice Error: Failed to update meta.xml.');
     }
     fclose($handle);
     # content.xml
     $text = utf8_encode(html_entity_decode("=```{$page}```=\n\n" . $pg->text));
     $odtUrlImages = array();
     $text = parseText($text, $OdtParseEngine, $page);
     $text = preg_replace('/\\n/', '', $text);
     // document body
     $content = file_get_contents($dir . '/content.xml');
     $content = str_replace('<text:p text:style-name="Standard"/>', '<text:p text:style-name="Standard">' . $text . '</text:p>', $content);
     // table styles
     if ($parseOdtTableStyle) {
         $content = str_replace('</office:automatic-styles>', $parseOdtTableStyle . '</office:automatic-styles>', $content);
     }
     // cleanup
     // paragraph
     $content = preg_replace('/<text:p text:style-name="(\\w+)"><\\/text:p>/', '<text:p text:style-name="\\1"/>', $content);
     $content = preg_replace('/(<text:p text:style-name="(\\w+)"\\/>)+/', '\\1', $content);
     // remove empty lines at top and bottom of document
     $content = preg_replace('/<\\/text:sequence-decls><text:p text:style-name="(\\w+)"\\/>/', '</text:sequence-decls>', $content);
     $content = preg_replace('/<text:p text:style-name="(\\w+)"\\/><\\/office:text>/', '</office:text>', $content);
     // indents mess
     $content = preg_replace('/<\\/text:list><text:p text:style-name="\\w+"\\/><\\/text:list-item>/', '</text:list></text:list-item>', $content);
     $content = str_replace('</text:list-item></text:p><text:p text:style-name="Standard">' . '<text:list-item>', '</text:list-item><text:p text:style-name="Standard"/>' . '<text:list-item>', $content);
     if ($handle = fopen($dir . '/content.xml', 'w')) {
         $fw = fwrite($handle, $content);
     }
     if ($handle === false || $fw === false || $fw == 0) {
         $this->tempFileCleanup($dir);
         die('Save as OpenOffice Error: Failed to update content.xml.');
     }
     fclose($handle);
     # images handling
     foreach ($odtUrlImages as $img) {
         if (file_exists($img)) {
             $newName = $dir . '/Pictures/' . substr(basename($img), 32);
             if (!@rename($img, $newName)) {
                 $this->tempFileCleanup($dir);
                 die('Save as OpenOffice Error: Failed to move an image in ' . 'Pictures directory.');
             }
         }
     }
     # assemble and sends document
     exec("cd {$dir}; {$OpenOfficeMacroZipCmd} -r {$page}.odt *;");
     if (!file_exists("{$dir}/{$page}.odt")) {
         $this->tempFileCleanup($dir);
         die('Save as OpenOffice Error: Failed assembling final .odt file.');
     }
     header('Content-Type: application/vnd.oasis.opendocument.text; ' . 'name="' . $page . '.odt"');
     header('Content-Disposition: attachment; filename="' . $page . '.odt"');
     print file_get_contents("{$dir}/{$page}.odt");
     # cleanup
     $this->rmDirAll($dir);
     exit;
 }