Exemplo n.º 1
0
function macro_ShareButtons($formatter, $value = '', $params)
{
    global $DBInfo;
    $lang = $DBInfo->lang;
    $btn = _("Tweet");
    $link = $formatter->link_url($formatter->page->name);
    $href = qualifiedURL($link);
    $encoded_href = $href;
    $twitter_attr = '';
    $facebook_attr = 'data-layout="button_count"';
    $gplus_attr = ' data-size="medium"';
    if ($value == 'vertical' or $value == 'vert') {
        $twitter_attr = ' data-count="vertical"';
        $gplus_attr = ' data-size="tall"';
        $facebook_attr = 'data-layout="box_count"';
    }
    $twitter = <<<EOF
<a href="https://twitter.com/share" class="twitter-share-button" data-url="{$href}" data-lang="{$lang}" data-dnt="true"{$twitter_attr}>{$btn}</a>
EOF;
    $js = <<<EOF
<script type="text/javascript">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
EOF;
    $formatter->register_javascripts($js);
    $gplus = <<<EOF
<div class="g-plusone" data-href="{$href}"{$gplus_attr}></div>
EOF;
    $js = <<<EOF
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>
EOF;
    $formatter->register_javascripts($js);
    $js = <<<EOF
<script type="text/javascript">(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/ko_KR/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

EOF;
    $formatter->register_javascripts($js);
    $fb = <<<EOF
<div class="fb-like"
data-href="{$href}"
data-width="450"
data-action="recommend"
data-show-faces="false"
{$facebook_attr}
data-send="false"></div>
EOF;
    return '<div class="share-buttons">' . $fb . ' ' . $twitter . ' ' . $gplus . '</div>';
}
Exemplo n.º 2
0
function generate_image($formatter)
{
    global $DBInfo;
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $img_url = qualifiedURL($DBInfo->logo_img);
    return <<<IMAGE
<image>
  <title>{$DBInfo->sitename}</title>
  <link>{$url}</link>
  <url>{$img_url}</url>
</image>

IMAGE;
}
Exemplo n.º 3
0
function do_post_savepage($formatter, $options)
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] != 'POST' || !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        $options['button_preview'] = 1;
        // force preview
    }
    if (isset($_FILES['upfile']) and is_array($_FILES) or isset($options['MYFILES']) and is_array($options['MYFILES'])) {
        $retstr = false;
        $options['retval'] =& $retstr;
        include_once 'plugin/UploadFile.php';
        do_uploadfile($formatter, $options);
    }
    $savetext = $options['savetext'];
    $datestamp = $options['datestamp'];
    $hash = $options['hash'];
    $button_preview = !empty($options['button_preview']) ? 1 : 0;
    if ($button_preview) {
        $formatter->preview = 1;
    }
    $button_merge = !empty($options['button_merge']) ? 1 : 0;
    $button_merge = !empty($options['manual_merge']) ? 2 : $button_merge;
    $button_merge = !empty($options['force_merge']) ? 3 : $button_merge;
    $button_diff = !empty($options['button_changes']) ? 1 : 0;
    if ($button_diff) {
        $button_preview = 1;
    }
    $savetext = preg_replace("/\r\n|\r/", "\n", $savetext);
    $savetext = _stripslashes($savetext);
    $comment = _stripslashes($options['comment']);
    $comment = trim($comment);
    $section_savetext = '';
    if (isset($options['section'])) {
        if ($formatter->page->exists()) {
            $sections = _get_sections($formatter->page->get_raw_body());
            if ($sections[$options['section']]) {
                if (substr($savetext, -1) != "\n") {
                    $savetext .= "\n";
                }
                $sections[$options['section']] = $savetext;
            }
            $section_savetext = $savetext;
            $savetext = implode('', $sections);
        }
    }
    if ($savetext and $savetext[strlen($savetext) - 1] != "\n") {
        $savetext .= "\n";
    }
    $new = md5($savetext);
    $menu = $formatter->link_to("#editor", _("Goto Editor"), ' class="preview-anchor"');
    $diff = '';
    if ($formatter->page->exists()) {
        # check difference
        $body = $formatter->page->get_raw_body();
        $body = preg_replace("/\r\n|\r/", "\n", $body);
        $orig = md5($body);
        if ($orig == $new) {
            // same text. just update datestamp
            unset($options['datestamp']);
            $datestamp = $formatter->page->mtime();
        }
        # check datestamp
        if ($formatter->page->mtime() > $datestamp) {
            $options['msg'] = sprintf(_("Someone else saved the page while you edited %s"), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
            $options['preview'] = 1;
            $options['conflict'] = 1;
            if ($button_merge) {
                $options['msg'] = sprintf(_("%s is merged with latest contents."), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
                $options['title'] = sprintf(_("%s is merged successfully"), _html_escape($options['page']));
                $merge = $formatter->get_merge($savetext);
                if (preg_grep('/^<<<<<<<$/', explode("\n", $merge))) {
                    $options['conflict'] = 2;
                    $options['title'] = sprintf(_("Merge conflicts are detected for %s !"), _html_escape($options['page']));
                    $options['msg'] = sprintf(_("Merge cancelled on %s."), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
                    $merge = preg_replace('/^>>>>>>>$/m', "=== /!\\ >>>>>>> " . _("NEW") . ' ===', $merge);
                    $merge = preg_replace('/^<<<<<<<$/m', "=== /!\\ <<<<<<< " . _("OLD") . ' ===', $merge);
                    $merge = preg_replace('/^=======$/m', "=== ======= ===", $merge);
                    if ($button_merge > 1) {
                        unset($options['datestamp']);
                        unset($options['section']);
                        unset($section_savetext);
                        $datestamp = $formatter->page->mtime();
                        $options['conflict'] = 0;
                        if ($button_merge == 2) {
                            $options['title'] = sprintf(_("Get merge conflicts for %s"), _html_escape($options['page']));
                            $options['msg'] = sprintf(_("Please resolve conflicts manually."));
                            if ($merge) {
                                $savetext = $merge;
                            }
                        } else {
                            $options['title'] = sprintf(_("Force merging for %s !"), _html_escape($options['page']));
                            $options['msg'] = sprintf(_("Please be careful, you could damage useful information."));
                        }
                    }
                } else {
                    $options['conflict'] = 0;
                    if ($merge) {
                        // successfully merged. reset datestamp
                        $savetext = $merge;
                        unset($options['datestamp']);
                        $datestamp = $formatter->page->mtime();
                    }
                }
                $button_preview = 1;
            } else {
                $options['title'] = _("Conflict error!");
                $button_preview = 1;
            }
            if ($options['conflict'] and !empty($merge)) {
                $diff = $formatter->get_diff($merge);
            } else {
                $diff = $formatter->get_diff($savetext);
            }
            // get diff
        } else {
            if ($datestamp > time()) {
                $options['msg'] = sprintf(_("Go back or return to %s"), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
                $formatter->send_header("", $options);
                $formatter->send_title(_("Invalid access"), "", $options);
                $formatter->send_footer();
                return;
            } else {
                if (!empty($DBInfo->use_savepage_hash)) {
                    // check hash
                    $ticket = getTicket($datestamp . $DBInfo->user->id, $_SERVER['REMOTE_ADDR']);
                    if ($hash != md5($ticket)) {
                        $formatter->send_header("", $options);
                        $formatter->send_title(_("Invalid access"), "", $options);
                        $formatter->send_footer();
                        return;
                    }
                }
            }
        }
    }
    if (empty($button_preview) && !empty($orig) && $orig == $new) {
        $options['msg'] = sprintf(_("Go back or return to %s"), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
        $formatter->send_header("", $options);
        $formatter->send_title(_("No difference found"), "", $options);
        $formatter->send_footer();
        return;
    }
    if ($comment && (function_exists('mb_strlen') and mb_strlen($comment, $DBInfo->charset) > 256) or strlen($comment) > 256) {
        //$options['msg']=sprintf(_("Go back or return to %s"),$formatter->link_tag($formatter->page->urlname,"",_html_escape($options['page'])));
        $options['title'] = _("Too long Comment");
        $button_preview = 1;
    }
    // XXX captcha
    $use_any = 0;
    if (!empty($DBInfo->use_textbrowsers)) {
        if (is_string($DBInfo->use_textbrowsers)) {
            $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        } else {
            $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        }
    }
    $ok_ticket = 0;
    if (!$button_preview and !$use_any and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') {
        if ($options['__seed'] and $options['check']) {
            $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4);
            if ($mycheck == $options['check']) {
                $ok_ticket = 1;
            } else {
                $options['msg'] = _("Invalid ticket !");
                $button_preview = 1;
            }
        } else {
            if (!$button_preview) {
                $options['msg'] = _("You need a ticket !");
            }
            $button_preview = 1;
        }
    } else {
        $ok_ticket = 1;
    }
    // XXX
    if (!$button_preview and $DBInfo->spam_filter) {
        $text = $savetext;
        $fts = preg_split('/(\\||,)/', $DBInfo->spam_filter);
        foreach ($fts as $ft) {
            $text = $formatter->filter_repl($ft, $text, $options);
        }
        if ($text != $savetext) {
            $button_preview = 1;
            $options['msg'] = _("Sorry, can not save page because some messages are blocked in this wiki.");
        } else {
            if ($options['id'] == 'Anonymous' and !empty($comment) and !empty($DBInfo->spam_comment_filter)) {
                // comment filter for anonymous users
                $cmt = $comment;
                $fts = preg_split('/(\\||,)/', $DBInfo->spam_comment_filter);
                // bad comments file
                $options['.badcontents'] = !empty($DBInfo->comments_badcontents) ? $DBInfo->comments_badcontents : null;
                foreach ($fts as $ft) {
                    $cmt = $formatter->filter_repl($ft, $cmt, $options);
                }
                if ($cmt != $comment) {
                    $button_preview = 1;
                    $options['msg'] = _("Sorry, can not save page because some messages are blocked in this wiki.");
                }
            }
        }
    }
    $formatter->page->set_raw_body($savetext);
    // check license agreement
    $ok_agreement = true;
    if (!empty($DBInfo->use_agreement)) {
        if ($options['id'] != 'Anonymous') {
            $ok_agreement = !empty($DBInfo->user->info['join_agreement']) && $DBInfo->user->info['join_agreement'] == 'agree';
            if ($ok_agreement && !empty($DBInfo->agreement_version)) {
                $ok_agreement = $DBInfo->user->info['join_agreement_version'] == $DBInfo->agreement_version;
            }
        } else {
            $ok_agreement = false;
        }
    }
    if (empty($button_preview) && !$ok_agreement && empty($options['license_agree'])) {
        $button_preview = 1;
        if ($options['id'] == 'Anonymous') {
            $options['msg'] = _("Anonymous user have to agree the contribution agreement for this wiki.");
        } else {
            $options['msg'] = _("Sorry, you have to agree the contribution agreement or the join agreement of this wiki.");
        }
    }
    // check full permission to edit
    $full_permission = true;
    if (!empty($DBInfo->no_full_edit_permission) or $options['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) {
        $full_permission = false;
    }
    // members always have full permission to edit
    if (in_array($options['id'], $DBInfo->members)) {
        $full_permission = true;
    }
    $minorfix = false;
    $options['editinfo'] = array();
    if (!$full_permission || !empty($DBInfo->use_abusefilter)) {
        // get diff
        if (!isset($diff[0])) {
            $diff = $formatter->get_diff($savetext);
        }
        // get total line numbers
        // test \n or \r or \r\n
        $crlf = "\n";
        if (preg_match("/(\r|\r\n|\n)\$/", $body, $match)) {
            $crlf = $match[1];
        }
        // count crlf
        $nline = substr_count($body, $crlf);
        // count diff lines, chars
        $changes = diffcount_lines($diff, $DBInfo->charset);
        // set return values
        $added = $changes[0];
        $deleted = $changes[1];
        $added_chars = $changes[2];
        $deleted_chars = $changes[3];
        // check minorfix
        $minorfix = $changes[4];
        $editinfo = array('add_lines' => $added, 'del_lines' => $deleted, 'add_chars' => $added_chars, 'del_chars' => $deleted_chars);
        $options['editinfo'] = $editinfo;
        if (!$button_diff) {
            $diff = '';
        }
    }
    if (!$full_permission) {
        $restricted = false;
        $delete_lines_restricted_ratio = !empty($DBInfo->allowed_max_lines_delete_ratio) ? $DBInfo->allowed_max_lines_delete_ratio : 0.5;
        if ($deleted > 0 && $deleted / $nline > $delete_lines_restricted_ratio) {
            $restricted = true;
        }
        // check the maximum number of characters allowed to add/delete
        $max_chars_add = !empty($DBInfo->allowed_max_chars_add) ? $DBInfo->allowed_max_chars_add : 300;
        $max_chars_del = !empty($DBInfo->allowed_max_chars_delete) ? $DBInfo->allowed_max_chars_delete : 180;
        if (!$restricted && ($added_chars > $max_chars_add || $deleted_chars > $max_chars_del)) {
            $restricted = true;
        }
        if ($restricted) {
            $options['title'] = _("You do not have full permission to edit this page on this wiki.");
            if ($options['id'] == 'Anonymous') {
                $options['msg'] = _("Anonymous user is restricted to delete a lot amount of page on this wiki.");
            } else {
                $options['msg'] = _("You are restricted to delete a lot amount of page on this wiki.");
            }
            $button_preview = true;
        }
    }
    if ($button_preview) {
        if (empty($options['title'])) {
            $options['title'] = sprintf(_("Preview of %s"), _html_escape($options['page']));
        }
        // http://stackoverflow.com/questions/1547884
        $header = '';
        if (!empty($DBInfo->preview_no_xss_protection)) {
            $header = 'X-XSS-Protection: 0';
        }
        $formatter->send_header($header, $options);
        $formatter->send_title("", "", $options);
        $options['preview'] = 1;
        $options['datestamp'] = $datestamp;
        $savetext = $section_savetext ? $section_savetext : $savetext;
        $options['savetext'] = $savetext;
        $formatter->preview = 1;
        $has_form = false;
        $options['has_form'] =& $has_form;
        $options['.minorfix'] = $minorfix;
        print '<div id="editor_area_wrap">' . macro_EditText($formatter, '', $options);
        echo $formatter->get_javascripts();
        if ($has_form and !empty($DBInfo->use_jsbuttons)) {
            $msg = _("Save");
            $onclick = ' onclick="submit_all_forms()"';
            $onclick1 = ' onclick="check_uploadform(this)"';
            echo "<div id='save-buttons'>\n";
            echo "<button type='button'{$onclick} tabindex='10'><span>{$msg}</span></button>\n";
            echo "<button type='button'{$onclick1} tabindex='11' name='button_preview' value='1'><span>" . _("Preview") . '</span></button>';
            if ($formatter->page->exists()) {
                echo "\n<button type='button'{$onclick1} tabindex='12' name='button_changes' value='1'><span>" . _("Show changes") . '</span></button>';
            }
            if ($button_preview) {
                echo ' ' . $formatter->link_to('#preview', _("Skip to preview"), ' class="preview-anchor"');
            }
            echo "</div>\n";
        }
        print '</div>';
        # XXX
        print $DBInfo->hr;
        print $menu;
        if ($button_diff and !isset($diff[0])) {
            $diff = $formatter->get_diff($options['section'] ? implode('', $sections) : $savetext);
            // get diff
            // strip diff header
            if (($p = strpos($diff, '@@')) !== false) {
                $diff = substr($diff, $p);
            }
        }
        if (isset($diff[0])) {
            echo "<div id='wikiDiffPreview'>\n";
            echo $formatter->processor_repl('diff', $diff, $options);
            //echo $formatter->macro_repl('Diff','',array('text'=>$diff,'type'=>'fancy'));
            echo "</div>\n";
        }
        print "<div id='wikiPreview'>\n";
        #$formatter->preview=1;
        $formatter->send_page($savetext);
        $formatter->preview = 0;
        print $DBInfo->hr;
        print "</div>\n";
        print $menu;
    } else {
        // check minorfix
        $options['.minorfix'] = $minorfix;
        if (empty($DBInfo->use_autodetect_minoredit)) {
            unset($options['.minorfix']);
        }
        if (!empty($options['category'])) {
            $savetext .= "----\n[[" . $options['category'] . "]]\n";
        }
        $options['minor'] = !empty($DBInfo->use_minoredit) ? $options['minor'] : 0;
        if ($options['minor']) {
            $user = $DBInfo->user;
            # get from COOKIE VARS
            if ($DBInfo->owners and in_array($user->id, $DBInfo->owners)) {
                $options['minor'] = 1;
            } else {
                $options['minor'] = 0;
            }
        }
        $formatter->page->write($savetext);
        $retval = array();
        $options['retval'] =& $retval;
        $ret = $DBInfo->savePage($formatter->page, $comment, $options);
        if ($ret != -1 and $DBInfo->notify and $options['minor'] != 1) {
            $options['noaction'] = 1;
            if (!function_exists('mail')) {
                $options['msg'] = sprintf(_("mail does not supported by default.")) . "<br />";
            } else {
                $ret2 = wiki_notify($formatter, $options);
                if ($ret2) {
                    $options['msg'] = sprintf(_("Sent notification mail.")) . "<br />";
                } else {
                    $options['msg'] = sprintf(_("No subscribers found.")) . "<br />";
                }
            }
        }
        if ($ret == -1) {
            if (!empty($options['retval']['msg'])) {
                $msg = $options['retval']['msg'];
            } else {
                $msg = sprintf(_("%s is not editable"), $formatter->link_tag($formatter->page->urlname, "", _html_escape($options['page'])));
            }
            $options['title'] = $msg;
        } else {
            $options['title'] = sprintf(_("%s is saved"), $formatter->link_tag($formatter->page->urlname, "?action=show", _html_escape($options['page'])));
        }
        $myrefresh = '';
        if (!empty($DBInfo->use_save_refresh)) {
            $lnk = $formatter->link_url($formatter->page->urlname, "?action=show");
            if (!empty($options['section'])) {
                $lnk .= '#sect-' . $options['section'];
            }
            if ($DBInfo->use_save_refresh > 0 || $ret == -1) {
                $sec = $DBInfo->use_save_refresh - 1;
                if ($sec < 0) {
                    $sec = 3;
                }
                $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
            } else {
                $myrefresh = array('Status: 302', 'Location: ' . qualifiedURL($lnk));
            }
        }
        $formatter->send_header($myrefresh, $options);
        if (is_array($myrefresh)) {
            return;
        }
        $formatter->send_title("", "", $options);
        $opt['pagelinks'] = 1;
        $opt['refresh'] = 1;
        $formatter->page->pi = null;
        // call get_instruction() again
        # re-generates pagelinks
        print "<div id='wikiContent'>\n";
        $formatter->send_page("", $opt);
        print "</div>\n";
    }
    $args['editable'] = 0;
    $formatter->send_footer($args, $options);
}
Exemplo n.º 4
0
function do_bbs($formatter, $options = array())
{
    global $DBInfo;
    $err = '';
    $args = array();
    if ($options['mode'] == 'rss') {
        #$formatter->send_header("Content-Type: text/xml",$options);
        header("Content-Type: application/xml");
        print macro_BBS($formatter, '', $options);
        return;
    }
    # load a config file
    $bname = $formatter->page->name;
    $conf0 = array();
    if (file_exists('config/bbs.' . $bname . '.php')) {
        $confname = 'bbs.' . $bname . '.php';
        $conf0 = _load_php_vars('config/bbs.default.php');
    } else {
        $confname = 'bbs.default.php';
    }
    $conf = _load_php_vars('config/' . $confname);
    $conf = array_merge($conf0, $conf);
    # check valid IP
    $check_ip = true;
    if ($conf['allowed_ip'] and in_array($options['mode'], array('edit', 'delete', 'new'))) {
        include_once 'lib/checkip.php';
        if (!check_ip($conf['allowed_ip'], $_SERVER['REMOTE_ADDR'])) {
            $options['title'] = sprintf(_("Your IP address is not allowed to %s at this BBS"), $options["mode"]);
            $check_ip = false;
        }
    }
    $check_pass = false;
    $MyBBS = macro_BBS($formatter, '', array('new' => 1));
    if ($options['id'] != 'Anonymous' and $options['mode'] == 'edit' and $options['no']) {
        $body = $MyBBS->getPage($options['no']);
        if ($body != null) {
            include_once 'lib/metadata.php';
            list($metas, $dummy) = _get_metadata($body);
            if ($metas['Name'] == $options['id']) {
                # XXX
                $check_pass = true;
            }
        }
    }
    # password check
    while ($options['no'] and ($options['mode'] == 'delete' or $options['mode'] == 'edit') and $_SERVER['REQUEST_METHOD'] == "POST") {
        # check admin(WikiMaster) password
        if (!$check_pass) {
            if ($DBInfo->admin_passwd) {
                $check_pass = $DBInfo->admin_passwd == crypt($options['pass'], $DBInfo->admin_passwd);
            } else {
                $check_pass = false;
            }
        }
        # check admin(BBSMaster) password
        if (!$check_pass and $conf['admin_passwd']) {
            $check_pass = $conf['admin_passwd'] == crypt($options['pass'], $conf['admin_passwd']);
        }
        while ($check_ip and $check_pass and $options['mode'] == 'delete') {
            if (($p = strpos($options['no'], ' ')) !== false) {
                $nids = explode(" ", $options['no']);
            } else {
                $nids = array($options['no']);
            }
            for ($i = 0, $sz = sizeof($nids); $i < $sz; $i++) {
                if ($MyBBS->hasPage($nids[$i])) {
                    $MyBBS->deletePage($nids[$i]);
                } else {
                    $MyBBS->deleteIndex($nids[$i]);
                }
            }
            $query = $options['p'] ? '&p=' . $options['p'] : '';
            $myrefresh = '';
            if ($DBInfo->use_save_refresh) {
                $sec = $DBInfo->use_save_refresh - 1;
                $lnk = $formatter->link_url($formatter->page->urlname, '?' . ($query ? $query : 'action=show'));
                $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
            }
            $options['msg'] = _("Successfully deleted.");
            $header = array("Expires: " . gmdate("D, d M Y H:i:s", 0) . " GMT");
            if ($myrefresh) {
                $header[] = $myrefresh;
            }
            $formatter->send_header($header, $options);
            $formatter->send_title("", "", $options);
            $formatter->send_footer("", $options);
            return;
        }
        break;
    }
    while ($options['mode'] == 'comment' and $options['savetext'] and $_SERVER['REQUEST_METHOD'] == "POST") {
        $query = 'no=' . $options['no'] . ($options['p'] ? '&p=' . $options['p'] : '');
        $myrefresh = '';
        if ($DBInfo->use_save_refresh) {
            $sec = $DBInfo->use_save_refresh - 1;
            $lnk = $formatter->link_url($formatter->page->urlname, '?' . $query);
            $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
        }
        $header = array("Expires: " . gmdate("D, d M Y H:i:s", 0) . " GMT");
        if ($myrefresh) {
            $header[] = $myrefresh;
        }
        $p = new WikiPage($options['page'] . ':' . $options['no'], $options);
        $formatter->page = $p;
        $options['page'] = $options['page'] . ':' . $options['no'];
        $options['minor'] = 1;
        # do not log
        $formatter->send_header($header, $options);
        $options['action_mode'] = 'ajax';
        $options['call'] = 1;
        $ret = $formatter->ajax_repl('comment', $options);
        if ($ret == false) {
            $options['msg'] = _("Fail to post comment.");
        }
        unset($options['action_mode']);
        $formatter->send_title("", "", $options);
        $formatter->send_footer("", $options);
        return;
        break;
    }
    if ($options['mode'] == 'delete') {
        $msg = sprintf(_("The article %s will be deleted."), $options['no']);
        $url = $formatter->link_url($formatter->page->urlname, '');
        $header = array("Expires: " . gmdate("D, d M Y H:i:s", 0) . " GMT");
        $formatter->send_header($header, $options);
        $formatter->send_title("", "", $options);
        print <<<EOF
<div class='deleteDialog'>
<form method='post' action='{$url}' >
<strong>{$msg}</strong>
<table border='0' width='20%'>
<tbody>
<tr><th>Password:</th><td><input type='password' style="width:200px" name='pass' /></td></tr>
</tbody>
</table>
<input type='hidden' name='no' value='{$options['no']}' />
<input type='hidden' name='p' value='{$options['p']}' />
<input type='hidden' name='action' value='bbs' />
<input type='hidden' name='mode' value='delete' />
</form>
</div>
EOF;
        $formatter->send_footer("", $options);
        return;
    } else {
        if ($options['mode'] == 'edit') {
            $button_preview = $options['button_preview'];
            while ($_SERVER['REQUEST_METHOD'] == "POST") {
                $savetext = $options['savetext'];
                $datestamp = $options['datestamp'];
                $subject = $options['subject'];
                # strip some tags from the subject
                $subject = preg_replace("%</?(marquee|embed|object|script|form|frame|iframe|img|a|)[^>]*>%", '', $subject);
                $args['subject'] = _stripslashes($subject);
                if ($options['id'] == 'Anonymous') {
                    $name = $options['name'];
                    $name = strip_tags($name);
                    $pass = $options['pass'];
                    $home = $options['homepage'];
                    # check a homepage address
                    if (!empty($home)) {
                        if (!preg_match('/^((ftp|http|news):\\/\\/)[a-z0-9][a-z0-9_\\-]+\\.[a-z0-9\\-\\.]+.*/', $home)) {
                            $options['msg'] = _("Invalid HomePage address.");
                            break;
                        } else {
                            if (!eregi("^(ftp|http|news):\\/\\/", $home)) {
                                $home = "http://" . $home;
                            }
                        }
                    }
                    # check email address
                    $email = $options['email'];
                    $args['name'] = _stripslashes($name);
                    $args['pass'] = _stripslashes($pass);
                    $args['home'] = _stripslashes($home);
                    $args['email'] = _stripslashes($email);
                    if (!$name) {
                        $options['msg'] = _("No Name error.");
                        break;
                    }
                } else {
                    $args['name'] = $options['id'];
                }
                $args['no'] = $options['no'] ? $options['no'] : 0;
                if ($options['no'] and !$check_pass) {
                    break;
                }
                # edit mode
                if (!$check_ip) {
                    break;
                }
                # not allowed IPs
                if (!$args['subject'] or !$savetext) {
                    $options['msg'] = _("No Subject error.");
                    break;
                }
                if ($button_preview) {
                    break;
                }
                $savetext = preg_replace("/\r\n|\r/", "\n", $savetext);
                if ($savetext and $DBInfo->spam_filter) {
                    $text = $savetext;
                    $fts = preg_split('/(\\||,)/', $DBInfo->spam_filter);
                    foreach ($fts as $ft) {
                        $text = $formatter->filter_repl($ft, $text, $options);
                    }
                    if ($text != $savetext) {
                        $options['msg'] = _("Sorry, can not save page because some messages are blocked in this wiki.");
                        break;
                    }
                }
                $savetext = rtrim($savetext) . "\n";
                $args['text'] = _stripslashes($savetext);
                $MyBBS = macro_BBS($formatter, '', array('new' => 1));
                $myrefresh = '';
                if ($DBInfo->use_save_refresh) {
                    $sec = $DBInfo->use_save_refresh - 1;
                    $lnk = $formatter->link_url($formatter->page->urlname, "?action=show");
                    $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
                }
                $header = array("Expires: " . gmdate("D, d M Y H:i:s", 0) . " GMT");
                $options['msg'] = _("New post added successfully");
                if ($myrefresh) {
                    $header[] = $myrefresh;
                }
                $formatter->send_header($header, $options);
                $formatter->send_title("", "", $options);
                if ($MyBBS->use_attach) {
                    # XXX
                    $args['call'] = 1;
                    $lists = array();
                    $lists = $formatter->macro_repl('Attachments', '', $args);
                    unset($args['call']);
                    if (!empty($lists)) {
                        $args['attach'] = $lists;
                    }
                }
                $MyBBS->savePage($args);
                $formatter->send_footer("", $options);
                return;
            }
            #print _bbs_edit_form();
            #print macro_BBSForm($formatter);
            $formatter->send_header("", $options);
            $formatter->send_title("", "", $options);
            if ($options['savetext']) {
                $formatter->_raw_body = $options['savetext'];
                if ($options['no']) {
                    $hidden = "<input type='hidden' name='no' value='{$options['no']}' />\n" . "<input type='hidden' name='p' value='{$options['p']}' />";
                }
            } else {
                if ($options['no']) {
                    $MyBBS = macro_BBS($formatter, '', array('new' => 1));
                    $nid = $options['no'];
                    if ($nid and $MyBBS->hasPage($nid)) {
                        $fields = array('Name', 'Subject', 'Date', 'Email', 'HomePage', 'IP', 'Keywords');
                        include_once 'lib/metadata.php';
                        $body = $MyBBS->getPage($nid);
                        $boundary = strtoupper(md5("COMMENT"));
                        # XXX
                        list($body, $comments) = explode('----' . $boundary . "\n", $body, 2);
                        # XXX
                        if ($body != null) {
                            list($metas, $nbody) = _get_metadata($body);
                            if ($nbody) {
                                $body = $nbody;
                            }
                            $args['name'] = $metas['Name'];
                            $args['subject'] = $metas['Subject'];
                            $args['home'] = $metas['HomePage'];
                            $args['email'] = $metas['Email'];
                            $args['text'] = $body;
                            $formatter->_raw_body = $body;
                            $hidden = "<input type='hidden' name='no' value='{$nid}' />\n" . "<input type='hidden' name='p' value='{$options['p']}' />";
                        }
                    }
                } else {
                    $formatter->_raw_body = "";
                }
            }
            if ($options['id'] == 'Anonymous') {
                $formatter->_extra_form = <<<EOF
<div>
<table border='0' width='100%'>
<col width='10%' /><col width='10%' /><col width='10%' /><col width='70%' />
<tbody>
<tr><th>Subject:</th><td colspan='3'><input type='text' style="width:80%" name='subject' value='{$args['subject']}' /></td></tr>
<tr><th>Name:</th><td><input type='text' name='name' value='{$args['name']}' /></td>
    <th>Password:</th><td><input type='password' name='pass' /></td></tr>
<tr><th>Email:</th><td colspan='3'><input type='text' style="width:50%" name='email' value='{$args['email']}' /></td></tr>
<tr><th>HomePage:</th><td colspan='3'><input type='text'style="width:50%" name='homepage' value='{$args['home']}' /></td></tr>
</tbody>
</table>
{$hidden}
</div>
EOF;
            } else {
                if (!$check_pass and !empty($options['no']) and $options['mode'] == 'edit') {
                    $pass_form = "<tr><th>Password:</th><td><input type='password' name='pass' /></td></tr>";
                }
                $formatter->_extra_form = <<<EOF
<div>
<table border='0' width='100%'>
<col width='20%' /><col width='80%' />
<tbody>
<tr><th>Subject:</th><td><input type='text' style="width:80%" name='subject' value='{$args['subject']}' /></td></tr>
{$pass_form}
</tbody>
</table>
{$hidden}
</div>
EOF;
            }
            $formatter->_mtime = 0;
            $options['simple'] = 2;
            $options['nocategories'] = 1;
            $options['minor'] = 1;
            # do not show a minor checkbox
            print macro_EditText($formatter, $value, $options);
            $formatter->_raw_body = null;
            $formatter->_extra_form = null;
        } else {
            $formatter->send_header("", $options);
            $formatter->send_title("", "", $options);
            print macro_BBS($formatter, 'no=' . $options['no']);
        }
    }
    $formatter->send_footer("", $options);
    return;
}
Exemplo n.º 5
0
function do_comment($formatter, $options = array())
{
    global $DBInfo;
    if (!$DBInfo->security->writable($options)) {
        $formatter->preview = 1;
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    } else {
        if (!$DBInfo->hasPage($options['page'])) {
            $options['err'] = _("You are not allowed to add a comment.");
            $options['title'] = _("Page does not exists");
            return do_invalid($formatter, $options);
        }
    }
    if (!empty($options['usemeta'])) {
        $use_meta = 1;
    }
    $cols = get_textarea_cols();
    $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 8;
    $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols;
    $url = $formatter->link_url($formatter->page->urlname);
    $button_preview = !empty($options['button_preview']) ? $options['button_preview'] : 0;
    $use_any = 0;
    if (!empty($DBInfo->use_textbrowsers)) {
        if (is_string($DBInfo->use_textbrowsers)) {
            $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        } else {
            $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        }
    }
    $ok_ticket = 0;
    if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') {
        if ($options['__seed'] and $options['check']) {
            $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4);
            if ($mycheck == $options['check']) {
                $ok_ticket = 1;
            } else {
                $options['msg'] = _("Invalid ticket !");
                $button_preview = 1;
            }
        } else {
            if (!$button_preview) {
                $options['msg'] = _("You need a ticket !");
            }
            $button_preview = 1;
        }
    } else {
        $ok_ticket = 1;
    }
    if ($options['savetext']) {
        $savetext = _stripslashes($options['savetext']);
        $savetext = str_replace("\r", "", $savetext);
        $savetext = rtrim($savetext);
        #$savetext=str_replace("<","&lt;",$savetext);
    }
    if (!empty($savetext) and empty($button_preview) and !empty($DBInfo->spam_filter)) {
        $text = $savetext;
        $fts = preg_split('/(\\||,)/', $DBInfo->spam_filter);
        foreach ($fts as $ft) {
            $text = $formatter->filter_repl($ft, $text, $options);
        }
        if ($text != $savetext) {
            $button_preview = 1;
            $options['msg'] = _("Sorry, can not save page because some messages are blocked in this wiki.");
        }
    }
    if (!empty($button_preview) && !empty($options['savetext'])) {
        if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') {
            $formatter->send_header("", $options);
            $formatter->send_title(_("Preview comment"), "", $options);
            $formatter->send_page($savetext . "\n----");
            $options['savetext'] = $savetext;
            print macro_Comment($formatter, '', $options);
            print $formatter->macro_repl('EditHints');
            $formatter->send_footer("", $options);
        }
        return false;
    } else {
        if (empty($savetext)) {
            if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') {
                $formatter->send_header("", $options);
                $formatter->send_title(_("Add comment"), "", $options);
                print macro_Comment($formatter, '', $options);
                print $formatter->macro_repl('EditHints');
                $formatter->send_footer("", $options);
            }
            return false;
        }
    }
    $datestamp = $options['datestamp'];
    if ($formatter->page->mtime() > $datestamp) {
        $options['msg'] = '';
        if (empty($options['action_mode']) or $options['action_mode'] != 'ajax') {
            $formatter->send_header('', $options);
            $formatter->send_title(_("Error: Don't make a clone!"), '', $options);
            $formatter->send_footer('', $options);
        }
        return false;
    }
    $body = $formatter->page->get_raw_body();
    if ($options['id'] == 'Anonymous') {
        $id = $options['name'] ? _stripslashes($options['name']) : $_SERVER['REMOTE_ADDR'];
    } else {
        $id = $options['id'];
    }
    if (!empty($use_meta)) {
        $date = gmdate('Y-m-d H:i:s') . ' GMT';
        $savetext = rtrim($savetext) . "\n";
        $boundary = strtoupper(md5("COMMENT"));
        # XXX
        $idx = 1;
        if (preg_match_all('/-{4}(?:' . $boundary . ')?\\nComment-Id:\\s*(\\d+)\\n/m', $body, $m)) {
            $idx = $m[1][sizeof($m[1]) - 1] + 1;
        }
        if ($options['id'] != 'Anonymous') {
            $id = '@USERNAME@';
        }
        $meta = <<<META
Comment-Id: {$idx}
From: {$id}
Date: {$date}
META;
        $savetext = "----" . $boundary . "\n{$meta}\n\n{$savetext}\n";
    } else {
        if (!empty($options['nosig'])) {
            $savetext = "----\n{$savetext}\n";
        } else {
            if ($options['id'] == 'Anonymous') {
                $savetext = "----\n{$savetext} -- {$id} @DATE@\n";
            } else {
                $savetext = "----\n{$savetext} @SIG@\n";
            }
        }
    }
    while ($options['comment_id']) {
        list($nth, $dum, $v) = explode(',', base64_decode($options['comment_id']), 3);
        if ($v) {
            $check = '[[' . $dum . '(' . $v . ')]]';
        } else {
            $check = '[[' . $dum . ']]';
        }
        if ($v) {
            $check2 = '<<' . $dum . '(' . $v . ')>>';
        } else {
            $check2 = '<<' . $dum . '>>';
        }
        if (is_numeric($nth)) {
            $raw = str_replace("\n", "", $body);
            $chunk = preg_split("/({{{.+}}})/U", $raw, -1, PREG_SPLIT_DELIM_CAPTURE);
            // FIXME
            $nc = '';
            $k = 1;
            $i = 1;
            foreach ($chunk as $c) {
                if ($k % 2) {
                    $nc .= $c;
                } else {
                    $nc .= "" . $i . "";
                    $blocks[$i] = str_replace("", "\n", $c);
                    ++$i;
                }
                $k++;
            }
            $nc = str_replace("", "\n", $nc);
            if (preg_match_all('/(?!\\!)(?:\\<\\<|\\[\\[)Comment(?:.*?)(?:\\]\\]|>>)/', $nc, $m)) {
                if (count($m[0]) == 1) {
                    break;
                }
            }
            $chunk = preg_split('/((?!\\!)(?:\\<\\<|\\[\\[).+(?:\\]\\]|>>))/U', $nc, -1, PREG_SPLIT_DELIM_CAPTURE);
            $nnc = '';
            $ii = 1;
            $matched = 0;
            for ($j = 0, $sz = sizeof($chunk); $j < $sz; ++$j) {
                if (($j + 1) % 2) {
                    $nnc .= $chunk[$j];
                } else {
                    if ($nth == $ii) {
                        $new = $savetext . $chunk[$j];
                        if ($check != $chunk[$j] and $check2 != $chunk[$j]) {
                            break;
                        }
                        $nnc .= $new;
                        $matched = 1;
                    } else {
                        $nnc .= $chunk[$j];
                    }
                    ++$ii;
                }
            }
            if (!empty($blocks)) {
                $formatter->_array_callback($blocks, true);
                $nnc = preg_replace_callback("/(\\d+)/", array(&$formatter, '_array_callback'), $nnc);
            }
        }
        if (!empty($matched)) {
            $body = $nnc;
        }
        break;
    }
    if (empty($matched)) {
        if ($options['comment_id'] and preg_match("/^((?:\\[\\[|\\<\\<)Comment\\(" . $options['comment_id'] . "\\)(?:\\]\\]|>>))/m", $body, $m)) {
            $str = $m[1];
            $body = preg_replace('/' . preg_quote($str) . '/', $savetext . $str, $body, 1);
        } else {
            if (preg_match("/\n##Comment\n/i", $body)) {
                $body = preg_replace("/\n##Comment\n/i", "\n##Comment\n{$savetext}", $body, 1);
            } else {
                if (preg_match("/^((\\[\\[|\\<\\<)Comment(\\([^\\)]*\\))?(\\]\\]|>>)/m", $body)) {
                    $body = preg_replace("/^((\\[\\[|\\<\\<)Comment(\\([^\\)]*\\))?(\\]\\]|>>))/m", $savetext . "\\1", $body, 1);
                } else {
                    $body .= $savetext;
                }
            }
        }
    }
    $formatter->page->write($body);
    $DBInfo->savePage($formatter->page, "Comment added", $options);
    if ($options['action_mode'] == 'ajax') {
        return true;
    }
    $options['msg'] = sprintf(_("%s is commented successfully"), $formatter->link_tag($formatter->page->urlname, "?action=show", $options['page']));
    $title = _("Comment added successfully");
    $myrefresh = '';
    if ($DBInfo->use_save_refresh) {
        $sec = $DBInfo->use_save_refresh - 1;
        $lnk = $formatter->link_url($formatter->page->urlname, "?action=show");
        $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
    }
    $formatter->send_header($myrefresh, $options);
    $formatter->send_title($title, '', $options);
    $opt['pagelinks'] = 1;
    # re-generates pagelinks
    $formatter->send_page('', $opt);
    $formatter->send_footer('', $options);
    return;
}
Exemplo n.º 6
0
function do_rss_rc($formatter, $options)
{
    global $DBInfo, $Config;
    // get members to hide log
    $members = $DBInfo->members;
    $days = !empty($DBInfo->rc_days) ? $DBInfo->rc_days : RSS_DEFAULT_DAYS;
    $options['quick'] = 1;
    if (!empty($options['c'])) {
        $options['items'] = $options['c'];
    }
    $lines = $DBInfo->editlog_raw_lines($days, $options);
    if (!empty($DBInfo->rss_rc_options)) {
        $opts = $DBInfo->rss_rc_options;
        $opts = explode(',', $opts);
        foreach ($opts as $opt) {
            $options[$opt] = 1;
            // FIXME
        }
    }
    // HTTP conditional get
    $mtime = $DBInfo->mtime();
    $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime);
    $cache_ttl = !empty($DBInfo->rss_rc_ttl) ? $DBInfo->rss_rc_ttl : 60;
    /* 60 seconds */
    // make etag based on some options and mtime.
    $check_opts = array('quick', 'items', 'oe', 'diffs', 'raw', 'nomsg', 'summary');
    $check = array();
    foreach ($check_opts as $c) {
        if (isset($options[$c])) {
            $check[$c] = $options[$c];
        }
    }
    $etag = md5($mtime . $DBInfo->logo_img . serialize($check) . $cache_ttl . $options['id']);
    $headers = array();
    $headers[] = 'Pragma: cache';
    $maxage = $cache_ttl;
    $public = 'public';
    if ($options['id'] != 'Anonymous') {
        $public = 'private';
    }
    $headers[] = 'Cache-Control: ' . $public . ', max-age=' . $maxage;
    $headers[] = 'Last-Modified: ' . $lastmod;
    $headers[] = 'ETag: "' . $etag . '"';
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        $headers[] = 'HTTP/1.0 304 Not Modified';
    }
    foreach ($headers as $h) {
        header($h);
    }
    if (!$need) {
        @ob_end_clean();
        return;
    }
    $cache = new Cache_Text('rss_rc');
    $cache_delay = min($cache_ttl, 30);
    $mtime = $cache->mtime($etag);
    $val = false;
    if (empty($formatter->refresh)) {
        if (($val = $cache->fetch($etag)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) {
            header("Content-Type: text/xml");
            echo $val;
            return;
        }
    }
    // need to update cache
    if ($val !== false and $cache->exists($etag . '.lock')) {
        header("Content-Type: text/xml");
        echo $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->';
        return;
    }
    if ($cache->exists($etag . '.lock')) {
        header("Content-Type: text/xml");
        echo '';
        return;
    }
    $cache->update($etag . '.lock', array('lock'), 5);
    // 5s lock
    $time_current = time();
    #  $secs_per_day= 60*60*24;
    #  $days_to_show= 30;
    #  $time_cutoff= $time_current - ($days_to_show * $secs_per_day);
    $URL = qualifiedURL($formatter->prefix);
    $img_url = qualifiedURL($DBInfo->logo_img);
    $url = qualifiedUrl($formatter->link_url("RecentChanges"));
    $channel = <<<CHANNEL
<channel rdf:about="{$URL}">
  <title>{$DBInfo->sitename}</title>
  <link>{$url}</link>
  <description>RecentChanges at {$DBInfo->sitename}</description>
  <image rdf:resource="{$img_url}"></image>
  <items>
  <rdf:Seq>

CHANNEL;
    $items = "";
    $ratchet_day = FALSE;
    if (!$lines) {
        $lines = array();
    }
    foreach ($lines as $line) {
        $parts = explode("\t", $line);
        $page_name = $DBInfo->keyToPagename($parts[0]);
        // hide log
        if (!empty($members) && !in_array($options['id'], $members) && !empty($Config['ruleset']['hidelog'])) {
            if (in_array($page_name, $Config['ruleset']['hidelog'])) {
                continue;
            }
        }
        $addr = $parts[1];
        $ed_time = $parts[2];
        $user = $parts[4];
        $log = _stripslashes($parts[5]);
        $act = rtrim($parts[6]);
        #    if ($ed_time < $time_cutoff)
        #      break;
        $url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name)));
        $diff_url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name), '?action=diff'));
        $extra = "<br /><a href='{$diff_url}'>" . _("show changes") . "</a>\n";
        if (!$DBInfo->hasPage($page_name)) {
            $status = 'deleted';
            $html = '<![CDATA[' . "<a href='{$url}'>" . $page_name . "</a> is deleted" . ']]>' . "\n";
        } else {
            $status = 'updated';
            if (!empty($options['diffs'])) {
                $p = new WikiPage($page_name);
                $f = new Formatter($p);
                $options['raw'] = 1;
                $options['nomsg'] = 1;
                $html = $f->macro_repl('Diff', '', $options);
                if (!$html) {
                    ob_start();
                    $f->send_page('', array('fixpath' => 1));
                    #$f->send_page('');
                    $html = ob_get_contents();
                    ob_end_clean();
                    $extra = '';
                }
                $html = str_replace(']', '&#93;', $html);
                $html = "<![CDATA[" . $html . $extra . "]]>";
                #$html=strtr($html.$extra,array('&'=>'&amp;','<'=>'&lt;'));
            } else {
                if (!empty($options['summary'])) {
                    $p = new WikiPage($page_name);
                    $f = new Formatter($p);
                    $f->section_edit = 0;
                    $f->sister_on = 0;
                    $f->perma_icon = '';
                    $options['nomsg'] = 1;
                    $b = $p->_get_raw_body();
                    $chunks = preg_split('/\\n#{4,}/', $b);
                    # summary breaker is ####
                    ob_start();
                    if ($chunks) {
                        $f->send_page($chunks[0], array('fixpath' => 1));
                    } else {
                        $f->send_page('', array('fixpath' => 1));
                    }
                    #$f->send_page('');
                    $html = ob_get_contents();
                    ob_end_clean();
                    $chunks = preg_split('/<!-- break -->/', $html);
                    # <!-- break -->
                    if ($chunks[0]) {
                        $html = $chunks[0];
                    }
                    $html = str_replace(']', '&#93;', $html);
                    $html = "<![CDATA[" . $html . "]]>";
                } else {
                    $html = str_replace('&', '&amp;', $log);
                }
            }
        }
        $zone = "+00:00";
        $date = gmdate("Y-m-d\\TH:i:s", $ed_time) . $zone;
        #$datetag = gmdate("YmdHis",$ed_time);
        $channel .= "<rdf:li rdf:resource=\"{$url}\"></rdf:li>\n";
        $valid_page_name = preg_replace('/&(?!#?\\w+;)/', '&amp;', _html_escape($page_name));
        $items .= "<item rdf:about=\"{$url}\">\n";
        $items .= "  <title>{$valid_page_name}</title>\n";
        $items .= "  <link>{$url}</link>\n";
        $items .= "  <description>{$html}</description>\n";
        $items .= "  <dc:date>{$date}</dc:date>\n";
        $items .= "<dc:creator>{$user}</dc:creator>\n";
        $items .= "<dc:contributor>{$user}</dc:contributor>\n";
        #    $items.="     <dc:contributor>\n     <rdf:Description>\n"
        #          ."     <rdf:value>$user</rdf:value>\n"
        #          ."     </rdf:Description>\n     </dc:contributor>\n";
        $items .= "     <wiki:status>{$status}</wiki:status>\n";
        $items .= "     <wiki:diff>{$diff_url}</wiki:diff>\n";
        $items .= "</item>\n";
    }
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $channel .= <<<FOOT
    </rdf:Seq>
  </items>
</channel>
<image rdf:about="{$img_url}">
<title>{$DBInfo->sitename}</title>
<link>{$url}</link>
<url>{$img_url}</url>
</image>

FOOT;
    $url = qualifiedUrl($formatter->link_url("FindPage"));
    $form = <<<FORM
<textinput>
<title>Search</title>
<link>{$url}</link>
<name>goto</name>
</textinput>

FORM;
    $new = "";
    if (!empty($options['oe']) and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $out = $head . $channel . $items . $form;
            $new = iconv($DBInfo->charset, $charset, $out);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<?xml-stylesheet href="{$DBInfo->url_prefix}/css/_feed.css" type="text/css"?>
<rdf:RDF xmlns="http://purl.org/rss/1.0/"
\txmlns:wiki="http://purl.org/rss/1.0/modules/wiki/"
\txmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
\txmlns:xlink="http://www.w3.org/1999/xlink"
\txmlns:dc="http://purl.org/dc/elements/1.1/">
<!--
    Add "diffs=1" to add change diffs to the description of each items.
    Add "summary=1" to add summary to the description of each items.
    Add "oe=utf-8" to convert the charset of this rss to UTF-8.
-->

HEAD;
    header("Content-Type: text/xml");
    if ($new) {
        $out = $head . $new;
    } else {
        $out = $head . $channel . $items . $form;
    }
    $out .= "</rdf:RDF>\n";
    echo $out;
    $cache->update($etag, $out);
    $cache->remove($etag . '.lock');
}
Exemplo n.º 7
0
function do_rdf_blog($formatter, $options)
{
    global $DBInfo;
    #  if (!$options['date'] or !preg_match('/^\d+$/',$date)) $date=date('Ym');
    #  else $date=$options['date'];
    $date = $options['date'];
    if ($options['all']) {
        # check error and set default value
        $blog_rss = new Cache_text('blogrss');
        #    $blog_mtime=filemtime($DBInfo->cache_dir."/blog");
        #    if ($blog_rss->exists($date'.xml') and ($blog_rss->mtime($date.'.xml') > $blog_mtime)) {
        #      print $blog_rss->fetch($date.'.xml');
        #      return;
        #    }
        $blogs = Blog_cache::get_rc_blogs($date);
        $logs = Blog_cache::get_summary($blogs, $date);
        $rss_name = $DBInfo->sitename . ': ' . _("Blog Changes");
    } else {
        $blogs = array($DBInfo->pageToKeyname($formatter->page->name));
        $logs = Blog_cache::get_summary($blogs, $date);
        $rss_name = $formatter->page->name;
    }
    usort($logs, 'BlogCompare');
    $time_current = time();
    $URL = qualifiedURL($formatter->prefix);
    $img_url = qualifiedURL($DBInfo->logo_img);
    $url = qualifiedUrl($formatter->link_url("BlogChanges"));
    $desc = sprintf(_("BlogChanges at %s"), $DBInfo->sitename);
    $channel = <<<CHANNEL
<channel rdf:about="{$URL}">
  <title>{$rss_name}</title>
  <link>{$url}</link>
  <description>{$desc}</description>
  <image rdf:resource="{$img_url}"/>
  <items>
  <rdf:Seq>
CHANNEL;
    $items = "";
    #          print('<description>'."[$data] :".$chg["action"]." ".$chg["pageName"].$comment.'</description>'."\n");
    #          print('</rdf:li>'."\n");
    #        }
    $ratchet_day = FALSE;
    if (!$logs) {
        $logs = array();
    }
    foreach ($logs as $log) {
        #print_r($log);
        list($page, $user, $date, $title, $summary) = $log;
        $url = qualifiedUrl($formatter->link_url(_urlencode($page)));
        if (!$title) {
            continue;
        }
        #$tag=md5("#!blog ".$line);
        $tag = md5($user . " " . $date . " " . $title);
        #$tag=_rawurlencode(normalize($title));
        $channel .= "    <rdf:li rdf:resource=\"{$url}#{$tag}\"/>\n";
        $items .= "     <item rdf:about=\"{$url}#{$tag}\">\n";
        $items .= "     <title>{$title}</title>\n";
        $items .= "     <link>{$url}#{$tag}</link>\n";
        if ($summary) {
            $p = new WikiPage($page);
            $f = new Formatter($p);
            ob_start();
            #$f->send_page($summary);
            $f->send_page($summary, array('fixpath' => 1));
            #$summary=_html_escape(ob_get_contents());
            $summary = '<![CDATA[' . ob_get_contents() . ']]>';
            ob_end_clean();
            $items .= "     <description>{$summary}</description>\n";
        }
        $items .= "     <dc:date>{$date}+00:00</dc:date>\n";
        $items .= "     <dc:contributor>\n<rdf:Description>\n" . "<rdf:value>{$user}</rdf:value>\n" . "</rdf:Description>\n</dc:contributor>\n";
        $items .= "     </item>\n";
    }
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $channel .= <<<FOOT
    </rdf:Seq>
  </items>
</channel>
<image rdf:about="{$img_url}">
<title>{$DBInfo->sitename}</title>
<link>{$url}</link>
<url>{$img_url}</url>
</image>
FOOT;
    $url = qualifiedUrl($formatter->link_url("FindPage"));
    $form = <<<FORM
<textinput>
<title>Search</title>
<link>{$url}</link>
<name>goto</name>
</textinput>
FORM;
    $new = "";
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $out = $head . $channel . $items . $form;
            $new = iconv($DBInfo->charset, $charset, $out);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<rdf:RDF xmlns:wiki="http://purl.org/rss/1.0/modules/wiki/"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:dc="http://purl.org/dc/elements/1.1/"
         xmlns="http://purl.org/rss/1.0/">

<!--
    Add "oe=utf-8" to convert the charset of this rss to UTF-8.
-->
HEAD;
    header("Content-Type: text/xml");
    if ($new) {
        print $head . $new;
    } else {
        print $head . $channel . $items . $form;
    }
    #print $head;
    #print $channel;
    #print $items;
    #print $form;
    print "</rdf:RDF>";
}
Exemplo n.º 8
0
function do_scrap($formatter, $options)
{
    global $DBInfo;
    if ($options['id'] == 'Anonymous') {
        $title = _("Please login or make your ID.");
        $formatter->send_header("", $options);
        $formatter->send_title($title, "", $options);
        $formatter->send_page("== " . _("Goto UserPreferences") . " ==\n");
        $formatter->send_footer();
        return;
    }
    $udb =& $DBInfo->udb;
    $userinfo = $udb->getUser($options['id']);
    if (isset($options['scrapped_pages']) or empty($DBInfo->scrap_manual) and empty($options['manual'])) {
        $pages = array();
        if (isset($options['scrapped_pages'])) {
            $pages = preg_replace("/\n\\s*/", "\n", $options['scrapped_pages']);
            $pages = preg_replace("/\\s*\n/", "\n", $pages);
            $pages = explode("\n", $pages);
            $pages = array_unique($pages);
            $title = _("Scrap lists updated.");
        } else {
            $pages = array();
            if (!empty($userinfo->info['scrapped_pages'])) {
                $pages = explode("\t", $userinfo->info['scrapped_pages']);
            }
            if (!empty($options['unscrap'])) {
                $tmp = array_flip($pages);
                if (isset($tmp[$formatter->page->name])) {
                    unset($tmp[$formatter->page->name]);
                }
                $pages = array_flip($tmp);
                $title = sprintf(_("\"%s\" is unscrapped."), $formatter->page->name);
            } else {
                $pages[] = $formatter->page->name;
                $title = sprintf(_("\"%s\" is scrapped."), $formatter->page->name);
            }
            $pages = array_unique($pages);
        }
        $page_list = join("\t", $pages);
        $userinfo->info['scrapped_pages'] = $page_list;
        $udb->saveUser($userinfo);
        $myrefresh = '';
        if (!empty($DBInfo->use_refresh)) {
            $sec = $DBInfo->use_refresh - 1;
            $lnk = $formatter->link_url($formatter->page->urlname, '?action=show');
            $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
        }
        $formatter->send_header($myrefresh, $options);
        $formatter->send_title($title, "", $options);
        $formatter->send_page("Goto [{$options['page']}]\n");
        $formatter->send_footer('', $options);
        return;
    }
    $pages = explode("\t", $userinfo->info['scrapped_pages']);
    if (!in_array($options['page'], $pages)) {
        $pages[] = $options['page'];
    }
    $page_lists = join("\n", $pages);
    $title = sprintf(_("Do you want to scrap \"%s\" ?"), $options['page']);
    $formatter->send_header("", $options);
    $formatter->send_title($title, "", $options);
    $msg = _("Scrapped pages");
    print "<form method='post'>\n<table border='0'><tr>\n<th>{$msg} :</th><td><textarea name='scrapped_pages' cols='40' rows='5' value='' />{$page_lists}</textarea></td></tr>\n<tr><td></td><td>\n    <input type='hidden' name='action' value='scrap' />\n    <input type='submit' value='Scrap' />\n</td></tr>\n</table>\n    </form>";
    $formatter->send_footer("", $options);
}
Exemplo n.º 9
0
function do_Blog($formatter, $options)
{
    global $DBInfo;
    $COLS_MSIE = 80;
    $COLS_OTHER = 85;
    $cols = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? $COLS_MSIE : $COLS_OTHER;
    $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 8;
    $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols;
    $name = !empty($options['name']) ? $options['name'] : '';
    $url = $formatter->link_url($formatter->page->urlname);
    if (!empty($formatter->refresh) or !empty($options['button_refresh'])) {
        updateBlogList($formatter);
        $options['msg'] = sprintf(_("Blog cache of \"%s\" is refreshed"), $formatter->page->name);
    }
    $savetext = "";
    if (!empty($options['savetext'])) {
        $savetext = _stripslashes($options['savetext']);
        $savetext = str_replace("\r", "", $savetext);
        $savetext = str_replace("----\n", "-''''''---\n", $savetext);
        $savetext = rtrim($savetext);
        #$savetext=str_replace("<","&lt;",$savetext);
    }
    # for conflict check
    if (!empty($options['datestamp'])) {
        $datestamp = $options['datestamp'];
    } else {
        $datestamp = $formatter->page->mtime();
    }
    if (!empty($options['title'])) {
        $options['title'] = _stripslashes($options['title']);
    } else {
        $options['title'] = '';
    }
    $button_preview = $options['button_preview'];
    if (!empty($savetext)) {
        $ok_ticket = 0;
        if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') {
            if ($options['__seed'] and $options['check']) {
                $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4);
                if ($mycheck == $options['check']) {
                    $ok_ticket = 1;
                } else {
                    $options['msg'] = _("Invalid ticket !");
                    $button_preview = 1;
                }
            } else {
                if (!$button_preview) {
                    $options['msg'] = _("You need a ticket !");
                }
                $button_preview = 1;
            }
        } else {
            $ok_ticket = 1;
        }
    }
    if (empty($button_preview) && !empty($savetext)) {
        $savetext = preg_replace("/(?<!\\\\)}}}/", "\\}}}", $savetext);
        $url = $formatter->link_tag($formatter->page->urlname, "", $options['page']);
        $options['msg'] = sprintf(_("\"%s\" is updated"), $url);
        if ($formatter->page->exists()) {
            $raw_body = $formatter->page->_get_raw_body();
        } else {
            $raw_body = "#action Blog " . _("Add Blog") . "\n##Blog\n";
        }
        $lines = explode("\n", $raw_body);
        $count = count($lines);
        if ($options['id'] == 'Anonymous') {
            $id = $options['name'] ? _stripslashes($options['name']) : $_SERVER['REMOTE_ADDR'];
        } else {
            $id = $options['id'];
        }
        if (!empty($options['value'])) {
            # add comment
            for ($i = 0; $i < $count; $i++) {
                if (preg_match("/^({{{)?#!blog (.*)\$/", $lines[$i], $match)) {
                    if (md5($match[2]) == $options['value']) {
                        list($tag, $user, $date, $title) = explode(" ", $lines[$i], 4);
                        $found = 1;
                        if ($match[1]) {
                            $endtag = '}}}';
                        }
                        break;
                    }
                }
            }
            if (!empty($found)) {
                if (!empty($endtag)) {
                    for (; $i < $count; $i++) {
                        if (preg_match("/^}}}\$/", $lines[$i])) {
                            $found = 1;
                            break;
                        }
                    }
                } else {
                    # XXX
                    $lines = explode("\n", rtrim($raw_body));
                    $i = count($lines);
                }
                if (!empty($options['nosig'])) {
                    $lines[$i] = "----\n{$savetext}\n{$endtag}";
                } else {
                    $lines[$i] = "----\n{$savetext} @SIG@\n{$endtag}";
                }
                $raw_body = join("\n", $lines);
            } else {
                $formatter->send_header("", $options);
                $formatter->send_title(_("Error: No blog entry found!"), "", $options);
                $formatter->send_footer("", $options);
                return;
            }
        } else {
            # Blog entry
            // check timestamp
            if ($formatter->page->mtime() > $datestamp) {
                $options['msg'] = '';
                if ($options['action_mode'] == 'ajax') {
                    print "false\n";
                    print _("Error: Don't make a clone!");
                } else {
                    $formatter->send_title(_("Error: Don't make a clone!"), "", $options);
                    $formatter->send_footer("", $options);
                }
                return;
            }
            $entry = "{{{#!blog {$id} @date@";
            if (!empty($options['title'])) {
                $entry .= " " . $options['title'];
            }
            $entry .= "\n{$savetext}\n}}}\n\n";
            if (preg_match("/\n##Blog\n/i", $raw_body)) {
                $raw_body = preg_replace("/\n##Blog\n/i", "\n##Blog\n{$entry}", $raw_body, 1);
            } else {
                $raw_body .= $entry;
            }
        }
        $myrefresh = '';
        if (!empty($DBInfo->use_save_refresh)) {
            $sec = $DBInfo->use_save_refresh - 1;
            $lnk = $formatter->link_url($formatter->page->urlname, "?action=show");
            $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
        }
        $formatter->send_header($myrefresh, $options);
        if (!empty($options['value'])) {
            $formatter->send_title(sprintf(_("Comment added to \"%s\""), $title), "", $options);
            $log = "Add Comment to \"{$title}\"";
        } else {
            $formatter->send_title(sprintf(_("Blog entry added to \"%s\""), $options['page']), "", $options);
            if (!empty($options['title'])) {
                $log = sprintf(_("Blog entry \"%s\" added"), $options['title']);
            } else {
                $log = _("Blog entry added");
            }
        }
        $formatter->page->write($raw_body);
        $DBInfo->savePage($formatter->page, $log, $options);
        updateBlogList($formatter);
        if ($options['action_mode'] == 'ajax') {
            print "true\n";
            print $options['msg'];
        } else {
            $formatter->send_page();
        }
    } else {
        # add entry or comment
        $formatter->send_header("", $options);
        if (!empty($options['value'])) {
            $raw_body = $formatter->page->_get_raw_body();
            $lines = explode("\n", $raw_body);
            $count = count($lines);
            for ($i = 0; $i < $count; $i++) {
                if (preg_match("/^({{{)?#!blog (.*)\$/", $lines[$i], $match)) {
                    if (md5($match[2]) == $options['value']) {
                        list($tag, $user, $date, $title) = explode(" ", $lines[$i], 4);
                        $found = 1;
                        $lines[$i] = '#!blog ' . $match[2];
                        break;
                    }
                }
            }
            if (!empty($found)) {
                $quote = '';
                for (; $i < $count; $i++) {
                    if (preg_match("/^}}}\$/", $lines[$i])) {
                        break;
                    }
                    $quote .= $lines[$i] . "\n";
                }
            }
            if (empty($title)) {
                $title = $options['page'];
            }
            if (empty($found)) {
                $formatter->send_title("Error: No entry found!", "", $options);
                $formatter->send_footer("", $options);
                return;
            }
            $formatter->send_title(sprintf(_("Add Comment to \"%s\""), $title), "", $options);
        } else {
            $formatter->send_title(sprintf(_("Add Blog entry to \"%s\""), $options['page']), "", $options);
        }
        $options['noaction'] = 1;
        if (!empty($quote)) {
            $quote = str_replace('\\}}}', '}}}', $quote);
            print $formatter->processor_repl('blog', $quote, $options);
            #print $formatter->send_page($quote,$options);
        }
        $extra = '';
        $btn = _("Refresh");
        if ($options['id'] != 'Anonymous') {
            $extra = '<div style="text-align:right">' . '
        <span class="button"><input type="submit" class="button" name="button_refresh" value="' . $btn . '" /></span></div>';
        }
        if (!empty($options['value'])) {
            print "<a name='BlogComment'></a>";
        }
        print '<div id="editor_area">';
        print "<form method='post' action='{$url}'>\n";
        $myinput = '';
        if ($options['id'] == 'Anonymous') {
            $myinput .= '<b>' . _("Name") . "</b>: <input name='name' size='15' maxlength='15' value='{$name}' />\n";
        }
        if (empty($options['value'])) {
            $myinput .= '<b>' . _("Title") . "</b>: <input name='title' value='{$options['title']}' size='70' maxlength='70' style='width:300px' /><br />\n";
        } else {
            print "<input type='hidden' name='value' value='{$options['value']}' />\n";
        }
        print '<div class="editor_area_extra">' . $myinput . "</div>\n";
        $savetext = $savetext ? $savetext : 'Enter blog entry';
        if (!empty($DBInfo->use_wikiwyg)) {
            $wysiwyg_msg = _("GUI");
            $wysiwyg_btn = '&nbsp;<span class="button"><input class="button" type="button" tabindex="7" value="' . $wysiwyg_msg . '" onclick="javascript:sectionEdit(null,null,null)" /></span>';
        }
        if ($DBInfo->use_resizer > 1) {
            echo <<<JS
<script type="text/javascript" src="{$DBInfo->url_prefix}/local/textarea.js"></script>
JS;
        }
        print <<<FORM
<div class="resizable-textarea" style='position:relative'><!-- IE hack -->
<textarea class="wiki resizable" id="content" wrap="virtual" name="savetext"
 rows="{$rows}" cols="{$cols}" class="wiki">{$savetext}</textarea></div>
FORM;
        if (!empty($options['value'])) {
            print "<input name='nosig' type='checkbox' />" . _("Don't add a signature") . "<br />";
        }
        $save_msg = _("Save");
        $preview_msg = _("Preview");
        if (empty($use_any) and !empty($DBInfo->use_ticket) and $options['id'] == 'Anonymous') {
            $seed = md5(base64_encode(time()));
            $ticketimg = $formatter->link_url($formatter->page->urlname, '?action=ticket&amp;__seed=' . $seed);
            $captcha = <<<EXTRA
  <div class='captcha'><span class='captchaImg'><img src="{$ticketimg}" alt="captcha" /></span><input type="text" size="10" name="check" />
<input type="hidden" name="__seed" value="{$seed}" /></div>
EXTRA;
        }
        print <<<FORM2
{$captcha}
<input type="hidden" name="action" value="Blog" />
<input type="hidden" name="datestamp" value="{$datestamp}" />
<span class="button"><input type="submit" class="button" value="{$save_msg}" /></span>&nbsp;
<span class="button"><input type="submit" class="button" name="button_preview" value="{$preview_msg}" /></span>
{$wysiwyg_btn}{$extra}
</form>
</div>
FORM2;
        if (!empty($DBInfo->use_wikiwyg) and $DBInfo->use_wikiwyg >= 3) {
            print <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
sectionEdit(null,null,null);
/*]]>*/
</script>
JS;
        }
    }
    if (empty($savetext)) {
        #print $formatter->macro_repl('SmileyChooser');
        print macro_EditHints($formatter);
        print "<div class='wikiHints'>" . _("<b>horizontal rule</b> ---- is not applied on the blog mode.") . "</div>\n";
    }
    if (!empty($options['button_preview']) && !empty($options['savetext'])) {
        if (!empty($options['title'])) {
            $formatter->send_page("== {$options['title']} ==\n");
        }
        $formatter->send_page($savetext);
    }
    $formatter->send_footer("", $options);
    return;
}
Exemplo n.º 10
0
function do_userform($formatter, $options)
{
    global $DBInfo;
    $user =& $DBInfo->user;
    # get cookie
    $id = !empty($options['login_id']) ? $options['login_id'] : '';
    $use_any = 0;
    if (!empty($DBInfo->use_textbrowsers)) {
        if (is_string($DBInfo->use_textbrowsers)) {
            $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        } else {
            $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
        }
    }
    $options['msg'] = '';
    # e-mail conformation
    if (!empty($options['ticket']) and $id and $id != 'Anonymous') {
        $userdb =& $DBInfo->udb;
        $suspended = false;
        if ($userdb->_exists($id)) {
            $user = $userdb->getUser($id);
        } else {
            if ($userdb->_exists($id, 1)) {
                // suspended user
                $suspended = true;
                $user = $userdb->getUser($id, 1);
            }
        }
        if ($user->id == $id) {
            if ($user->info['eticket'] == $options['ticket']) {
                list($dummy, $email) = explode('.', $options['ticket'], 2);
                $user->info['email'] = $email;
                $user->info['eticket'] = '';
                if ($suspended) {
                    if (empty($DBInfo->register_confirm_admin)) {
                        $userdb->activateUser($id);
                        $userdb->saveUser($user);
                    } else {
                        $userdb->saveUser($user, array('suspended' => 1));
                    }
                } else {
                    $userdb->saveUser($user);
                }
                $title = _("Successfully confirmed");
                $options['msg'] = _("Your e-mail address is confirmed successfully");
                if (!empty($DBInfo->register_confirm_admin)) {
                    $options['msg'] .= "<br />" . _("Your need to wait until your ID activated by admin");
                }
            } else {
                if ($user->info['nticket'] == $options['ticket']) {
                    $title = _("Successfully confirmed");
                    $user->info['nticket'] = '';
                    $user->info['password'] = $user->info['npassword'];
                    $user->info['npassword'] = '';
                    $userdb->saveUser($user);
                    $options['msg'] = _("Your new password is confirmed successfully");
                } else {
                    $title = _("Confirmation missmatched !");
                    $options['msg'] = _("Please try again to register your e-mail address");
                }
            }
        } else {
            if ($suspended) {
                $title = _("Please wait until your ID is confirmed by admin!");
            } else {
                $title = _("ID does not exist !");
            }
            $options['msg'] = _("Please try again to register your e-mail address");
        }
        $formatter->send_header("", $options);
        $formatter->send_title($title, "", $options);
        $formatter->send_footer("", $options);
        return '';
    }
    $title = '';
    if ($user->id == "Anonymous" and !empty($options['emailreset'])) {
        setcookie('MONI_VERIFIED_EMAIL', '', time() - 3600, get_scriptname());
        $options['msg'] .= '<br />' . _("Verification E-mail removed.");
        $options['verifyemail'] = '';
        $user->verified_email = '';
    } else {
        if ($user->id == "Anonymous" and !empty($options['login']) and !empty($options['verify_email'])) {
            $email = base64_decode($options['login']);
            $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $email, 10));
            if ($ticket == $options['verify_email']) {
                $options['msg'] .= '<br />' . _("Your email address is successfully verified.");
                $user->verified_email = $email;
                setcookie('MONI_VERIFIED_EMAIL', $email, time() + 60 * 60 * 24 * 30, get_scriptname());
            } else {
                $options['msg'] .= '<br />' . _("Verification missmatched.");
            }
        } else {
            if ($user->id == "Anonymous" and $options['verify'] == _("Verify E-mail address") and !empty($DBInfo->anonymous_friendly) and !empty($options['verifyemail'])) {
                if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['verifyemail'])) {
                    if (($ret = verify_email($options['verifyemail'])) < 0) {
                        $ret = -$ret;
                        $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret;
                        $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it.");
                    } else {
                        if (!empty($DBInfo->verify_email)) {
                            if ($DBInfo->verify_email == 1) {
                                $options['msg'] .= '<br/>' . _("Your email address is successfully verified.");
                                setcookie('MONI_VERIFIED_EMAIL', $options['verifyemail'], time() + 60 * 60 * 24 * 30, get_scriptname());
                            } else {
                                $opts = array();
                                $opts['subject'] = "[{$DBInfo->sitename}] " . _("Verify Email address");
                                $opts['email'] = $options['verifyemail'];
                                $opts['id'] = 'nobody';
                                $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $opts['email'], 10));
                                $enc = base64_encode($opts['email']);
                                $body = qualifiedUrl($formatter->link_url('UserPreferences', "?action=userform&login={$enc}&verify_email={$ticket}"));
                                $body = _("Please confirm your e-mail address") . "\n" . $body . "\n";
                                $ret = wiki_sendmail($body, $opts);
                                $options['msg'] .= '<br/>' . _("E-mail verification mail sent");
                            }
                        }
                    }
                } else {
                    $options['msg'] .= '<br/>' . _("Your email address is not valid");
                }
            } else {
                if ($user->id == "Anonymous" and !empty($options['login_id']) and isset($options['password']) and !isset($options['passwordagain'])) {
                    if (method_exists($user, 'login')) {
                        $user->login($formatter, $options);
                        $params = array();
                        $params['value'] = $options['page'];
                        do_goto($formatter, $params);
                        return;
                    }
                    # login
                    $userdb = $DBInfo->udb;
                    if ($userdb->_exists($id)) {
                        $user = $userdb->getUser($id);
                        $login_ok = 0;
                        if (!empty($DBInfo->use_safelogin)) {
                            if (isset($options['challenge']) and $options['_chall'] == $options['challenge']) {
                                #print '<pre>';
                                #print $options['password'].'<br />';
                                #print hmac($options['challenge'],$user->info['password']);
                                #print '</pre>';
                                if (hmac($options['challenge'], $user->info['password']) == $options['password']) {
                                    $login_ok = 1;
                                }
                            } else {
                                # with no javascript browsers
                                $md5pw = md5($options['password']);
                                if ($md5pw == $user->info['password']) {
                                    $login_ok = 1;
                                }
                            }
                        }
                        if ($login_ok or $user->checkPasswd($options['password']) === true) {
                            $options['msg'] = sprintf(_("Successfully login as '%s'"), $id);
                            $options['id'] = $user->id;
                            if ($user->id == 'Anonymous') {
                                // special case. login success but ID is not acceptable
                                $options['msg'] = _("Invalid user ID. Please register again");
                            } else {
                                $formatter->header($user->setCookie());
                                if (!isset($user->info['login_success'])) {
                                    $user->info['login_success'] = 0;
                                }
                                if (!isset($user->info['login_fail'])) {
                                    $user->info['login_fail'] = 0;
                                }
                                $user->info['login_success']++;
                                $user->info['last_login'] = gmdate("Y/m/d H:i:s", time());
                                $user->info['login_fail'] = 0;
                                // reset login
                                $user->info['remote'] = $_SERVER['REMOTE_ADDR'];
                                $userdb->saveUser($user);
                                $use_refresh = 1;
                            }
                            $DBInfo->user = $user;
                        } else {
                            $title = sprintf(_("Invalid password !"));
                            if (!isset($user->info['login_fail'])) {
                                $user->info['login_fail'] = 0;
                            }
                            $user->info['login_fail']++;
                            $user->info['remote'] = $_SERVER['REMOTE_ADDR'];
                            $userdb->saveUser($user);
                            $user->setID('Anonymous');
                        }
                    } else {
                        if (isset($options['login_id'][0])) {
                            if ($userdb->_exists($id, 1)) {
                                // suspended user
                                $title = sprintf(_("\"%s\" is waiting for activated by admin !"), $options['login_id']);
                            } else {
                                $title = sprintf(_("\"%s\" does not exist on this wiki !"), $options['login_id']);
                            }
                            $options['login_id'] = '';
                        } else {
                            $title = _("Make new ID on this wiki");
                        }
                        $form = macro_UserPreferences($formatter, '', $options);
                    }
                } else {
                    if (!empty($options['logout'])) {
                        # logout
                        header($user->unsetCookie(), false);
                        if (session_name() != '') {
                            $path = get_scriptname();
                            // for moniwiki internal
                            header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $path, false);
                            // for some user plugins
                            $params = session_get_cookie_params();
                            header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $params['path'], false);
                        }
                        // call logout method
                        if (method_exists($user, 'logout')) {
                            $user->logout($formatter, $options);
                        } else {
                            $options['msg'] = _("Cookie deleted !");
                        }
                        $user->id = 'Anonymous';
                        $DBInfo->user = $user;
                        $use_refresh = 1;
                    } else {
                        if (!empty($DBInfo->use_sendmail) and $options['login'] == _("E-mail new password") and $user->id == "Anonymous" and !empty($options['email']) and !empty($options['login_id'])) {
                            # email new password
                            $title = '';
                            if (!$use_any and $DBInfo->use_ticket) {
                                if ($options['__seed'] and $options['check']) {
                                    $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4);
                                    if ($mycheck == $options['check']) {
                                        $ok_ticket = 1;
                                    } else {
                                        $title = _("Invalid ticket !");
                                    }
                                } else {
                                    $title = _("You need a ticket !");
                                }
                            } else {
                                $ok_ticket = 1;
                            }
                            $userdb =& $DBInfo->udb;
                            if ($userdb->_exists($id)) {
                                $user = $userdb->getUser($id);
                            }
                            if ($ok_ticket and $user->id != "Anonymous") {
                                if ($options['email'] == $user->info['email'] and $user->info['eticket'] == '') {
                                    #make new password
                                    $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10));
                                    $mypass = substr($mypass, 0, 8);
                                    $options['password'] = $mypass;
                                    $old_passwd = $user->info['password'];
                                    if ($DBInfo->use_safelogin) {
                                        $ret = $user->setPasswd(md5($mypass), md5($mypass), 1);
                                    } else {
                                        $ret = $user->setPasswd($mypass, $mypass);
                                    }
                                    $new_passwd = $user->info['password'];
                                    $user->info['password'] = $old_passwd;
                                    $user->info['npassword'] = $new_passwd;
                                    #make ticket
                                    $ticket = md5(time() . $user->id . $options['email']);
                                    $user->info['nticket'] = $ticket . "." . $options['email'];
                                    // save join agreement
                                    if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) {
                                        $user->info['join_agreement'] = 'agree';
                                        if (!empty($DBInfo->agreement_version)) {
                                            $user->info['join_agreement_version'] = $DBInfo->agreement_version;
                                        }
                                    }
                                    $userdb->saveUser($user);
                                    # XXX
                                    $opts['subject'] = "[{$DBInfo->sitename}] " . _("New password confirmation");
                                    $opts['email'] = $options['email'];
                                    $opts['id'] = 'nobody';
                                    $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}"));
                                    $body = _("Please confirm your new password") . "\n" . $body . "\n";
                                    $body .= sprintf(_("Your new password is %s"), $mypass) . "\n\n";
                                    $body .= _("Please change your password later") . "\n";
                                    $ret = wiki_sendmail($body, $opts);
                                    if (is_array($ret)) {
                                        $title = _("Fail to e-mail notification !");
                                        $options['msg'] = $ret['msg'];
                                    } else {
                                        $title = _("New password is sent to your e-mail !");
                                        $options['msg'] = _("Please check your e-mail");
                                    }
                                } else {
                                    if ($options['email'] != $user->info['email']) {
                                        $title = _("Fail to e-mail notification !");
                                        $options['msg'] = _("E-mail mismatch !");
                                    } else {
                                        $title = _("Invalid request");
                                        $options['msg'] = _("Please confirm your e-mail address first !");
                                    }
                                }
                            } else {
                                if (!$ok_ticket) {
                                    $title = _("Invalid ticket !");
                                } else {
                                    $title = _("ID and e-mail mismatch !");
                                }
                                $options['msg'] = _("Please try again or make a new profile");
                            }
                            $formatter->send_header("", $options);
                            $formatter->send_title($title, "", $options);
                            $formatter->send_footer("", $options);
                            return;
                        } else {
                            if ($user->id == "Anonymous" and !empty($options['login_id']) and ($options['password'] and $options['passwordagain'] or $DBInfo->use_safelogin and $options['email'])) {
                                # create profile
                                $title = '';
                                if (!$use_any and !empty($DBInfo->use_ticket)) {
                                    if ($options['__seed'] and $options['check']) {
                                        $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4);
                                        if ($mycheck == $options['check']) {
                                            $ok_ticket = 1;
                                        } else {
                                            $title = _("Invalid ticket !");
                                        }
                                    } else {
                                        $title = _("You need a ticket !");
                                    }
                                } else {
                                    $ok_ticket = 1;
                                }
                                $id = $user->getID($options['login_id']);
                                if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $id)) {
                                    if (($ret = verify_email($id)) < 0) {
                                        $ret = -$ret;
                                        $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret;
                                        $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it.");
                                    } else {
                                        $options['email'] = $id;
                                        $user->setID($id);
                                    }
                                } else {
                                    if (!preg_match("/\\//", $id)) {
                                        $user->setID($id);
                                    }
                                }
                                // protect http:// style id
                                if (!empty($DBInfo->use_agreement) and empty($options['joinagreement'])) {
                                    $title = _("Please check join agreement.");
                                } else {
                                    if ($ok_ticket and $user->id != "Anonymous") {
                                        if (!empty($DBInfo->use_safelogin)) {
                                            $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10));
                                            $mypass = substr($mypass, 0, 8);
                                            $options['password'] = $mypass;
                                            $ret = $user->setPasswd(md5($mypass), md5($mypass), 1);
                                        } else {
                                            $ret = $user->setPasswd($options['password'], $options['passwordagain']);
                                        }
                                        if (!empty($DBInfo->password_length) and strlen($options['password']) < $DBInfo->password_length) {
                                            $ret = 0;
                                        }
                                        if ($ret <= 0) {
                                            if ($ret == 0) {
                                                $title = _("too short password!");
                                            } else {
                                                if ($ret == -1) {
                                                    $title = _("mismatch password!");
                                                } else {
                                                    if ($ret == -2) {
                                                        $title = _("not acceptable character found in the password!");
                                                    }
                                                }
                                            }
                                        } else {
                                            if ($ret < 8 and empty($DBInfo->use_safelogin)) {
                                                $options['msg'] = _("Your password is too simple to use as a password !");
                                            }
                                            $udb = $DBInfo->udb;
                                            if ($options['email']) {
                                                if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) {
                                                    if (($ret = verify_email($options['email'])) < 0) {
                                                        $options['email'] = '';
                                                        // reset email address
                                                        $ret = -$ret;
                                                        $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret;
                                                        $options['msg'] .= '<br/>' . _("Can't verify E-mail address! Please check your email address.");
                                                    }
                                                } else {
                                                    $options['msg'] .= '<br/>' . _("Your email address is not valid");
                                                }
                                            }
                                            if ($udb->isNotUser($user)) {
                                                if (!empty($DBInfo->no_register)) {
                                                    $options['msg'] = _("Fail to register");
                                                    $options['err'] = _("You are not allowed to register on this wiki");
                                                    $options['err'] .= "\n" . _("Please contact WikiMasters");
                                                    do_invalid($formatter, $options);
                                                    return;
                                                }
                                                $title = sprintf(_("Successfully added as '%s'"), _html_escape($user->id));
                                                $options['id'] = $user->id;
                                                $ticket = md5(time() . $user->id . $options['email']);
                                                $user->info['eticket'] = $ticket . "." . $options['email'];
                                                if (!empty($DBInfo->use_safelogin)) {
                                                    $options['msg'] = sprintf(_("Successfully added as '%s'"), $user->id);
                                                    $options['msg'] .= '<br />' . _("Please check your mailbox");
                                                }
                                                $args = array();
                                                if ($options['email'] == $id or !empty($DBInfo->register_confirm_email)) {
                                                    $args = array('suspended' => 1);
                                                }
                                                if (!empty($DBInfo->register_confirm_admin)) {
                                                    $args = array('suspended' => 1);
                                                }
                                                if (!empty($DBInfo->register_confirm_admin)) {
                                                    if (!empty($options['msg'])) {
                                                        $options['msg'] .= '<br />';
                                                    }
                                                    $options['msg'] .= _("Your need to wait until your ID activated by admin");
                                                }
                                                // save join agreement
                                                if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) {
                                                    $user->info['join_agreement'] = 'agree';
                                                    if (!empty($DBInfo->agreement_version)) {
                                                        $user->info['join_agreement_version'] = $DBInfo->agreement_version;
                                                    }
                                                }
                                                if (empty($DBInfo->use_safelogin) && empty($args['suspended'])) {
                                                    $formatter->header($user->setCookie());
                                                }
                                                $ret = $udb->addUser($user, $args);
                                                # XXX
                                                if (!empty($options['email']) and preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) {
                                                    $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation");
                                                    $body = '';
                                                    if (!empty($DBInfo->email_register_header) and file_exists($DBInfo->email_register_header)) {
                                                        $body = file_get_contents($DBInfo->email_register_header);
                                                        $body = str_replace(array('@sitename@'), array($DBInfo->sitename), $body);
                                                    }
                                                    $body .= _("Please confirm your email address") . "\n\n";
                                                    $body .= qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}"));
                                                    $body .= "\n";
                                                    if (!empty($DBInfo->use_safelogin)) {
                                                        $body .= "\n" . sprintf(_("Your initial password is %s"), $mypass) . "\n\n";
                                                        $body .= _("Please change your password later") . "\n";
                                                    }
                                                    $ret = wiki_sendmail($body, $options);
                                                    if (is_array($ret)) {
                                                        $options['msg'] .= $ret['msg'];
                                                    } else {
                                                        $options['msg'] .= '<br/>' . _("Confirmation E-mail sent");
                                                    }
                                                }
                                            } else {
                                                # already exist user
                                                $user = $udb->getUser($user->id);
                                                if ($user->checkPasswd($options['password']) === true) {
                                                    $options['msg'] .= sprintf(_("Successfully login as '%s'"), $id);
                                                    $options['id'] = $user->id;
                                                    $formatter->header($user->setCookie());
                                                    $udb->saveUser($user);
                                                    # XXX
                                                } else {
                                                    $title = _("Invalid password !");
                                                }
                                            }
                                        }
                                    } else {
                                        if (empty($title)) {
                                            $title = _("Invalid username !");
                                        }
                                    }
                                }
                            } else {
                                if ($user->id != "Anonymous") {
                                    # save profile
                                    $udb =& $DBInfo->udb;
                                    $userinfo = $udb->getUser($user->id);
                                    if (!empty($options['password']) and !empty($options['passwordagain'])) {
                                        $chall = 0;
                                        if (!empty($DBInfo->use_safelogin)) {
                                            if (isset($options['_chall'])) {
                                                $chall = $options['challenge'];
                                            } else {
                                                $chall = rand(100000);
                                                $options['password'] = hmac($chall, $options['password']);
                                            }
                                        }
                                        //echo 'chall=',$chall,' ',$options['password'];
                                        if ($userinfo->checkPasswd($options['password'], $chall) === true) {
                                            if ($DBInfo->use_safelogin) {
                                                $mypass = md5($options['passwordagain']);
                                                // XXX
                                                $ret = $userinfo->setPasswd($mypass, $mypass, 1);
                                            } else {
                                                $ret = $userinfo->setPasswd($options['passwordagain']);
                                            }
                                            if ($ret <= 0) {
                                                if ($ret == 0) {
                                                    $title = _("too short password!");
                                                } else {
                                                    if ($ret == -1) {
                                                        $title = _("mismatch password !");
                                                    } else {
                                                        if ($ret == -2) {
                                                            $title = _("not acceptable character found in the password!");
                                                        }
                                                    }
                                                }
                                                $options['msg'] = _("Password is not changed !");
                                            } else {
                                                $title = _("Password is changed !");
                                                if ($ret < 8) {
                                                    $options['msg'] = _("Password is too simple to use as a password !");
                                                }
                                            }
                                        } else {
                                            $title = _("Invalid password !");
                                            $options['msg'] = _("Password is not changed !");
                                        }
                                    }
                                    if (isset($options['user_css'])) {
                                        $userinfo->info['css_url'] = $options['user_css'];
                                    }
                                    if (isset($options['timezone'])) {
                                        list($hour, $min) = explode(':', $options['timezone']);
                                        $min = $min * 60;
                                        $min = $hour < 0 ? -1 * $min : $min;
                                        $tz_offset = $hour * 3600 + $min;
                                        $userinfo->info['tz_offset'] = $tz_offset;
                                    }
                                    if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) {
                                        $userinfo->info['join_agreement'] = 'agree';
                                        if (!empty($DBInfo->agreement_version)) {
                                            $userinfo->info['join_agreement_version'] = $DBInfo->agreement_version;
                                        }
                                    }
                                    $button_check_email_again = !empty($options['button_check_email_again']) ? 1 : 0;
                                    if ($button_check_email_again and !empty($userinfo->info['eticket'])) {
                                        list($dummy, $email) = explode('.', $userinfo->info['eticket'], 2);
                                        if (!empty($email)) {
                                            $options['email'] = $email;
                                        }
                                    }
                                    if (!empty($options['email']) and $options['email'] != $userinfo->info['email']) {
                                        if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) {
                                            if (($ret = verify_email($options['email'])) < 0) {
                                                $ret = -$ret;
                                                $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret;
                                                $options['msg'] .= '<br />' . _("Invalid email address or can't verify it.");
                                            } else {
                                                $ticket = md5(time() . $userinfo->info['id'] . $options['email']);
                                                $userinfo->info['eticket'] = $ticket . "." . $options['email'];
                                                $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation");
                                                $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}"));
                                                $body = _("Please confirm your email address") . "\n" . $body;
                                                $ret = wiki_sendmail($body, $options);
                                                if (is_array($ret)) {
                                                    $options['msg'] = $ret['msg'];
                                                } else {
                                                    $options['msg'] = _("E-mail confirmation mail sent");
                                                }
                                            }
                                        } else {
                                            $options['msg'] = _("Your email address is not valid");
                                        }
                                    }
                                    if (!empty($userinfo->info['idtype']) and $userinfo->info['idtype'] == 'openid' and isset($options['nick']) and $options['nick'] != $userinfo->info['nick']) {
                                        $nick = $userinfo->getID($options['nick']);
                                        // nickname check XXX
                                        if (!$udb->_exists($nick)) {
                                            $userinfo->info['nick'] = $nick;
                                        } else {
                                            $options['msg'] = _("Your Nickname already used as ID in this wiki");
                                        }
                                    }
                                    $udb->saveUser($userinfo);
                                    #$options['css_url']=$options['user_css'];
                                    if (!isset($options['msg'])) {
                                        $options['msg'] = _("Profiles are saved successfully !");
                                    }
                                } else {
                                    if ($user->id == "Anonymous" and isset($options['openid_url'])) {
                                        # login with openid
                                        include_once 'lib/openid.php';
                                        session_start();
                                        $process_url = qualifiedUrl($formatter->link_url("UserPreferences", "?action=userform"));
                                        $trust_root = qualifiedUrl($formatter->link_url(""));
                                        $openid = new SimpleOpenID();
                                        $openid->SetIdentity($options['openid_url']);
                                        $openid->SetTrustRoot($trust_root);
                                        $openid->SetRequiredFields(array('nickname', 'email', 'fullname'));
                                        $openid->SetOptionalFields(array('language', 'timezone'));
                                        if ($openid->GetOpenIDServer()) {
                                            $openid->SetApprovedURL($process_url);
                                            // Send Response from OpenID server to this script
                                            $openid->Redirect();
                                            // This will redirect user to OpenID Server
                                            return;
                                        } else {
                                            $error = $openid->GetError();
                                            #echo "ERROR CODE: " . $error['code'] . "<br>";
                                            #echo "ERROR DESCRIPTION: " . $error['description'] . "<br>";
                                            $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']);
                                        }
                                    } else {
                                        if (!empty($options['openid_mode']) and $options['openid_mode'] == 'id_res') {
                                            // OpenID result
                                            include_once 'lib/openid.php';
                                            if (!preg_match('/utf-?8/i', $DBInfo->charset)) {
                                                $options['openid_sreg_nickname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_nickname']);
                                                $options['openid_sreg_fullname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_fullname']);
                                            }
                                            $openid = new SimpleOpenID();
                                            $openid->SetIdentity($options['openid_identity']);
                                            $openid_validation_result = $openid->ValidateWithServer();
                                            if ($openid_validation_result == true) {
                                                // OK HERE KEY IS VALID
                                                $userdb =& $DBInfo->udb;
                                                // XXX
                                                $user->setID($options['openid_identity']);
                                                // XXX
                                                if (!empty($options['openid_language'])) {
                                                    $user->info['language'] = strtolower($options['openid_sreg_language']);
                                                }
                                                //$user->info['tz_offset']=$options['openid_timezone'];
                                                if ($userdb->_exists($options['openid_identity'])) {
                                                    $user = $userdb->getUser($options['openid_identity']);
                                                    $user->info['idtype'] = 'openid';
                                                    $options['msg'] .= sprintf(_("Successfully login as '%s' via OpenID."), $options['openid_identity']);
                                                    $formatter->header($user->setCookie());
                                                    $userdb->saveUser($user);
                                                    // always save
                                                } else {
                                                    if (!empty($DBInfo->no_register) and $DBInfo->no_register == 1) {
                                                        $options['msg'] = _("Fail to register");
                                                        $options['err'] = _("You are not allowed to register on this wiki");
                                                        $options['err'] .= "\n" . _("Please contact WikiMasters");
                                                        do_invalid($formatter, $options);
                                                        return;
                                                    }
                                                    if ($options['openid_sreg_nickname']) {
                                                        $nick = $user->getID($options['openid_sreg_nickname']);
                                                        if (!$userdb->_exists($nick)) {
                                                            $user->info['nick'] = $nick;
                                                        } else {
                                                            $options['msg'] = sprintf(_("Your Nickname %s already used as ID in this Wiki."), $nick);
                                                        }
                                                    }
                                                    $user->info['email'] = $options['openid_sreg_email'];
                                                    $user->info['idtype'] = 'openid';
                                                    $userdb->addUser($user);
                                                    $formatter->header($user->setCookie());
                                                    $userdb->saveUser($user);
                                                    $options["msg"] .= sprintf(_("OpenID Authentication successful and saved as %s."), $options['openid_identity']);
                                                }
                                                $options['id'] = $user->id;
                                            } else {
                                                if ($openid->IsError() == true) {
                                                    // ON THE WAY, WE GOT SOME ERROR
                                                    $error = $openid->GetError();
                                                    $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']);
                                                } else {
                                                    // Signature Verification Failed
                                                    $options["msg"] = _("Invalid OpenID Authentication request");
                                                    echo "INVALID AUTHORIZATION";
                                                }
                                            }
                                        } else {
                                            if (!empty($DBInfo->use_agreement) and $options['login'] == _("Make profile")) {
                                                $options['agreement'] = 1;
                                                $form = macro_UserPreferences($formatter, '', $options);
                                            } else {
                                                $options["msg"] = _("Invalid request");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    $myrefresh = '';
    if (!empty($DBInfo->use_refresh) and !empty($use_refresh)) {
        $sec = $DBInfo->use_refresh - 1;
        if (!empty($options['return_url'])) {
            $lnk = $options['return_url'];
        } else {
            $lnk = $formatter->link_url($formatter->page->urlname, '?action=show');
        }
        $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
    }
    $formatter->send_header($myrefresh, $options);
    $formatter->send_title($title, "", $options);
    if (!$title && (empty($DBInfo->control_read) or $DBInfo->security->is_allowed('read', $options))) {
        $lnk = $formatter->link_to('?action=show');
        if (empty($form)) {
            echo sprintf(_("return to %s"), $lnk);
        } else {
            echo $form;
        }
    } else {
        if (!empty($form)) {
            print $form;
        }
        #    else $formatter->send_page("Goto UserPreferences");
    }
    $formatter->send_footer("", $options);
}
Exemplo n.º 11
0
function do_gallery($formatter, $options = '')
{
    global $DBInfo;
    $COLS_MSIE = 80;
    $COLS_OTHER = 85;
    $cols = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? $COLS_MSIE : $COLS_OTHER;
    $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 4;
    $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols;
    if (!empty($options['comments']) and !$DBInfo->security->is_valid_password($options['passwd'], $options)) {
        $title = sprintf('Invalid password !');
        $formatter->send_header("", $options);
        $formatter->send_title($title);
        $formatter->send_footer();
        return;
    }
    $ret = macro_Gallery($formatter, '', $options);
    if (isset($options['passwd']) and !empty($options['comments'])) {
        $options['msg'] = sprintf(_("Go back or return to %s"), $formatter->link_tag($formatter->page->urlname, "", $options['page']));
        $options['title'] = _("Comments are edited");
    } else {
        if (!empty($options['comment'])) {
            if (!$options['err']) {
                $options['msg'] = sprintf(_("Go back or return to %s"), $formatter->link_tag($formatter->page->urlname, "", $options['page']));
                $options['title'] = _("Comments is added");
            } else {
                $options['msg'] =& $options['err'];
            }
        }
    }
    if (!$options['value']) {
        $formatter->send_header("", $options);
        $formatter->send_title("", "", $options);
        print $ret;
    } else {
        if (!empty($options['comment']) or !empty($options['comments']) and !empty($options['passwd'])) {
            $myrefresh = '';
            if (!$options['err'] and $DBInfo->use_save_refresh) {
                $sec = $DBInfo->use_save_refresh;
                $lnk = $formatter->link_url($formatter->page->urlname, "?action=show");
                $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk);
            }
            $formatter->send_header($myrefresh, $options);
            $formatter->send_title("", "", $options);
            #$formatter->send_page('',$options);
        } else {
            if (!empty($options['comments']) and !empty($options['admin']) and empty($options['passwd'])) {
                // admin form
                $rows += 5;
                $formatter->send_header("", $options);
                $formatter->send_title("", "", $options);
                print $ret;
                $url = $formatter->link_url($formatter->page->urlname);
                $form = "<form method='post' action='{$url}'>\n";
                $form .= <<<FORM
<textarea class="wiki" id="content" wrap="virtual" name="comments"
 rows="{$rows}" cols="{$cols}" class="wiki">
FORM;
                $form .= $options['comments'];
                $form .= '</textarea><br />';
                $form .= <<<FORM2
<input type="hidden" name="action" value="gallery" />
<input type="hidden" name="value" value="{$options['value']}" />
password: <input type='password' name='passwd' />
<input type="submit" value="Save" />&nbsp;
<input type="reset" value="Reset" />&nbsp;
</form>
FORM2;
                print $form;
            } else {
                if (empty($options['comment'])) {
                    // add comment form
                    $formatter->send_header("", $options);
                    $formatter->send_title("", "", $options);
                    print $ret;
                    $url = $formatter->link_url($formatter->page->urlname);
                    $form = "<form method='post' action='{$url}'>\n";
                    $form .= "<input name='admin' type='submit' value='Admin' /><br />\n";
                    $form .= "<b>Name or Email</b>: <input name='name' size='30' maxlength='30' style='width:200' /><br />\n";
                    $form .= <<<FORM
<textarea class="wiki" id="content" wrap="virtual" name="comment"
 rows="{$rows}" cols="{$cols}" class="wiki"></textarea><br />
FORM;
                    $form .= <<<FORM2
<input type="hidden" name="action" value="gallery" />
<input type="hidden" name="value" value="{$options['value']}" />
<input type="submit" value="Save" />&nbsp;
<input type="reset" value="Reset" />&nbsp;
</form>
FORM2;
                    print $form;
                }
            }
        }
    }
    if (!in_array('UploadFile', $formatter->actions)) {
        $formatter->actions[] = 'UploadFile';
    }
    $formatter->send_footer("", $options);
    return;
}
Exemplo n.º 12
0
function do_atom($formatter, $options)
{
    global $DBInfo;
    global $_release;
    define('ATOM_DEFAULT_DAYS', 7);
    $days = $DBInfo->rc_days ? $DBInfo->rc_days : ATOM_DEFAULT_DAYS;
    $options['quick'] = 1;
    if ($options['c']) {
        $options['items'] = $options['c'];
    }
    $lines = $DBInfo->editlog_raw_lines($days, $options);
    $time_current = time();
    #  $secs_per_day= 60*60*24;
    #  $days_to_show= 30;
    #  $time_cutoff= $time_current - ($days_to_show * $secs_per_day);
    $URL = qualifiedURL($formatter->prefix);
    $img_url = qualifiedURL($DBInfo->logo_img);
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $surl = qualifiedUrl($formatter->link_url($options['page'] . '?action=atom'));
    $channel = <<<CHANNEL
  <title>{$DBInfo->sitename}</title>
  <link href="{$url}"></link>
  <link rel="self" type="application/atom+xml" href="{$surl}" />
  <subtitle>RecentChanges at {$DBInfo->sitename}</subtitle>
  <generator version="{$_release}">MoniWiki Atom feeder</generator>

CHANNEL;
    $items = "";
    $ratchet_day = FALSE;
    if (!$lines) {
        $lines = array();
    }
    foreach ($lines as $line) {
        $parts = explode("\t", $line);
        $page_name = $DBInfo->keyToPagename($parts[0]);
        $addr = $parts[1];
        $ed_time = $parts[2];
        $user = $parts[4];
        $user_uri = '';
        if ($DBInfo->hasPage($user)) {
            $user_uri = $formatter->link_url(_rawurlencode($user), "", $user);
            $user_uri = '<uri>' . $user_uri . '</uri>';
        }
        $log = _stripslashes($parts[5]);
        $act = rtrim($parts[6]);
        $url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name)));
        $diff_url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name), '?action=diff'));
        $extra = "<br /><a href='{$diff_url}'>" . _("show changes") . "</a>\n";
        $content = '';
        if (!$DBInfo->hasPage($page_name)) {
            $status = 'deleted';
            $content = "<content type='html'><a href='{$url}'>{$page_name}</a> is deleted</content>\n";
        } else {
            $status = 'updated';
            if ($options['diffs']) {
                $p = new WikiPage($page_name);
                $f = new Formatter($p);
                $options['raw'] = 1;
                $options['nomsg'] = 1;
                $html = $f->macro_repl('Diff', '', $options);
                if (!$html) {
                    ob_start();
                    $f->send_page('', array('fixpath' => 1));
                    #$f->send_page('');
                    $html = ob_get_contents();
                    ob_end_clean();
                    $extra = '';
                }
                $content = "  <content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>{$html}</content>\n";
            } else {
                if ($log) {
                    $html = str_replace('&', '&amp;', $log);
                    $content = "<content type='text'>" . $html . "</content>\n";
                } else {
                    $content = "<content type='text'>updated</content>\n";
                }
            }
        }
        $zone = '+00:00';
        $date = gmdate("Y-m-d\\TH:i:s", $ed_time) . $zone;
        if (!isset($updated)) {
            $updated = $date;
        }
        #$datetag = gmdate("YmdHis",$ed_time);
        $valid_page_name = str_replace('&', '&amp;', $page_name);
        $items .= "<entry>\n";
        $items .= "  <title>{$valid_page_name}</title>\n";
        $items .= "  <link href='{$url}'></link>\n";
        $items .= '  ' . $content;
        $items .= "  <author><name>{$user}</name>{$user_uri}</author>\n";
        $items .= "  <updated>{$date}</updated>\n";
        $items .= "  <contributor><name>{$user}</name>{$user_uri}</contributor>\n";
        $items .= "</entry>\n";
    }
    $updated = "  <updated>{$updated}</updated>\n";
    $new = "";
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $out = $head . $channel . $items . $form;
            $new = iconv($DBInfo->charset, $charset, $out);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<!--<?xml-stylesheet href="{$DBInfo->url_prefix}/css/_feed.css" type="text/css"?>-->
<feed xmlns="http://www.w3.org/2005/Atom">
<!--
    Add "diffs=1" to add change diffs to the description of each items.
    Add "oe=utf-8" to convert the charset of this rss to UTF-8.
-->

HEAD;
    header("Content-Type: application/xml");
    if ($new) {
        print $head . $new;
    } else {
        print $head . $channel . $updated . $items . $form;
    }
    print "</feed>\n";
}
Exemplo n.º 13
0
function do_atom($formatter, $options)
{
    global $DBInfo, $Config;
    global $_release;
    define('ATOM_DEFAULT_DAYS', 7);
    // get members to hide log
    $members = $DBInfo->members;
    $days = $DBInfo->rc_days ? $DBInfo->rc_days : ATOM_DEFAULT_DAYS;
    $options['quick'] = 1;
    if ($options['c']) {
        $options['items'] = $options['c'];
    }
    $lines = $DBInfo->editlog_raw_lines($days, $options);
    // HTTP conditional get
    $mtime = $DBInfo->mtime();
    $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime);
    $cache_ttl = !empty($DBInfo->atom_ttl) ? $DBInfo->atom_ttl : 60 * 30;
    /* 30 minutes */
    // make etag based on some options and mtime.
    $check_opts = array('quick', 'items', 'c');
    $check = array();
    foreach ($check_opts as $c) {
        if (isset($options[$c])) {
            $check[$c] = $options[$c];
        }
    }
    $etag = md5($mtime . $DBInfo->logo_img . serialize($check) . $cache_ttl . $options['id']);
    $headers = array();
    $headers[] = 'Pragma: cache';
    $maxage = $cache_ttl;
    $public = 'public';
    if ($options['id'] != 'Anonymous') {
        $public = 'private';
    }
    $headers[] = 'Cache-Control: ' . $public . ', max-age=' . $maxage;
    $headers[] = 'Last-Modified: ' . $lastmod;
    $headers[] = 'ETag: "' . $etag . '"';
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        $headers[] = 'HTTP/1.0 304 Not Modified';
    }
    foreach ($headers as $h) {
        header($h);
    }
    if (!$need) {
        @ob_end_clean();
        return;
    }
    $cache = new Cache_Text('atom');
    $cache_delay = min($cache_ttl, 30);
    $mtime = $cache->mtime($etag);
    $time_current = time();
    $val = false;
    if (empty($formatter->refresh)) {
        if (($val = $cache->fetch($etag)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) {
            header("Content-Type: application/xml");
            echo $val;
            return;
        }
    }
    // need to update cache
    if ($val !== false and $cache->exists($etag . '.lock')) {
        header("Content-Type: application/xml");
        echo $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->';
        return;
    }
    if ($cache->exists($etag . '.lock')) {
        header("Content-Type: application/xml");
        echo '';
        return;
    }
    $cache->update($etag . '.lock', array('lock'), 30);
    // 30s lock
    $URL = qualifiedURL($formatter->prefix);
    $img_url = qualifiedURL($DBInfo->logo_img);
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $surl = qualifiedUrl($formatter->link_url($options['page'] . '?action=atom'));
    $channel = <<<CHANNEL
  <title>{$DBInfo->sitename}</title>
  <link href="{$url}"></link>
  <link rel="self" type="application/atom+xml" href="{$surl}" />
  <subtitle>RecentChanges at {$DBInfo->sitename}</subtitle>
  <generator version="{$_release}">MoniWiki Atom feeder</generator>

CHANNEL;
    $items = "";
    $ratchet_day = FALSE;
    if (!$lines) {
        $lines = array();
    }
    foreach ($lines as $line) {
        $parts = explode("\t", $line);
        $page_name = $DBInfo->keyToPagename($parts[0]);
        // hide log
        if (!empty($members) && !in_array($options['id'], $members) && !empty($Config['ruleset']['hidelog'])) {
            if (in_array($page_name, $Config['ruleset']['hidelog'])) {
                continue;
            }
        }
        $addr = $parts[1];
        $ed_time = $parts[2];
        $user = $parts[4];
        $user_uri = '';
        if ($user != 'Anonymous' && $DBInfo->hasPage($user)) {
            $user_uri = $formatter->link_url(_rawurlencode($user), "", $user);
            $user_uri = '<uri>' . $user_uri . '</uri>';
        }
        $log = _stripslashes($parts[5]);
        $act = rtrim($parts[6]);
        $url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name)));
        $diff_url = qualifiedUrl($formatter->link_url(_rawurlencode($page_name), '?action=diff'));
        $extra = "<br /><a href='{$diff_url}'>" . _("show changes") . "</a>\n";
        $content = '';
        if (!$DBInfo->hasPage($page_name)) {
            $status = 'deleted';
            $content = "<content type='html'><a href='{$url}'>{$page_name}</a> is deleted</content>\n";
        } else {
            $status = 'updated';
            if ($options['diffs']) {
                $p = new WikiPage($page_name);
                $f = new Formatter($p);
                $options['raw'] = 1;
                $options['nomsg'] = 1;
                $html = $f->macro_repl('Diff', '', $options);
                if (!$html) {
                    ob_start();
                    $f->send_page('', array('fixpath' => 1));
                    #$f->send_page('');
                    $html = ob_get_contents();
                    ob_end_clean();
                    $extra = '';
                }
                $content = "  <content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>{$html}</content>\n";
            } else {
                if ($log) {
                    $html = str_replace('&', '&amp;', $log);
                    $content = "<content type='text'>" . $html . "</content>\n";
                } else {
                    $content = "<content type='text'>updated</content>\n";
                }
            }
        }
        $zone = '+00:00';
        $date = gmdate("Y-m-d\\TH:i:s", $ed_time) . $zone;
        if (!isset($updated)) {
            $updated = $date;
        }
        #$datetag = gmdate("YmdHis",$ed_time);
        $valid_page_name = str_replace('&', '&amp;', $page_name);
        $items .= "<entry>\n";
        $items .= "  <title>{$valid_page_name}</title>\n";
        $items .= "  <link href='{$url}'></link>\n";
        $items .= '  ' . $content;
        $items .= "  <author><name>{$user}</name>{$user_uri}</author>\n";
        $items .= "  <updated>{$date}</updated>\n";
        $items .= "  <contributor><name>{$user}</name>{$user_uri}</contributor>\n";
        $items .= "</entry>\n";
    }
    $updated = "  <updated>{$updated}</updated>\n";
    $new = "";
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $out = $head . $channel . $items . $form;
            $new = iconv($DBInfo->charset, $charset, $out);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<!--<?xml-stylesheet href="{$DBInfo->url_prefix}/css/_feed.css" type="text/css"?>-->
<feed xmlns="http://www.w3.org/2005/Atom">
<!--
    Add "diffs=1" to add change diffs to the description of each items.
    Add "oe=utf-8" to convert the charset of this rss to UTF-8.
-->

HEAD;
    header("Content-Type: application/xml");
    $out = '';
    if ($new) {
        $out = $head . $new;
    } else {
        $out = $head . $channel . $updated . $items . $form;
    }
    $out .= "</feed>\n";
    echo $out;
    $cache->update($etag, $out);
    $cache->remove($etag . '.lock');
}
Exemplo n.º 14
0
function macro_ShareButtons($formatter, $value = '', $params)
{
    global $DBInfo;
    $lang = $DBInfo->lang;
    $btn = _("tweet");
    $link = $formatter->link_url($formatter->page->urlname);
    $href = qualifiedURL($link);
    $ehref = urlencode($href);
    // fix for twitter
    if (!$formatter->page->exists()) {
        return '';
    }
    if ($value == 'nojs') {
        $fb = '<li><a class="facebook" href="https://www.facebook.com/sharer/sharer.php?u=' . $href . '" target="_blank"><span>' . _("fb") . '</span></a></li>';
        $gplus = '<li><a class="gplus" href="https://plus.google.com/share?url=' . $href . '" target="_blank"><span>' . _("g+") . '</span></a></li>';
        $twitter = '<li><a class="twitter" href="https://twitter.com/share?url=' . $ehref . '" target="_blank"><span>' . $btn . '</span></a></li>';
        $oc = new Cache_text('opengraph');
        $pin = '';
        if (($val = $oc->fetch($formatter->page->name)) !== false) {
            if (!empty($val['image'])) {
                $image = $val['image'];
                $image_href = urlencode(str_replace('&amp;', '&', $image));
                // fix
                $pin = '<li><a class="pinterest" href="https://pinterest.com/pin/create/button/?url=' . $ehref . '&amp;description=' . _urlencode($val['description']) . '&amp;media=' . $image_href . '" target="_blank"><span>' . _("pin") . '</span></a></li>';
            }
        }
        return '<div class="share-buttons"><ul>' . $pin . ' ' . $fb . ' ' . $twitter . ' ' . $gplus . '</ul></div>';
    }
    $twitter_attr = '';
    $facebook_attr = 'data-layout="button_count"';
    $gplus_attr = ' data-size="medium"';
    if ($value == 'vertical' or $value == 'vert') {
        $twitter_attr = ' data-count="vertical"';
        $gplus_attr = ' data-size="tall"';
        $facebook_attr = 'data-layout="box_count"';
    } else {
        if ($value == 'icon') {
            $twitter_attr = ' data-count="none"';
            $gplus_attr = ' data-annotation="none" data-size="tall"';
            $facebook_attr = 'data-layout="button"';
        }
    }
    $twitter = <<<EOF
<a href="https://twitter.com/share" class="twitter-share-button" data-url="{$href}" data-lang="{$lang}" data-dnt="true"{$twitter_attr}>{$btn}</a>
EOF;
    $js = <<<EOF
<script type="text/javascript">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
EOF;
    $formatter->register_javascripts($js);
    $gplus = <<<EOF
<div class="g-plusone" data-href="{$href}"{$gplus_attr}></div>
EOF;
    $js = <<<EOF
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>
EOF;
    $formatter->register_javascripts($js);
    $js = <<<EOF
<script type="text/javascript">(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/ko_KR/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

EOF;
    $formatter->register_javascripts($js);
    $fb = <<<EOF
<div class="fb-like"
data-href="{$href}"
data-width="450"
data-action="recommend"
data-show-faces="false"
{$facebook_attr}
data-send="false"></div>
EOF;
    return '<div class="share-buttons">' . $fb . ' ' . $twitter . ' ' . $gplus . '</div>';
}
Exemplo n.º 15
0
function macro_RecentChanges($formatter, $value = '', $options = '')
{
    global $DBInfo;
    $checknew = 1;
    $checkchange = 0;
    $template_bra = "";
    $template = '"$icon&nbsp;&nbsp;$title$updated $date . . . . $user $count$diff $extra<br />\\n"';
    $template_cat = "";
    $use_day = 1;
    $users = array();
    $target = '';
    if (!empty($options['target'])) {
        $target = "target='{$options['target']}'";
    }
    $bookmark_action = empty($options['action']) ? '?action=bookmark' : '?action=' . $options['action'];
    // $date_fmt='D d M Y';
    $date_fmt = $DBInfo->date_fmt_rc;
    $days = !empty($DBInfo->rc_days) ? $DBInfo->rc_days : RC_DEFAULT_DAYS;
    $perma_icon = $formatter->perma_icon;
    $changed_time_fmt = $DBInfo->changed_time_fmt;
    $args = explode(',', $value);
    // first arg assumed to be a date fmt arg
    if (preg_match("/^[\\s\\/\\-:aABdDFgGhHiIjmMOrSTY\\[\\]]+\$/", $args[0])) {
        $my_date_fmt = $args[0];
    }
    $strimwidth = isset($DBInfo->rc_strimwidth) ? $DBInfo->rc_strimwidth : 20;
    // use javascript
    $use_js = 0;
    // show last edit entry only
    $last_entry_only = 1;
    $last_entry_check = 60 * 60 * 24;
    // show last editor only
    $last_editor_only = 1;
    // show editrange like as MoinMoin
    $use_editrange = 0;
    // avatar
    $use_avatar = 0;
    $avatar_type = 'identicon';
    if (!empty($DBInfo->use_avatar)) {
        $use_avatar = 1;
        if (is_string($DBInfo->use_avatar)) {
            $avatar_type = $DBInfo->use_avatar;
        }
    }
    $avatarlink = qualifiedUrl($formatter->link_url('', '?action=' . $avatar_type . '&amp;seed='));
    $trash = 0;
    $rctype = '';
    $bra = '';
    $cat = '';
    $cat0 = '';
    $rctitle = "<h2>" . _("Recent Changes") . "</h2>";
    foreach ($args as $arg) {
        $arg = trim($arg);
        if (($p = strpos($arg, '=')) !== false) {
            $k = trim(substr($arg, 0, $p));
            $v = trim(substr($arg, $p + 1));
            if ($k == 'item' or $k == 'items') {
                $opts['items'] = min((int) $v, RC_MAX_ITEMS);
            } else {
                if ($k == 'days') {
                    $days = min(abs($v), RC_MAX_DAYS);
                } else {
                    if ($k == "datefmt") {
                        $my_date_fmt = $v;
                    } else {
                        if ($k == 'ago') {
                            if (is_numeric($v) and $v == abs($v)) {
                                $opts['ago'] = abs($v);
                            } else {
                                $opts['from'] = $v;
                            }
                        } else {
                            if ($k == "new") {
                                $checknew = $v;
                            } else {
                                if ($k == 'strimwidth' and is_numeric($v) and (abs($v) > 15 or $v == 0)) {
                                    $strimwidth = abs($v);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            if ($arg == "quick") {
                $opts['quick'] = 1;
            } else {
                if ($arg == "nonew") {
                    $checknew = 0;
                } else {
                    if ($arg == "change") {
                        $checkchange = 1;
                    } else {
                        if ($arg == "showhost") {
                            $showhost = 1;
                        } else {
                            if ($arg == "comment") {
                                $comment = 1;
                            } else {
                                if ($arg == "comments") {
                                    $comment = 1;
                                } else {
                                    if ($arg == "nobookmark") {
                                        $nobookmark = 1;
                                    } else {
                                        if ($arg == "noperma") {
                                            $perma_icon = '';
                                        } else {
                                            if ($arg == "button") {
                                                $button = 1;
                                            } else {
                                                if ($arg == "timesago") {
                                                    $timesago = 1;
                                                } else {
                                                    if ($arg == "notitle") {
                                                        $rctitle = '';
                                                    } else {
                                                        if ($arg == "hits") {
                                                            $use_hits = 1;
                                                        } else {
                                                            if ($arg == "daysago") {
                                                                $use_daysago = 1;
                                                            } else {
                                                                if ($arg == "trash") {
                                                                    $trash = 1;
                                                                } else {
                                                                    if ($arg == "editrange") {
                                                                        $use_editrange = 1;
                                                                    } else {
                                                                        if ($arg == "allauthors") {
                                                                            $last_editor_only = 0;
                                                                        } else {
                                                                            if ($arg == "allusers") {
                                                                                $last_editor_only = 0;
                                                                            } else {
                                                                                if ($arg == "allentries") {
                                                                                    $last_entry_only = 0;
                                                                                } else {
                                                                                    if ($arg == "avatar") {
                                                                                        $use_avatar = 1;
                                                                                    } else {
                                                                                        if ($arg == "noavatar") {
                                                                                            $use_avatar = 0;
                                                                                        } else {
                                                                                            if ($arg == "js") {
                                                                                                $use_js = 1;
                                                                                            } else {
                                                                                                if ($arg == "diffwidth") {
                                                                                                    $use_diffwidth = 1;
                                                                                                } else {
                                                                                                    if (in_array($arg, array('simple', 'moztab', 'board', 'table', 'list'))) {
                                                                                                        $rctype = $arg;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // set as dynamic macro or not.
    if ($formatter->_macrocache and empty($options['call'])) {
        // and empty($use_js))
        return $formatter->macro_cache_repl('RecentChanges', $value);
    }
    $formatter->_dynamic_macros['@RecentChanges'] = 1;
    if (empty($DBInfo->interwiki)) {
        $formatter->macro_repl('InterWiki', '', array('init' => 1));
    }
    // reset some conflict params
    if (empty($DBInfo->use_counter)) {
        $use_hits = 0;
    }
    if (empty($DBInfo->show_hosts)) {
        $showhost = 0;
    }
    if (!empty($rctype)) {
        if ($rctype == "simple") {
            $checkchange = 0;
            $use_day = 0;
            if ($showhost) {
                $template = '"$icon&nbsp;&nbsp;$title @ $day $date by $user $count $extra<br />\\n"';
            } else {
                $template = '"$icon&nbsp;&nbsp;$title @ $day $date $count $extra<br />\\n"';
            }
        } else {
            if ($rctype == "list") {
                $rctitle = '';
                $changed_time_fmt = !empty($my_date_fmt) ? $my_date_fmt : '[H:i]';
                $checkchange = 0;
                $use_day = 0;
                $template = '"$date $title<br />\\n"';
            } else {
                if ($rctype == "moztab") {
                    $use_day = 1;
                    $template = '"<li>$title $date</li>\\n"';
                } else {
                    if ($rctype == "table") {
                        $bra = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
                        $template = '"<tr><td style=\'white-space:nowrap;width:2%\'>$icon</td><td style=\'width:40%\'>$title$updated</td><td class=\'date\' style=\'width:15%\'>$date</td><td>$user $count$diff $extra</td></tr>\\n"';
                        $cat = "</table>";
                        $cat0 = "";
                    } else {
                        if ($rctype == "board") {
                            $changed_time_fmt = !empty($my_date_fmt) ? $my_date_fmt : 'm-d [H:i]';
                            $use_day = 0;
                            $template_bra = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
                            if (empty($nobookmark)) {
                                $cols = 3;
                            } else {
                                $cols = 2;
                            }
                            $template_bra .= "<thead><tr><th colspan='{$cols}' class='title'>" . _("Title") . "</th>";
                            if (!empty($showhost)) {
                                $template_bra .= "<th class='author'>" . _("Editor") . '</th>';
                            }
                            $template_bra .= "<th class='editinfo'>" . _("Changes") . '</th>';
                            if (!empty($use_hits)) {
                                $template_bra .= "<th class='hits'>" . _("Hits") . "</th>";
                            }
                            $template_bra .= "<th class='date'>" . _("Change Date") . '</th>';
                            $template_bra .= "</tr></thead>\n<tbody>\n";
                            $template = '"<tr$alt><td style=\'white-space:nowrap;width:2%\'>$icon</td><td class=\'title\' style=\'width:40%\'>$title$updated</td>';
                            if (empty($nobookmark)) {
                                $template .= '<td>$bmark</td>';
                            }
                            if (!empty($showhost)) {
                                $template .= '<td class=\'author\'>$user</td>';
                            }
                            $template .= '<td class=\'editinfo\'>$count';
                            if (!empty($checkchange) or !empty($checknew)) {
                                $template .= ' $diff';
                            }
                            $template .= '</td>';
                            if (!empty($use_hits)) {
                                $template .= '<td class=\'hits\'>$hits</td>';
                            }
                            $template .= '<td class=\'date\'>$date</td>';
                            $template_extra = $template . '</tr>\\n<tr class=\'log\'$style><td colspan=\'6\'><div>$extra</div></td></tr>\\n"';
                            $template .= '</tr>\\n"';
                            $template_cat = "</tbody></table>";
                            $cat0 = "";
                        }
                    }
                }
            }
        }
    }
    // override days
    $days = !empty($_GET['days']) ? min(abs($_GET['days']), RC_MAX_DAYS) : $days;
    // override ago
    empty($opts['ago']) ? $opts['ago'] = 0 : null;
    if (!empty($_GET['ago']) and is_numeric($_GET['ago'])) {
        $opts['ago'] = abs($_GET['ago']);
    } else {
        $opts['from'] = $_GET['ago'];
    }
    // override times
    // accept both 'item' or 'items'
    $tmp = isset($_GET['item']) ? $_GET['item'] : (isset($_GET['items']) ? $_GET['items'] : null);
    !empty($tmp) ? $opts['items'] = min(abs($tmp), RC_MAX_ITEMS) : null;
    unset($tmp);
    // daysago
    $daysago = '&amp;days=' . $days;
    $daysago = $opts['ago'] ? $daysago . '&amp;ago=' . $opts['ago'] : $daysago;
    $u = $DBInfo->user;
    # retrive user info
    if ($u->id != 'Anonymous') {
        $bookmark = !empty($u->info['bookmark']) ? $u->info['bookmark'] : '';
    } else {
        $bookmark = $u->bookmark;
    }
    $tz_offset = $formatter->tz_offset;
    if (!$bookmark or !empty($nobookmark)) {
        if (!empty($checknew) and preg_match('/^\\d+(\\s*\\*\\s*\\d+)*$/', $checknew)) {
            $checknew = eval('return ' . $checknew . ';');
        }
        if ($checknew > 1) {
            $bookmark = strtotime(date('Y-m-d', time() - $checknew) . ' 00:00:00');
        }
    }
    if (!$bookmark) {
        $bookmark = time();
    }
    if (!empty($nobookmark)) {
        $use_js = 0;
    }
    // set search query
    if (isset($_GET['q'][0])) {
        $query = _preg_search_escape(trim($_GET['q']));
        if (@preg_match('/' . $query . '/', '') === false) {
            unset($query);
        }
    }
    // make rclog uniq key
    $locals = get_defined_vars();
    unset($locals['bookmark']);
    unset($locals['formatter']);
    unset($locals['options']);
    unset($locals['DBInfo']);
    unset($locals['args']);
    unset($locals['arg']);
    unset($locals['u']);
    unset($locals['k']);
    unset($locals['v']);
    $rckey = md5(serialize($locals));
    unset($locals);
    $time_current = time();
    $secs_per_day = 60 * 60 * 24;
    //$time_cutoff= $time_current - ($days * $secs_per_day);
    $lines = $DBInfo->editlog_raw_lines($days, $opts);
    // make a daysago button
    $btnlist = '';
    if (!empty($use_daysago) or !empty($_GET['ago'])) {
        $msg[0] = _("Show changes for ");
        $agolist = array(-$days, $days, 2 * $days, 3 * $days);
        $btn = array();
        $arg = 'days=' . $days . '&amp;ago';
        $msg[1] = _("days ago");
        foreach ($agolist as $d) {
            $d += $opts['ago'];
            if ($d <= 0) {
                continue;
            }
            $link = $formatter->link_tag($formatter->page_urlname, "?{$arg}=" . $d, $d);
            $btn[] = $link;
        }
        #if (sizeof($lines)==0) $btn=array_slice($btn,0,1);
        $btn[] = $formatter->link_tag($formatter->page_urlname, "?{$arg}=...", '...', 'onClick="return daysago(this)"');
        $script = "<script type='text/javascript' src='{$DBInfo->url_prefix}/local/rc.js' ></script>";
        $btnlist = $msg[0] . ' <ul><li>' . implode("</li>\n<li>", $btn) . '</li></ul> ' . $msg[1];
        $btnlist = $script . "<div class='rc-button'>\n" . $btnlist . "</div>\n";
    }
    $rc = new Cache_text('rclogs');
    $ratchet_day = FALSE;
    $editors = array();
    $editcount = array();
    $rc_delay = 0;
    //60*2;
    $rctimestamp = 0;
    $needupdate = false;
    if (empty($formatter->refresh) and $DBInfo->checkUpdated($rc->mtime($rckey), $rc_delay) and $val = $rc->fetch($rckey)) {
        $editors = $val['editors'];
        $editcount = $val['editcount'];
        $lastmod = $val['lastmod'];
        $rclastline = $val['lastline'];
        $rctimestamp = $val['timestamp'];
        $users = $val['users'];
    }
    $lastline = $lines[0];
    $tmp = explode("\t", $lastline, 6);
    $timestamp = $tmp[2];
    unset($tmp);
    $updatemod = array();
    $needupdate = $rctimestamp < $timestamp or $lastline != $rclastline;
    if ($needupdate) {
        foreach ($lines as $line) {
            $parts = explode("\t", $line, 6);
            if ($lastline == $rclastline) {
                break;
            }
            $page_key = $parts[0];
            $ed_time = $parts[2];
            $user = $parts[4];
            $addr = $parts[1];
            if ($user == 'Anonymous') {
                $user = '******' . $addr;
            } else {
                $user = $user . "\t" . $addr;
            }
            $day = gmdate('Ymd', $ed_time + $tz_offset);
            //if ($day != $ratchet_day) {
            //  $ratchet_day = $day;
            //}
            if ($last_entry_only and !empty($last_entry_check)) {
                if (!empty($lastmod[$page_key]) and $lastmod[$page_key] < $ed_time + $last_entry_check) {
                    $edit_day = gmdate('Ymd', $lastmod[$page_key] + $tz_offset);
                    $editors[$page_key][$edit_day][] = $user;
                    $editcount[$page_key][$edit_day]++;
                    if ($needupdate and empty($updatemod[$page_key])) {
                        $updatemod[$page_key] = $ed_time;
                    }
                    continue;
                }
            } else {
                if (!empty($editcount[$page_key][$day])) {
                    $editors[$page_key][$day][] = $user;
                    $editcount[$page_key][$day]++;
                    if ($needupdate and empty($updatemod[$page_key])) {
                        $updatemod[$page_key] = $ed_time;
                    }
                    continue;
                }
            }
            if (empty($editcount[$page_key])) {
                $editcount[$page_key] = array();
                $editors[$page_key] = array();
            }
            $editcount[$page_key][$day] = 1;
            $editors[$page_key][$day] = array();
            $editors[$page_key][$day][] = $user;
            $lastmod[$page_key] = $ed_time;
            if ($needupdate) {
                $updatemod[$page_key] = $ed_time;
            }
        }
    }
    if (!empty($lastmod)) {
        $lastmod = array_merge($lastmod, $updatemod);
    }
    // search query
    if (isset($query[0])) {
        $lines = preg_grep("/{$query}/i", $lines);
    }
    $out = "";
    $ratchet_day = FALSE;
    $br = "";
    $ii = 0;
    $rc_list = array();
    $list = array();
    foreach ($lines as $line) {
        $parts = explode("\t", $line);
        $page_key = $parts[0];
        $ed_time = $parts[2];
        $day = gmdate('Ymd', $ed_time + $tz_offset);
        // show last edit only
        if (!empty($last_entry_only) and !empty($logs[$page_key])) {
            continue;
        } else {
            if (!empty($logs[$page_key][$day])) {
                continue;
            }
        }
        $page_name = $DBInfo->keyToPagename($parts[0]);
        // show trashed pages only
        if ($trash and $DBInfo->hasPage($page_name)) {
            continue;
        }
        $addr = $parts[1];
        $user = $parts[4];
        $log = _stripslashes($parts[5]);
        $act = rtrim($parts[6]);
        //    if ($ed_time < $time_cutoff)
        //      break;
        $group = '';
        if ($formatter->group) {
            if (!preg_match("/^({$formatter->group})(.*)\$/", $page_name, $match)) {
                continue;
            }
            $title = $match[2];
        } else {
            if (!empty($formatter->use_group) and ($p = strpos($page_name, '~')) !== false) {
                $title = substr($page_name, $p + 1);
                $group = ' (' . substr($page_name, 0, $p) . ')';
            } else {
                $title = $page_name;
            }
        }
        if (!empty($changed_time_fmt)) {
            if (empty($timesago)) {
                $date = gmdate($changed_time_fmt, $ed_time + $tz_offset);
            } else {
                $date = _timesago($ed_time, 'Y-m-d', $tz_offset);
            }
        }
        $pageurl = _rawurlencode($page_name);
        // get title
        $title0 = get_title($title) . $group;
        $title0 = htmlspecialchars($title0);
        if ($list) {
            $attr = '';
        } else {
            $attr = " id='title-{$ii}'";
        }
        if (!empty($strimwidth) and strlen(get_title($title)) > $strimwidth and function_exists('mb_strimwidth')) {
            $title0 = mb_strimwidth($title0, 0, $strimwidth, '...', $DBInfo->charset);
        }
        $attr .= ' title="' . $title . '"';
        $title = $formatter->link_tag($pageurl, "", $title0, $target . $attr);
        // simple list format
        if ($rctype == 'list') {
            if (empty($logs[$page_key])) {
                $logs[$page_key] = array();
            }
            $logs[$page_key][$day] = 1;
            if (!$DBInfo->hasPage($page_name)) {
                $act = 'DELETE';
            }
            $list[$page_name] = array($title, $date, $act);
            continue;
        }
        $jsattr = '';
        if (!empty($use_js)) {
            $jsattr = ' onclick="update_bookmark(' . $ed_time . ');return false;"';
        }
        $bmark = '';
        if ($day != $ratchet_day) {
            $ratchet_day = $day;
            if (!empty($use_day)) {
                $tag = str_replace('-', '', $day);
                $perma = "<a name='{$tag}'></a><a class='perma' href='#{$tag}'>{$perma_icon}</a>";
                $out .= $cat0;
                $rcdate = gmdate($date_fmt, $ed_time + $tz_offset);
                $out .= sprintf("%s<span class='rc-date' style='font-size:large'>%s ", $br, $rcdate);
                if (empty($nobookmark)) {
                    $out .= "<span class='rc-bookmark' style='font-size:small'>[" . $formatter->link_tag($formatter->page->urlname, $bookmark_action . "&amp;time={$ed_time}" . $daysago, _("set bookmark"), $jsattr) . "]</span>\n";
                }
                $br = "<br />";
                $out .= '</span>' . $perma . '<br />' . $bra;
                $cat0 = $cat;
            } else {
                $bmark = $formatter->link_to($bookmark_action . "&amp;time={$ed_time}" . $daysago, _("Bookmark"), $jsattr . ' class="button-small"');
            }
        }
        //if (empty($use_day) and empty($nobookmark)) {
        if (empty($nobookmark)) {
            $date = $formatter->link_to($bookmark_action . "&amp;time={$ed_time}" . $daysago, $date, ' id="time-' . $ii . '" ' . $jsattr);
        }
        // print $ed_time."/".$bookmark."//";
        $diff = '';
        $updated = '';
        if ($act == 'UPLOAD') {
            $icon = $formatter->link_tag($pageurl, "?action=uploadedfiles", $formatter->icon['attach']);
        } else {
            if (!$DBInfo->hasPage($page_name)) {
                $icon = $formatter->link_tag($pageurl, "?action=info", $formatter->icon['del']);
                if (!empty($use_js)) {
                    $rc_list[] = $page_name;
                }
            } else {
                $icon = $formatter->link_tag($pageurl, "?action=diff", $formatter->icon['diff'], " id='icon-{$ii}'");
                if (empty($use_js) and $ed_time > $bookmark) {
                    $icon = $formatter->link_tag($pageurl, "?action=diff&amp;date={$bookmark}", $formatter->icon['diff']);
                    $updated = ' ' . $formatter->link_tag($pageurl, "?action=diff&amp;date={$bookmark}", $formatter->icon['updated'], 'class="updated"');
                    $add = 0;
                    $del = 0;
                    if ($checknew or $checkchange) {
                        $p = new WikiPage($page_name);
                        $v = $p->get_rev($bookmark);
                        if (empty($v)) {
                            $icon = $formatter->link_tag($pageurl, "?action=info", $formatter->icon['show']);
                            $updated = ' ' . $formatter->link_tag($pageurl, "?action=info", $formatter->icon['new'], 'class="new"');
                            $add += $p->lines();
                        }
                    }
                    if ($checkchange) {
                        if (empty($v)) {
                            // new
                            $infos = array();
                        } else {
                            $infos = $p->get_info('>' . $bookmark);
                        }
                        foreach ($infos as $inf) {
                            $tmp = explode(' ', trim($inf[1]));
                            if (isset($tmp[1])) {
                                $add += $tmp[0];
                                $del += $tmp[1];
                            }
                        }
                    }
                    if (!empty($add)) {
                        $diff .= '<span class="diff-added"><span>+' . $add . '</span></span>';
                    }
                    if (!empty($del)) {
                        $diff .= '<span class="diff-removed"><span>' . $del . '</span></span>';
                    }
                } else {
                    if (!empty($use_js)) {
                        $diff = '<span id="diff-' . $ii . '"></span>';
                        $rc_list[] = $page_name;
                    }
                }
            }
        }
        if (!empty($use_hits)) {
            $hits = $DBInfo->counter->pageCounter($page_name);
        }
        if (!empty($showhost)) {
            $last_editor = $user;
            if ($last_editor_only) {
                // show last editor only
                $editor = $editors[$page_key][$day];
                if (is_array($editor)) {
                    $editor = $editor[count($editor) - 1];
                }
            } else {
                // all show all authors
                // count edit number
                // make range list
                if ($use_editrange) {
                    // MoinMoin like edit range
                    $editor_list = array();
                    if ($editors[$page_key][$day]) {
                        foreach ($editors[$page_key][$day] as $idx => $name) {
                            if (empty($editor_list[$name])) {
                                $editor_list[$name] = array();
                            }
                            $editor_list[$name][] = $idx + 1;
                        }
                    }
                    $editor_counts = array();
                    foreach ($editor_list as $name => $edits) {
                        $range = ',';
                        if (isset($edits[1])) {
                            $edits[] = 999999;
                            // MoinMoin method
                            for ($i = 0, $sz = count($edits) - 1; $i < $sz; $i++) {
                                if (substr($range, -1) == ',') {
                                    $range .= $edits[$i];
                                    if ($edits[$i] + 1 == $edits[$i + 1]) {
                                        $range .= '-';
                                    } else {
                                        $range .= ',';
                                    }
                                } else {
                                    if ($edits[$i] + 1 != $edits[$i + 1]) {
                                        $range .= $edits[$i] . ',';
                                    }
                                }
                            }
                            $range = trim($range, ',-');
                            $editor_counts[$name] = $range;
                        } else {
                            $editor_counts[$name] = $edits[0];
                        }
                    }
                } else {
                    $editor_counts = array_count_values($editors[$page_key][$day]);
                }
                $editor = array_keys($editor_counts);
            }
            $all_user = array();
            foreach ((array) $editor as $user) {
                if (!$last_editor_only and isset($editor[1]) and isset($editor_counts[$user])) {
                    $count = " <span class='range'>[" . $editor_counts[$user] . "]</span>";
                } else {
                    $count = '';
                }
                if (!empty($showhost) && substr($user, 0, 9) == 'Anonymous') {
                    $ouser = $user;
                    if (isset($users[$ouser])) {
                        $user = $users[$ouser];
                    } else {
                        $checkaddr = null;
                        $addr = null;
                        $tmp = $user;
                        if (strpos($user, "\t") !== false) {
                            list($tmp, $addr) = explode("\t", $user);
                        }
                        $checkaddr = substr($tmp, 10);
                        // Anonymous-127.0.0.1 or Anonymous-email@foo.bar
                        $user = $addr ? $addr : $checkaddr;
                        if (!is_numeric($checkaddr[0]) and preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $user)) {
                            $user = $checkaddr;
                            if (!empty($DBInfo->hide_emails)) {
                                $user = substr(md5($user), 0, 8);
                            } else {
                                $user = email_guard($user);
                            }
                        } else {
                            if (!empty($DBInfo->mask_hostname)) {
                                $user = _mask_hostname($user);
                            }
                        }
                        if (!empty($use_avatar)) {
                            $crypted = md5($addr . $rckey);
                            $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink);
                            $user = '******' . $mylnk . '" style="width:16px;height:16px;vertical-align:middle" alt="avatar" />' . _('Anonymous');
                        }
                        $users[$ouser] = $user;
                    }
                } else {
                    list($user, $addr) = explode("\t", $user);
                    $ouser = $user;
                    if (isset($users[$ouser])) {
                        $user = $users[$ouser];
                    } else {
                        if (!empty($DBInfo->use_nick)) {
                            $uid = $user;
                            if (($p = strpos($uid, ' ')) !== false) {
                                $uid = substr($uid, 0, $p);
                            }
                            $u = $DBInfo->udb->getUser($uid);
                            if (!empty($u->info)) {
                                if (!empty($DBInfo->interwiki['User'])) {
                                    $user = $formatter->link_repl('[wiki:User:'******' ' . $u->info['nick'] . ']');
                                } else {
                                    if (!empty($u->info['home'])) {
                                        $user = $formatter->link_repl('[' . $u->info['home'] . ' ' . $u->info['nick'] . ']');
                                    } else {
                                        if (!empty($u->info['nick'])) {
                                            $user = $formatter->link_repl('[wiki:' . $uid . ' ' . $u->info['nick'] . ']');
                                        }
                                    }
                                }
                            }
                            $users[$ouser] = $user;
                        } else {
                            if (strpos($user, ' ') !== false) {
                                $user = $formatter->link_repl($user);
                                $users[$ouser] = $user;
                            } else {
                                if (empty($DBInfo->no_wikihomepage) and $DBInfo->hasPage($user)) {
                                    $user = $formatter->link_tag(_rawurlencode($user), "", $user);
                                    $users[$ouser] = $user;
                                } else {
                                    if (substr($user, 0, 9) == 'Anonymous') {
                                        $addr = substr($user, 10);
                                        $user = _('Anonymous');
                                    }
                                    if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $user)) {
                                        if (!empty($DBInfo->hide_emails)) {
                                            $user = substr(md5($user), 0, 8);
                                        } else {
                                            $user = email_guard($user);
                                        }
                                    }
                                    if (!empty($use_avatar)) {
                                        $crypted = crypt($addr, $addr);
                                        $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink);
                                        $user = '******' . $mylnk . '" style="width:16px;height:16px;vertical-align:middle" alt="avatar" />' . $user;
                                    }
                                    $users[$ouser] = $user;
                                }
                            }
                        }
                    }
                }
                $all_user[] = $user . $count;
            }
            if (isset($editor[1])) {
                $user = '******' . implode("</span> <span class='editor'>", $all_user) . "</span></span>\n";
            } else {
                $user = $all_user[0];
            }
        } else {
            $user = '******';
        }
        $count = "";
        $extra = "";
        if ($editcount[$page_key][$day] > 1) {
            $count = '<span id="change-' . $ii . '">' . sprintf(_("%s changes"), " <span class='num'>" . $editcount[$page_key][$day] . "</span>") . '</span>';
        } else {
            $count = '<span id="change-' . $ii . '"></span>';
        }
        if (!empty($comment) && !empty($log)) {
            $extra = "&nbsp; &nbsp; &nbsp; <small name='word-break'>{$log}</small>";
        }
        $alt = $ii % 2 == 0 ? ' class="alt"' : '';
        if ($extra and isset($template_extra)) {
            if ($rctype == 'board' and !empty($use_js)) {
                $style = ' style="display:none"';
            } else {
                $style = '';
            }
            if (!empty($use_js)) {
                $title = '<button onclick="toggle_log(this);return false;"><span>+</span></button>' . $title;
            }
            $out .= eval('return ' . $template_extra . ';');
        } else {
            $out .= eval('return ' . $template . ';');
        }
        if (empty($logs[$page_key])) {
            $logs[$page_key] = array();
        }
        $logs[$page_key][$day] = 1;
        ++$ii;
    }
    if ($needupdate) {
        $rc->update($rckey, array('editors' => $editors, 'editcount' => $editcount, 'lastmod' => $lastmod, 'lastline' => $lastline, 'timestamp' => $timestamp, 'users' => $users));
    }
    $js = '';
    if (!empty($rc_list)) {
        require_once 'lib/JSON.php';
        $json = new Services_JSON();
        $icon_new = $formatter->icon['new'];
        $icon_updated = $formatter->icon['updated'];
        $icon_show = $formatter->icon['show'];
        $icon_diff = $formatter->icon['diff'];
        $js = "<script type='text/javascript'>\n/*<![CDATA[*/\nvar rclist =";
        $ext = array();
        if (!empty($checknew)) {
            $ext[] = 'new=1';
        }
        if (!empty($checkchange)) {
            $ext[] = 'change=1';
        }
        $arg = implode('&', $ext);
        $url = qualifiedURL($formatter->link_url('RecentChanges'));
        // FIXME
        $postdata = "action=recentchanges/ajax" . ($arg ? '&' . $arg : '');
        $js .= $json->encode($rc_list) . ";\n";
        if ($use_diffwidth) {
            $js .= "var use_diffwidth = true;\n";
        } else {
            $js .= "var use_diffwidth = false;\n";
        }
        $js .= <<<EOF
function diff_width(size) {
    if (size < 0)
        size = -size;
    if (size < 5)
      return '';
    else if (size < 10)
      return 'display:inline-block;width:25px';
    else
      return 'display:inline-block;width:' + ~~(25 + 2*Math.sqrt(size)) + 'px';
}

function update_bookmark(time) {
    var url = "{$url}";
    if (rclist.length) {
      var timetag;
      if (typeof time == 'undefined') timetag = '';
      else timetag = '&time=' + time;

      var data = "{$postdata}";
      data += timetag + '&value=' + encodeURIComponent(json_encode(rclist));
      var txt = HTTPPost(url, data);
      var ret;
      if (txt == null) return;

      var icon_new = "{$icon_new}";
      var icon_updated = "{$icon_updated}";
      var icon_show = "{$icon_show}";
      var icon_diff = "{$icon_diff}";

      ret = window["eval"]("(" + txt + ")");
      var bookmark = ret['__-_-bookmark-_-__'];
      var jj = 0;
      for (var ii = 0; ii < rclist.length; ii++) {
        // update time
        var time = document.getElementById('time-' + ii);
        var tstr = time.firstChild.innerText;
        var d0 = Date.parse(tstr); // test
        if (isNaN(d0)) {
          // recalc time string
          var timestamp = time.href.match(/time=(\\d+)/);
          tstr = timesago(timestamp[1], "{$date_fmt}", {$tz_offset});
          if (tstr != null)
            time.firstChild.innerText = tstr;
        }

        var item = document.getElementById('title-' + ii);
        var title = item.getAttribute('title');
        if (rclist[jj] != title) {
          var re = new RegExp("^.*" + url_prefix + '/');
          title = decodeURIComponent(item.href.replace(re, ''));
        }

        if (ret[title] && ret[title]['state'] == 'deleted') { jj++; continue; }

        if (rclist[jj] == title && ret[title]) {
          var icon = document.getElementById('icon-' + ii);
          var state = document.createElement('SPAN');
          if (ret[title]['state'] == 'new') {
            state.innerHTML = icon_new;
            state.setAttribute('class', 'new');
            icon.href = icon.href.replace(/action=(diff|info)((?:&|&amp;)date=\\d+)?/, 'action=info');
            icon.innerHTML = icon_show;
          } else {
            state.innerHTML = icon_updated;
            state.setAttribute('class', 'updated');
            icon.href = icon.href.replace(/action=(diff|info)((?:&|&amp;)date=\\d+)?/, 'action=diff&date=' + bookmark);
            icon.innerHTML = icon_diff;
          }

          // remove previous icon
          if (item.firstChild.nextSibling)
            item.removeChild(item.firstChild.nextSibling);
          item.appendChild(state); // add updated / new icon

          var change = document.getElementById('change-' + ii);
          if (!change) continue;
          var diff = document.getElementById('diff-' + ii);
          var nodiff = !diff;

          // remove previous diff info
          if (change.lastChild && change.lastChild.tagName == 'SPAN')
            change.removeChild(change.lastChild);
          else if (diff && diff.lastChild)
            diff.removeChild(diff.lastChild);

          // add diff info
          var diff0 = document.createElement('SPAN');
          if (ret[title]['add']) {
            var add = document.createElement('SPAN');
            var add2 = document.createElement('SPAN');
            add.setAttribute('class', 'diff-added');
            var txt = document.createTextNode('+' + ret[title]['add']);
            add2.appendChild(txt);
            add.appendChild(add2);
            diff0.appendChild(add);
            if (use_diffwidth)
            add.style.cssText = diff_width(ret[title]['add']);
          }
          if (ret[title]['del']) {
            var del = document.createElement('SPAN');
            var del2 = document.createElement('SPAN');
            del.setAttribute('class', 'diff-removed');
            var txt = document.createTextNode(ret[title]['del']);
            del2.appendChild(txt);
            del.appendChild(del2);
            diff0.appendChild(del);
            if (use_diffwidth)
            del.style.cssText = diff_width(ret[title]['del']);
          }
          if (nodiff)
            change.appendChild(diff0);
          else
            diff.appendChild(diff0);
          jj++;
        } else {
          if (item.firstChild.nextSibling)
            item.removeChild(item.firstChild.nextSibling);

          var change = document.getElementById('change-' + ii);
          if (!change) continue;
          var diff = document.getElementById('diff-' + ii);

          // remove diff info
          if (change.lastChild && change.lastChild.tagName == 'SPAN')
            change.removeChild(change.lastChild);
          else if (diff && diff.lastChild)
            diff.removeChild(diff.lastChild);

          // recover diff icon and link
          var icon = document.getElementById('icon-' + ii);
          if (icon && icon.firstChild) {
            var alt = icon.firstChild.getAttribute('alt');
            if (alt != 'D' && alt != '@') {
              icon.innerHTML = icon_diff;
            }
            // recover link
            icon.href = icon.href.replace(/action=(diff|info)(&date=\\d+)?/, 'action=diff');
          }
        }
      }
    }
}
update_bookmark();
/*]]>*/
</script>
EOF;
    } else {
        if (!empty($list)) {
            $out = '';
            foreach ($list as $k => $v) {
                $out .= $v[1] . ' ' . $v[0] . '<br />';
            }
            if (!empty($options['call'])) {
                return $out;
            }
        }
    }
    if (in_array($rctype, array('list', 'simple')) and $use_js) {
        static $rc_id = 1;
        $rcid = ' id="rc' . $rc_id . '"';
        $extra = '';
        if (!empty($opts['items'])) {
            $extra .= '&item=' . $opts['items'];
        }
        $url = $formatter->link_url('RecentChanges', "?action=recentchanges/ajax&type={$rctype}" . $extra);
        $js = <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
  var url = "{$url}";
  var txt = HTTPGet(url);
  var rc = document.getElementById("rc{$rc_id}");
  rc.innerHTML = txt;
/*]]>*/
</script>
JS;
        $rc_id++;
    } else {
        if ($use_js and $rctype == 'board') {
            $js .= <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
function toggle_log(el)
{
  var item = el.parentNode.parentNode; // container
  var log = item.nextSibling;
  if (log.tagName == undefined)
    log = log.nextSibling; // for IE6

  if (log.style.display == "none") {
    el.className = "close";
    log.style.display = "";
  } else {
    el.className = "open";
    log.style.display = "none";
  }
}
/*]]>*/
</script>
JS;
        }
    }
    return $btnlist . '<div class="recentChanges"' . $rcid . '>' . $rctitle . $template_bra . $out . $template_cat . $cat0 . '</div>' . $js;
}