Example #1
0
 function endElement($parser, $tagName)
 {
     if ($tagName == "ITEM") {
         //if ($this->status) print "[$this->status] ";
         $title = trim($this->title);
         if (!empty($this->title_width) && function_exists('mb_strimwidth')) {
             $title = mb_strimwidth($title, 0, $this->title_width, '...', $this->charset);
         }
         $title = sprintf("<a href='%s' title='%s' target='_content'>%s</a>", trim($this->link), _html_escape($this->title), _html_escape($title));
         #printf("<p>%s</p>",
         #  _html_escape(trim($this->description)));
         if ($this->date) {
             $date = trim($this->date);
             $date[10] = " ";
             # 2003-07-11T12:08:33+09:00
             # http://www.w3.org/TR/NOTE-datetime
             $zone = str_replace(":", "", substr($date, 19));
             $time = strtotime(substr($date, 0, 19) . $zone);
             $date = date($this->date_fmt, $time);
         }
         echo '<li><span data-timestamp="' . $time . '" class="date">', $date, '</span> ', $title, '</li>', "\n";
         $this->title = "";
         $this->description = "";
         $this->link = "";
         $this->date = "";
         $this->status = "";
         $this->insideitem = false;
     }
 }
Example #2
0
function macro_Revert($formatter, $value, $options = array())
{
    $options['info_actions'] = array('recall' => 'view', 'revert' => 'revert');
    $options['title'] = '<h3>' . sprintf(_("Old Revisions of the %s"), _html_escape($formatter->page->name)) . '</h3>';
    $out = $formatter->macro_repl('Info', '', $options);
    return $out;
}
Example #3
0
function macro_PageHits($formatter = "", $value)
{
    global $DBInfo;
    if (!$DBInfo->use_counter) {
        return "[[PageHits is not activated. set \$use_counter=1; in the config.php]]";
    }
    $pages = $DBInfo->getPageLists();
    sort($pages);
    $hits = array();
    foreach ($pages as $page) {
        $hits[$page] = $DBInfo->counter->pageCounter($page);
    }
    if (!empty($value) and ($value == 'reverse' or $value[0] == 'r')) {
        asort($hits);
    } else {
        arsort($hits);
    }
    $out = '';
    while (list($name, $hit) = each($hits)) {
        if (!$hit) {
            $hit = 0;
        }
        $name = $formatter->link_tag(_rawurlencode($name), "", _html_escape($name));
        $out .= "<li>{$name} . . . . [{$hit}]</li>\n";
    }
    return "<ol>\n" . $out . "</ol>\n";
}
Example #4
0
function macro_PageLinks($formatter, $options = "")
{
    global $DBInfo;
    $pages = $DBInfo->getPageLists();
    $pagelinks = $formatter->pagelinks;
    // save
    $save = $formatter->sister_on;
    $formatter->sister_on = 0;
    $out = "<ul>\n";
    $cache = new Cache_text("pagelinks");
    foreach ($pages as $page) {
        $lnks = $cache->fetch($page);
        if ($lnks !== false) {
            $out .= "<li>" . $formatter->link_tag($page, '', _html_escape($page)) . ": ";
            $links = implode(' ', $lnks);
            $links = preg_replace_callback("/(" . $formatter->wordrule . ")/", array(&$formatter, 'link_repl'), $links);
            $out .= $links . "</li>\n";
        }
    }
    $out .= "</ul>\n";
    $formatter->pagelinks = $pagelinks;
    // restore
    $formatter->sister_on = $save;
    return $out;
}
Example #5
0
function macro_InputForm($formatter, $value, $options = array())
{
    $out = '';
    $type = 'select';
    $name = 'val[]';
    if (empty($value)) {
        return "</form>\n";
    }
    if (strpos($value, ':') !== false) {
        list($type, $value) = explode(':', $value, 2);
    }
    if (!in_array($type, array('form', 'select', 'input', 'submit', 'checkbox', 'radio'))) {
        $type = 'select';
    }
    $myname = $name;
    $val = _html_escale($value);
    switch ($type) {
        case 'form':
            #list($method,$action,$dum)=explode(':',$value);
            $tmp = explode(':', $value);
            $method = $tmp[0];
            $action = $tmp[1];
            $method = in_array(strtolower($method), array('post', 'get')) ? $method : 'get';
            $url = $formatter->link_url($formatter->page->urlname);
            $out = "<form method='{$method}' action='{$url}'>\n" . "<input type='hidden' name='action' value='{$action}' />\n";
            break;
        case 'submit':
            $out .= "<input type='{$type}' name='{$name}' value=\"{$val}\" />\n";
            break;
        case 'input':
            list($myname, $size, $value) = explode(':', $value, 3);
            $size = $size ? "size='{$size}'" : '';
            $out .= "<input type='{$type}' {$size}name='{$myname}' value=\"{$val}\" />\n";
            break;
        case 'select':
        default:
            list($myname, $value) = explode(':', $value);
            $list = explode(',', $value);
            $out .= '<option>----</option>' . "\n";
            foreach ($list as $l) {
                $l = _html_escape(trim($l));
                if (($p = strrpos($l, ' ')) !== false and substr($l, $p + 1) == 1) {
                    $check = ' selected="selected"';
                    $l = substr($l, 0, -1);
                } else {
                    $check = '';
                }
                $out .= "<option value=\"" . $l . "\"{$check}>" . _($l) . "</option>\n";
            }
            $out = "<select name='{$myname}'>" . $out . "</select>\n";
            break;
    }
    return $out;
}
Example #6
0
function macro_PageHits($formatter, $value = '', $params = array())
{
    global $DBInfo, $Config;
    if (empty($Config['use_counter'])) {
        return "[[PageHits is not activated. set \$use_counter=1; in the config.php]]";
    }
    $perpage = !empty($Config['counter_per_page']) ? intval($Config['counter_per_page']) : 200;
    if (!empty($params['p'])) {
        $p = intval($params['p']);
    } else {
        $p = 0;
    }
    if ($p < 0) {
        $p = 0;
    }
    $hits = $DBInfo->counter->getPageHits($perpage, $p);
    if (!empty($value) and ($value == 'reverse' or $value[0] == 'r')) {
        asort($hits);
    } else {
        arsort($hits);
    }
    $out = '';
    while (list($name, $hit) = each($hits)) {
        if (!$hit) {
            $hit = 0;
        }
        $name = $formatter->link_tag(_rawurlencode($name), "", _html_escape($name));
        $out .= "<li>{$name} . . . . [{$hit}]</li>\n";
    }
    $start = $perpage * $p;
    if ($start > 0) {
        $start = ' start="' . $start . '"';
    } else {
        $start = '';
    }
    $out = "<ol{$start}>\n" . $out . "</ol>\n";
    $prev = '';
    $next = '';
    if ($p > 0) {
        $prev = $formatter->link_tag($formatter->page->urlname, '?action=pagehits&amp;p=' . ($p - 1), _("&#171; Prev"));
    }
    $p++;
    if (count($hits) >= 0) {
        $next = $formatter->link_tag($formatter->page->urlname, '?action=pagehits&amp;p=' . $p, _("Next &#187;"));
    }
    return $out . $prev . ' ' . $next;
}
Example #7
0
function do_post_fixbacklinks($formatter, $options = array())
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    }
    $options['name'] = trim($options['name']);
    $new = $options['name'];
    if (!empty($DBInfo->use_namespace) and $new[0] == '~' and ($p = strpos($new, '/')) !== false) {
        // Namespace renaming ~foo/bar -> foo~bar
        $dummy = substr($new, 1, $p - 1);
        $dummy2 = substr($new, $p + 1);
        $options['name'] = $dummy . '~' . $dummy2;
    }
    if (isset($options['name'][0]) and $options['name']) {
        if ($DBInfo->hasPage($options['name'])) {
            $formatter->send_header('', $options);
            $new_encodedname = _rawurlencode($options['name']);
            $fixed = 0;
            $msg = '';
            $title = sprintf(_("backlinks of \"%s\" page are fixed !"), $options['page']);
            $comment = sprintf(_("Fixed \"%s\" to \"%s\""), $options['page'], $options['name']);
            if ($options['pagenames'] and is_array($options['pagenames'])) {
                $regex = preg_quote($options['page']);
                //$options['minor'] = 1; # disable log
                foreach ($options['pagenames'] as $page) {
                    $p = new WikiPage($page);
                    if (!$p->exists()) {
                        continue;
                    }
                    $f = new Formatter($p);
                    $body = $p->_get_raw_body();
                    $nbody = preg_replace("/{$regex}/m", $options['name'], $body);
                    // FIXME
                    if ($nbody !== false && $body != $nbody) {
                        $f->page->write($nbody);
                        if (!$options['show_only']) {
                            $DBInfo->savePage($f->page, $comment, $options);
                        }
                        $msg .= sprintf(_("'%s' is changed"), $f->link_tag(_rawurlencode($page), "?action=highlight&amp;value=" . $new_encodedname, _html_escape($page))) . "<br />";
                        $fixed++;
                    }
                }
            }
            if ($fixed == 0) {
                $title = _("No pages are fixed!");
            }
            $formatter->send_title($title, '', $options);
            if ($fixed > 0) {
                print $msg;
                print sprintf(_("'%s' links are successfully fixed as '%s'."), _html_escape($options['page']), $formatter->link_tag($new_encodedname, "?action=highlight&amp;value=" . $new_encodedname, _html_escape($options['name'])));
            }
            $formatter->send_footer('', $options);
            return;
        } else {
            $title = sprintf(_("Fail to fix backlinks of \"%s\" !"), $options['page']);
            $options['msg'] = sprintf(_("New pagename \"%s\" is not exists!"), $options['name']);
            $formatter->send_header('', $options);
            $formatter->send_title($title, '', $options);
            $formatter->send_footer('', $options);
            return;
        }
    }
    $title = sprintf(_("Fix backlinks of \"%s\" ?"), $options['page']);
    $formatter->send_header('', $options);
    $formatter->send_title($title, '', $options);
    $obtn = _("Old name:");
    $nbtn = _("New name:");
    $pgname = _html_escape($options['page']);
    print "<form method='post'>\n        <table border='0'>\n        <tr><td align='right'>{$obtn} </td><td><b>{$pgname}</b></td></tr>\n        <tr><td align='right'>{$nbtn} </td><td><input name='name' /></td></tr>\n";
    if (!empty($options['value']) and $options['value'] == 'check_backlinks') {
        $button = _("Fix backlinks");
        print "<tr><td colspan='2'>\n";
        print check_backlinks($formatter, $options);
        print "</td></tr>\n";
    } else {
        $button = _("Check backlinks");
    }
    if ($DBInfo->security->is_protected("fixbacklinks", $options)) {
        print "<tr><td align='right'>" . _("Password") . ": </td><td><input type='password' name='passwd' /> " . _("Only WikiMaster can fix backlinks of this page") . "</td></tr>\n";
    }
    if (!empty($options['value']) and $options['value'] == 'check_backlinks') {
        print "<tr><td colspan='2'><input type='checkbox' name='show_only' checked='checked' />" . _("show only") . "</td></tr>\n";
    }
    print "<tr><td></td><td><input type='submit' name='button_fixbacklinks' value='{$button}' />";
    print "<input type='hidden' name='value' value='check_backlinks' />";
    print "</td></tr>\n";
    print "\n        </table>\n        <input type='hidden' name='action' value='fixbacklinks' />\n        </form>";
    $formatter->send_footer('', $options);
}
Example #8
0
function macro_UploadedFiles($formatter, $value = "", $options = "")
{
    global $DBInfo;
    $use_preview = $DBInfo->use_preview_uploads ? $DBInfo->use_preview_uploads : 0;
    $preview_width = 64;
    #$use_preview=0;
    $use_admin = 1;
    $use_fileinfo = 1;
    $js_tag = 0;
    $js_script = '';
    $uploader = '';
    // get user id
    if (empty($formatter->preview) && empty($options)) {
        $options = array();
        $options['id'] = $DBInfo->user->id;
    }
    if (isset($DBInfo->members) and !in_array($options['id'], $DBInfo->members)) {
        $use_admin = 0;
    }
    $iconset = 'gnome';
    $icon_dir = $DBInfo->imgs_dir . '/plugin/UploadedFiles/' . $iconset;
    $args = !empty($DBInfo->uploadedfiles_options) ? explode(',', $DBInfo->uploadedfiles_options) : array();
    $nargs = explode(',', $value);
    if (!empty($nargs)) {
        $args = array_merge($args, $nargs);
    }
    $value = '';
    $default_column = 8;
    $col = (!empty($options['col']) and $options['col'] > 0) ? (int) $options['col'] : $default_column;
    if (!empty($formatter->preview)) {
        $js_tag = 1;
        $use_preview = 1;
        $uploader = 'UploadForm';
        $use_admin = 0;
        $use_fileinfo = 0;
        $col = 10000;
    } else {
        if (!empty($options['preview'])) {
            $use_preview = 1;
            $use_admin = 0;
            $use_fileinfo = 0;
        }
    }
    if (!empty($options['tag'])) {
        # javascript tag mode
        $js_tag = 1;
        $use_preview = 1;
        $use_admin = 0;
        $use_fileinfo = 0;
        $col = 10000;
    }
    if ($use_fileinfo) {
        $col = 1;
    }
    $href_attr = '';
    $attr = '';
    if (!empty($DBInfo->use_lightbox) and !$js_tag) {
        $href_attr = ' rel="lightbox[upload]" ';
    }
    $nodir = 0;
    foreach ($args as $arg) {
        $arg = trim($arg);
        if (($p = strpos($arg, '=')) !== false) {
            $k = substr($arg, 0, $p);
            $v = substr($arg, $p + 1);
            if ($k == 'preview') {
                $use_preview = $v;
            } else {
                if ($k == 'nodir') {
                    $nodir = $v;
                } else {
                    if ($k == 'tag') {
                        $js_tag = 1;
                        $use_preview = 1;
                    }
                }
            }
        } else {
            $value = $arg;
        }
    }
    if (!isset($options['nodir'])) {
        $options['nodir'] = $nodir;
    }
    if (!empty($options['page'])) {
        $value = $options['page'];
    }
    // avoid to set the pagename of the "page,name" as "name"
    if ($js_tag) {
        $form = 'editform';
        $js_script = <<<EOS
      <script language="javascript" type="text/javascript">
/*<![CDATA[*/
// based on wikibits.js in the MediaWiki
// small fix to use opener in the dokuwiki.

function insertTags(tagOpen,tagClose,myText,replaced)
{
  var is_ie = document.selection && document.all;
  if (document.{$form}) {
    var txtarea = document.{$form}.savetext;
  } else {

    // some alternate form? take the first one we can find
    var areas = document.getElementsByTagName('textarea');
    if (areas.length > 0) {
        var txtarea = areas[0];
    } else if (opener) {
        // WikiWyg support
        if (opener.document.{$form} && opener.document.{$form}.savetext) {
            txtarea = opener.document.{$form}.savetext;
        } else {
            txtarea = opener.document.getElementsByTagName('textarea')[0];
        }

        var my=opener.document.getElementById('editor_area');
        while (my == null || my.style.display == 'none') { // wikiwyg hack
            txtarea = opener.document.getElementById('wikiwyg_wikitext_textarea');

            // get iframe and check visibility.
            var myframe = opener.document.getElementsByTagName('iframe')[0];
            if (myframe.style.display == 'none' || myframe.parentNode.style.display == 'none') break;

            var postdata = 'action=markup/ajax&value=' + encodeURIComponent(tagOpen + myText + tagClose);
            var myhtml='';
            myhtml= HTTPPost(self.location, postdata);

            var mnew = myhtml.replace(/^<div>/i,''); // strip div tag
            mnew = mnew.replace(/<\\/div>\\s*\$/i,''); // strip div tag

            if (is_ie) {
                var range = myframe.contentWindow.document.selection.createRange();
                if (range.boundingTop == 2 && range.boundingLeft == 2)
                    return;
                range.pasteHTML(html);
                range.collapse(false);
                range.select();
            } else {
                myframe.contentWindow.document.execCommand('inserthtml', false, mnew + ' ');
            }

            return;
        }
    } else {
        return; // XXX
    }
  }

  if(is_ie) {
    var theSelection = document.selection.createRange().text;
    txtarea.focus();
    if(theSelection.charAt(theSelection.length - 1) == " "){
      // exclude ending space char, if any
      theSelection = theSelection.substring(0, theSelection.length - 1);
      document.selection.createRange().text = theSelection + tagOpen + myText + tagClose + " ";
    } else {
      document.selection.createRange().text = theSelection + tagOpen + myText + tagClose + " ";
    }
  }
  // Mozilla
  else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
\t\t//var replaced = false;
\t\tvar startPos = txtarea.selectionStart;
\t\tvar endPos = txtarea.selectionEnd;
\t\tif (!replaced && endPos-startPos)
\t\t\treplaced = true;
\t\tvar scrollTop = txtarea.scrollTop;

\t\tif (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any
\t\t\tsubst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
\t\t} else {
\t\t\tsubst = tagOpen + myText + tagClose;
\t\t}
\t\ttxtarea.value = txtarea.value.substring(0, startPos) + subst +
\t\t\ttxtarea.value.substring(endPos, txtarea.value.length);
\t\ttxtarea.focus();
\t\t//set new selection
\t\tif (replaced) {
\t\t\tvar cPos = startPos+(tagOpen.length+myText.length+tagClose.length);
\t\t\ttxtarea.selectionStart = cPos;
\t\t\ttxtarea.selectionEnd = cPos;
\t\t} else {
\t\t\ttxtarea.selectionStart = startPos+tagOpen.length;   
\t\t\ttxtarea.selectionEnd = startPos+tagOpen.length+myText.length;
\t\t}\t
\t\ttxtarea.scrollTop = scrollTop;
  } else { // All others
    txtarea.value += tagOpen + myText + tagClose + " ";
    txtarea.focus();
  }
}
/*]]>*/
</script>
EOS;
    }
    if (!empty($DBInfo->download_action)) {
        $mydownload = $DBInfo->download_action;
    } else {
        $mydownload = 'download';
    }
    $checkbox = 'checkbox';
    $needle = "//";
    if (!empty($options['download']) || !empty($DBInfo->force_download)) {
        $force_download = 1;
        if (!empty($options['download'])) {
            $mydownload = $options['download'];
        }
    }
    if (!empty($options['needle'])) {
        $needle = '@' . $options['needle'] . '@i';
    }
    if (!empty($options['checkbox'])) {
        $checkbox = $options['checkbox'];
    }
    if (!in_array('UploadFile', $formatter->actions)) {
        $formatter->actions[] = 'UploadFile';
    }
    if ($value and $value != 'UploadFile') {
        $key = $DBInfo->pageToKeyname($value);
        //if ($force_download or $key != $value)
        $down_prefix = $formatter->link_url(_rawurlencode($value), "?action={$mydownload}&amp;value=");
        $dir = $DBInfo->upload_dir . "/{$key}";
    } else {
        $value = $formatter->page->urlname;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        //if ($force_download or $key != $formatter->page->name)
        $down_prefix = $formatter->link_url($formatter->page->urlname, "?action={$mydownload}&amp;value=");
        $dir = $DBInfo->upload_dir . "/{$key}";
    }
    // support hashed upload_dir
    if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $dir = $DBInfo->upload_dir . '/' . get_hashed_prefix($key) . $key;
    }
    if (!empty($force_download) or $key != $value) {
        $prefix = $down_prefix;
    }
    if (!empty($formatter->preview) and $formatter->page->name == $value) {
        $opener = '';
    } else {
        $opener = $value . ':';
    }
    if ($value != 'UploadFile' and file_exists($dir)) {
        $handle = opendir($dir);
    } else {
        $key = '';
        $value = 'UploadFile';
        if (!$force_download) {
            $prefix .= $prefix ? '/' : '';
        }
        $dir = $DBInfo->upload_dir;
        $handle = opendir($dir);
        $opener = '/';
    }
    $upfiles = array();
    $dirs = array();
    $per = !empty($DBInfo->uploadedfiles_per_page) ? $DBInfo->uploadedfiles_per_page : 100;
    // set nodir option to show only files
    if (!empty($options['needle']) && !isset($options['nodir'])) {
        $options['nodir'] = true;
    } else {
        if (!isset($options['nodir'])) {
            $options['nodir'] = false;
        }
    }
    // count files/dirs
    $count_files = 0;
    $count_dirs = 0;
    $uf = new Cache_text('settings');
    if (($info = $uf->fetch('uploadedfiles')) !== false) {
        $count_files = $info['files'];
        $count_dirs = $info['dirs'];
    } else {
        while (($file = readdir($handle)) !== false) {
            if ($file[0] == '.') {
                continue;
            }
            if (is_dir($dir . "/" . $file)) {
                $count_dirs++;
            } else {
                $count_files++;
            }
        }
        rewinddir($handle);
        // TTL = 1 day
        $uf->update('uploadedfiles', array('files' => $count_files, 'dirs' => $count_dirs), 60 * 60 * 24);
    }
    // XXX
    $plink = '';
    if (!empty($options['p'])) {
        $p = $options['p'] ? (int) $options['p'] : 1;
    } else {
        $p = 1;
    }
    $pfrom = ($p - 1) * $per;
    $pto = $pfrom + $per;
    $count = 0;
    while (($file = readdir($handle)) !== false) {
        if ($file[0] == '.') {
            continue;
        }
        if ($count >= $pfrom) {
            if (is_dir($dir . "/" . $file)) {
                if ($options['nodir']) {
                    continue;
                }
                if ($value == 'UploadFile') {
                    $dirs[] = $DBInfo->keyToPagename($file);
                }
            } else {
                if (preg_match($needle, $file) and $count >= $pfrom) {
                    if ($count < $pto) {
                        $upfiles[] = _p_filename($file);
                    }
                }
            }
        }
        $count++;
        if ($count >= $pto) {
            $plink = 1;
            break;
        }
    }
    closedir($handle);
    if (!$upfiles and !$dirs) {
        return "<h3>" . _("No files found") . "</h3>";
    }
    sort($upfiles);
    sort($dirs);
    $link = $formatter->link_url($formatter->page->urlname);
    $out = "<form method='post' action='{$link}'>";
    $out .= "<p><input type='hidden' name='action' value='DeleteFile' />\n";
    if ($key) {
        $out .= "<input type='hidden' name='value' value=\"{$value}\" />\n";
    }
    $out .= "</p><table style='border:0px' cellpadding='2' class='info'>\n";
    // set colspan to show file informations
    $c = 1;
    if ($use_admin) {
        $c = 2;
    }
    if ($c) {
        $colspan = ' colspan="' . $c . '"';
    }
    if ($use_fileinfo) {
        $mname = _("File name");
        $msize = _("Size");
        $mdate = _("Date");
        $out .= "<tr><th{$colspan}>{$mname}</th><th>{$msize}</th><th>{$mdate}</th></tr>\n";
        $c += 2;
    }
    // set colspan again
    if ($c > 1) {
        $colspan = ' colspan="' . $c . '"';
    }
    $idx = 1;
    if ($js_tag) {
        #$attr=' target="_blank"';
        $extra = '&amp;popup=1&amp;tag=1';
    } else {
        $attr = '';
        $extra = '';
    }
    // support hashed upload_dir
    if (!empty($DBInfo->use_hashed_upload_dir)) {
        $ndirs = array();
        foreach ($dirs as $d0) {
            if (strlen($d0) != 1) {
                $ndirs[] = $d0;
                continue;
            }
            $handle = opendir($DBInfo->upload_dir . '/' . $d0);
            if (!is_resource($handle)) {
                continue;
            }
            $pre = $DBInfo->upload_dir . '/' . $d0;
            while (($d = readdir($handle)) !== false) {
                if (!is_dir($pre . '/' . $d)) {
                    $ndirs[] = $d0;
                    break;
                }
                if ($d[0] == $d0[0]) {
                    $hd = opendir($pre . '/' . $d);
                    if (!is_resource($hd)) {
                        continue;
                    }
                    $pre1 = $pre . '/' . $d;
                    while (($d1 = readdir($hd)) !== false) {
                        if ($d1[0] == '.') {
                            continue;
                        }
                        if (is_dir($pre1 . '/' . $d1)) {
                            $ndirs[] = $d1;
                        }
                    }
                    closedir($hd);
                }
            }
            closedir($handle);
        }
        $dirs = $ndirs;
        sort($dirs);
    }
    // count dirs
    $didx = 0;
    if (count($dirs)) {
        $out .= "<tr>";
        $didx++;
    }
    foreach ($dirs as $file) {
        $link = $formatter->link_url($file, "?action=uploadedfiles{$extra}", $file, $attr);
        $key = $DBInfo->pageToKeyname($file);
        // support hashed upload_dir
        $pre = '';
        if (!empty($DBInfo->use_hashed_upload_dir)) {
            $pre = get_hashed_prefix($key);
            if (!is_dir($dir . '/' . $pre . $key)) {
                $pre = '';
            }
        }
        $dirname = $dir . '/' . $pre . $key;
        $date = date("Y-m-d", filemtime($dirname));
        $file = _html_escape($file);
        if ($use_admin) {
            $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>";
        }
        $out .= "<td class='wiki'><a href='{$link}'>{$file}/</a></td>";
        if ($use_fileinfo) {
            $out .= "<td align='right' class='wiki'>&nbsp;</td><td class='wiki'>{$date}</td>";
        }
        if ($didx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        $idx++;
        $didx++;
    }
    if (isset($value[0]) and $value != 'UploadFile') {
        if ($js_tag) {
            #$attr=' target="_blank"';
            $extra = '&amp;popup=1&amp;tag=1';
        }
        if (!empty($options['needle'])) {
            $extra .= '&amp;q=' . $options['needle'];
        }
        $link = $formatter->link_tag('UploadFile', "?action=uploadedfiles&amp;value=top{$extra}", "<img src='" . $icon_dir . "/32/up.png' style='border:0' class='upper' alt='..' />", $attr);
        $out .= "<tr>";
        if ($use_admin) {
            $out .= "<td class='wiki'>&nbsp;</td>";
        }
        $out .= "<td class='wiki'>{$link}</td>";
        if ($use_fileinfo) {
            $date = date("Y-m-d", filemtime($dir . "/.."));
            $out .= "<td align='right' class='wiki'>&nbsp;</td><td class='wiki'>{$date}</td>";
        }
        if ($didx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        $didx++;
    }
    if (!empty($options['needle'])) {
        $extra .= '&amp;q=' . $options['needle'];
    }
    if (isset($options['nodir'])) {
        $extra .= '&amp;nodir=' . $options['nodir'];
    }
    if ($plink) {
        $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}&amp;p=" . ($p + 1), _("Next page &raquo;"), $attr);
    } else {
        if ($p > 1) {
            $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}", _("&laquo; First page"), $attr);
        }
    }
    if (empty($prefix)) {
        $prefix = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir) . '/';
    }
    $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
    $down_mode = strpos($prefix, ';value=') !== false;
    $mywidth = $preview_width;
    if (empty($didx)) {
        // no dirs found.
        $out .= '<tr>';
    }
    $iidx = $didx;
    // file index
    foreach ($upfiles as $file) {
        $_l_file = _l_filename($file);
        // force download with some extensions. XXX
        if ($down_mode or preg_match('/\\.(pl|cgi|py|php.?)$/', $file)) {
            $link = str_replace(";value=", ";value=" . rawurlencode($file), $down_prefix);
        } else {
            $link = $prefix . rawurlencode($file);
        }
        // XXX
        $previewlink = $link;
        $size = filesize($dir . '/' . $_l_file);
        if (!empty($use_preview)) {
            preg_match("/\\.(.{1,4})\$/", $file, $m);
            $ext = isset($m[1]) ? strtolower($m[1]) : '';
            if ($use_preview > 1 and $ext and stristr('gif,png,jpeg,jpg', $ext)) {
                list($w, $h) = getimagesize($dir . '/' . $file);
                if ($w <= $preview_width) {
                    $mywidth = $w;
                } else {
                    $mywidth = $preview_width;
                }
                if (file_exists($dir . "/thumbnails/" . $_l_file)) {
                    if ($down_mode) {
                        $previewlink = str_replace('value=', 'value=thumbnails/', $previewlink);
                    } else {
                        $previewlink = $prefix . 'thumbnails/' . rawurlencode($file);
                    }
                }
            }
        }
        if (!empty($use_fileinfo)) {
            $i = 0;
            for (; $i < 4; $i++) {
                if ($size <= 1024) {
                    #$size= round($size,2).' '.$unit[$i];
                    break;
                }
                $size = $size / 1024;
            }
            $size = round($size, 2) . ' ' . $unit[$i];
        }
        $date = date('Y-m-d', filemtime($dir . '/' . $_l_file));
        $fname = $file;
        if ($use_preview or $js_tag) {
            $tag_open = 'attachment:';
            $tag_close = '';
            if ($opener != $value) {
                $tag_open .= $opener;
            }
            $alt = "alt='{$tag_open}{$file}{$tag_close}' title='{$file}'";
            if ($ext and stristr('gif,png,jpeg,jpg', $ext)) {
                $fname = "<img src='{$previewlink}' class='icon' width='{$mywidth}' {$alt} />";
                $attr .= $href_attr;
            } else {
                if (preg_match('/^(wmv|avi|mpeg|mpg|swf|wav|mp3|ogg|midi|mid|mov)$/', $ext)) {
                    $tag_open = '[[Media(';
                    $tag_close = ')]]';
                    $alt = "{$tag_open}{$file}{$tag_close}";
                } else {
                    if (!preg_match('/^(bmp|c|h|java|py|bak|diff|doc|css|php|xml|html|mod|' . 'rpm|deb|pdf|ppt|xls|tgz|gz|bz2|zip)$/', $ext)) {
                        $ext = 'unknown';
                    }
                }
                $fname = "<img src='{$icon_dir}/{$ext}.png' class='icon' {$alt} /><span>{$file}</span>";
            }
            if ($js_tag) {
                //if (strpos($file,' '))
                $tag = "insertTags('{$tag_open}','{$tag_close}','{$file}',true)";
                $link = "javascript:{$tag}";
            }
        }
        $file = _html_escape($file);
        if ($use_admin) {
            $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>";
        }
        $out .= "<td class='wiki'><a href=\"{$link}\"{$attr}>{$fname}</a></td>";
        if ($use_fileinfo) {
            $out .= "<td align='right' class='wiki'>{$size}</td><td class='wiki'>{$date}</td>";
        }
        if ($iidx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        if ($use_admin && $use_fileinfo) {
            $out .= "<td>&nbsp;</td><td{$colspan}>";
            if ($use_admin) {
                $out .= $dir . '/';
            }
            $out .= "{$file}</td>\n";
            $out .= "</tr>\n<tr>";
        }
        $idx++;
        $iidx++;
    }
    $kidx = $iidx - 1;
    $k = 0;
    // setup colspan to fill up <tr> with colspaned <td>
    while ($kidx % $col != 0) {
        $k += $c;
        $kidx++;
    }
    if ($k > 0) {
        // fill tr
        $out .= '<td colspan="' . $k . '">&nbsp;</td>';
    }
    if (substr($out, -4) == '<tr>') {
        $out = substr($out, 0, -4);
    } else {
        $out .= "</tr>\n";
    }
    $idx--;
    $msg = sprintf(_("%d files"), $idx);
    if (count($dirs)) {
        $msg .= ' / ' . sprintf(_("Total %d files"), $count_files);
        $msg .= ' / ' . sprintf(_("%d dirs"), $count_dirs);
    }
    // colspan for multi column case.
    if ($col > 1) {
        $colspan = ' colspan="' . $col * $c . '"';
    }
    $out .= "<tr>";
    if ($use_admin && $c > 1) {
        $out .= "<td>&nbsp;</td>";
    }
    // fill checkbox column
    $out .= "<th {$colspan}>{$msg}</th></tr>\n";
    if ($plink) {
        $out .= "<tr><th {$colspan}>{$plink}</th></tr>\n";
    }
    $out .= "</table>\n";
    if ($use_admin) {
        if ($DBInfo->security->is_protected("deletefile", $options)) {
            $out .= '<p>' . _("Password") . ": <input type='password' name='passwd' size='10' /></p>\n";
        }
        $out .= "<p><input type='submit' value='" . _("Delete selected files") . "' /></p>";
    }
    $out .= "</form>\n";
    if (!$value and !in_array('UploadFile', $formatter->actions)) {
        $formatter->actions[] = 'UploadFile';
    }
    if ($uploader and !in_array('UploadedFiles', $formatter->actions)) {
        $out .= $formatter->macro_repl($uploader);
    }
    if ($use_preview) {
        $class = ' class="fileList preview"';
        return $js_script . "<div{$class}>" . $out . "</div>\n";
    }
    return $js_script . $out;
}
Example #9
0
function macro_GoTo($formatter = "", $value = "")
{
    $url = $formatter->link_url($formatter->page->urlname);
    $value = _html_escape($value);
    $msg = _("Go");
    return "<form method='get' action='{$url}'>\n    <input type='hidden' name='action' value='goto' />\n    <input name='value' size='30' value=\"{$value}\" />\n    <span class='button'><input type='submit' class='button' value='{$msg}' /></span>\n    </form>";
}
Example #10
0
function macro_BBS($formatter, $value, $options = array())
{
    global $DBInfo;
    # set defaults
    $ncount = 20;
    # default
    $bname = $formatter->page->name;
    $nid = '';
    # check options
    $args = preg_split('/\\s*,\\s*/', $value);
    foreach ($args as $arg) {
        $arg = trim($arg);
        if ($arg == '') {
            continue;
        }
        if (($p = strpos($arg, '=')) !== false) {
            $k = substr($arg, 0, $p);
            $v = substr($arg, $p + 1);
            if ($k == 'no') {
                $nid = $v;
            } else {
                if ($k == 'mode') {
                    $options['mode'] = $v;
                }
            }
        } else {
            if ($arg == 'mode') {
            } else {
                if ($arg == (int) $arg . "") {
                    $ncount = $arg;
                } else {
                    $bname = $arg;
                }
            }
        }
    }
    $bpage = _rawurlencode($bname);
    $nid = $nid ? $nid : $_GET['no'];
    $nids = array();
    if ($nid) {
        $nids = preg_split('/\\s+/', $nid);
        rsort($nids);
    }
    $options['p'] = $_GET['p'] > 0 ? $_GET['p'] : 1;
    $options['c'] = $ncount != 20 ? $ncount : '';
    $options['p'] = intval($options['p']);
    # is it exists ?
    if (!$DBInfo->hasPage($bname)) {
        return _("This bbs does not exists yet. Please save this page first");
    }
    # load a config file
    $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);
    $conf['data_dir'] = $DBInfo->data_dir;
    $conf['dba_type'] = $DBInfo->dba_type;
    if (!$DBInfo->use_bbs) {
        return '[[BBS]]';
    }
    #if ($DBInfo->use_bbs == 1);
    #if ($DBInfo->use_bbs == 2);
    $MyBBS = new BBS_text($bname, $conf);
    // XXX
    if ($options['new'] and $MyBBS) {
        return $MyBBS;
    }
    if (!$MyBBS) {
        return '[[BBS]]';
    }
    $msg = '';
    $btn = array();
    # read messages
    #
    $formatter->baserule[] = "/^((-=)+-?\$)/";
    $formatter->baserule[] = "/ comment #(\\d+)\\b/";
    $formatter->baserule[] = "/\\[reply (\\d+)\\]/";
    $formatter->baserepl[] = "<hr />\n";
    $formatter->baserepl[] = " comment [#c\\1 #\\1]";
    $formatter->baserepl[] = "<script type='text/javascript'><!--\n" . " addReplyLink(\\1); //--></script>";
    $msg = '';
    $narticle = sizeof($nids);
    $js = '';
    if ($nid and $narticle == 1 and $options['mode'] == 'simple') {
        $nid = $nids[0];
        if (!$nid or !$MyBBS->hasPage($nid)) {
            return '[[BBS(error)]]';
        }
        include_once 'lib/metadata.php';
        $body = $MyBBS->getPage($nid);
        list($metas, $body) = _get_metadata($body);
        $img = '';
        if ($MyBBS->use_attach) {
            $cache = new Cache_text('attachments');
            $attachs = $cache->fetch($MyBBS->bbsname . ':' . $nid);
            if (preg_match('/^attachment:([^\\?]+)(\\?.*)?$/', $attachs[0], $m)) {
                $img = $formatter->macro_repl('Attachment', $m[1] . '?thumbwidth=100');
            }
            $subject = $formatter->link_tag($bpage, "?no={$nid}", $metas['Subject']);
        }
        $out = "<div class='simpleView'><table>\n" . "<tr><td class='img'>" . $img . "</td><td class='subject'>" . $subject . '</td></tr>' . "<tr><td colspan='2'></td>\n</tr></table></div>";
        return $out;
    }
    foreach ($nids as $nid) {
        if (!$nid or !$MyBBS->hasPage($nid)) {
            continue;
        }
        $fields = array('Name', 'Subject', 'Date', 'Email', 'HomePage', 'IP', 'Keywords');
        include_once 'lib/metadata.php';
        #Name: wkpark
        #Subject: Oh well
        #Date: 2006-04-29 42:04:39
        #Email: wkpark@gmail.com
        #HomePage:
        #IP: 2xx.xxx.xxx.x
        $body = $MyBBS->getPage($nid);
        if ($body != null) {
            $options['nosisters'] = 1;
            $MyBBS->counter->incCounter($nid, $options);
            list($metas, $body) = _get_metadata($body);
            $boundary = strtoupper(md5("COMMENT"));
            # XXX
            $copy = $body;
            list($comment, $copy) = explode("----" . $boundary . "\n", $copy, 2);
            while (!empty($comment)) {
                list($comment, $copy) = explode("----" . $boundary . "\n", $copy, 2);
                if (preg_match('/^Comment-Id:\\s*(\\d+)/i', $comment, $m)) {
                    list($myhead, $my) = explode("\n\n", $comment, 2);
                    $hidden .= '<pre style="display:none;" id="comment_text_' . $m[1] . '">' . _html_escape($my) . '</pre>';
                }
            }
            ob_start();
            # add some basic rule/repl for bts
            $rule = "/-{4}(?:" . $boundary . ")?\nComment-Id:\\s*(\\d+)\n" . "From:\\s*([^\n]+)\nDate:\\s*([^\n]+)\n\n/im";
            $repl = "----\n'''Comment-Id:''' [#c\\1][#c\\1 #\\1] by \\2 on [[DateTime(\\3)]] [reply \\1]\n\n";
            $body = preg_replace($rule, $repl, $body);
            $formatter->quote_style = 'bbs-comment';
            $options['usemeta'] = 1;
            #
            $q_save = $formatter->self_query;
            $query = '?no=' . $nid . '&amp;p=' . $options['p'];
            $formatter->self_query = $query;
            $save = $formatter->preview;
            $formatter->preview = 1;
            $save_markup = $formatter->format;
            ob_start();
            if ($conf['default_markup']) {
                $formatter->pi['#format'] = $conf['default_markup'];
            }
            $formatter->send_page($body, $options);
            $body = ob_get_contents();
            ob_end_clean();
            $formatter->pi['#format'] = $save_markup;
            $formatter->self_query = $q_save;
            $msg .= "<div class='bbsArticle'>" . '<div class="head"><h2>' . _("No") . ' ' . $nid . ': ' . $metas['Subject'] . '</h2></div>' . '<div class="body">' . '<div class="extra"> @ ' . $metas['Date'] . ' (' . _mask_hostname($metas['IP'], 3) . ')</div>' . '<div class="user"><h3>' . $metas['Name'] . '</h3></div>' . '<div class="article">' . $body . "</div>\n</div>\n" . '<div class="foot"><div></div></div>' . "</div>\n";
            $snid = $nid;
            $btn['edit'] = $formatter->link_tag($bpage, "?action=bbs&amp;mode=edit&amp;no=" . $nid, '<span>' . _("Edit") . '</span>', 'class="button"');
            $btn['delete'] = $formatter->link_tag($bpage, "?action=bbs&amp;mode=delete&amp;no=" . $nid, '<span>' . _("Delete") . '</span>', 'class="button"');
            if ($narticle == 1 and $conf['use_comment']) {
                $opts['action'] = 'bbs';
                $opts['no'] = $nid;
                $opts['p'] = $options['p'];
                $opts['mode'] = 'comment';
                $opts['nopreview'] = 1;
                $p = new WikiPage($bname . ':' . $opts['no'], $options);
                $opts['datestamp'] = $p->mtime();
                $comment = $formatter->macro_repl('Comment', 'usemeta', $opts);
                unset($opts['no']);
                # XXX
            }
            $msg .= '<div class="bbsComment">' . $comment . '</div><div class="bbsArticleBtn">' . implode(" ", $btn) . '</div>';
            unset($btn['delete']);
            unset($btn['edit']);
            $title = str_replace('"', '\\"', $metas['Subject']);
            $js .= <<<JS
<script type="text/javascript">
/*<![CDATA[*/
document.title+=" [" + {$snid} + "] - " + "{$title}";
/*]]>*/
</script>
JS;
        }
    }
    if (!empty($msg) and !$_GET['p']) {
        return $msg;
    }
    if (1) {
        # XXX
        $nochk = _("Please check article numbers.");
        $js .= <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
  function send_list(obj,mode) {
    var tmp="";
    var i, chk=false;

    form=obj.parentNode.parentNode;

    for(i=0;i< form.length;i++) {
       if(form[i].type!="checkbox") continue;
       if(form[i].checked) {
          tmp+=form[i].value+" ";
          chk=true;
       }
    }
    if(chk==true) {
       form.no.value = tmp.substr(0,tmp.length-1);
       if (mode!=undefined) {
         form.elements.action.value = 'bbs';
         form.elements.mode.value = mode;
       } else {
         form.removeChild(form.elements.mode);
         form.removeChild(form.elements.action);
       }
       form.submit();
       return false;
    }
    alert ("{$nochk}");
    return false;
  }
/*]]>*/
</script>

JS;
    }
    # get list
    $options['perpage'] = $ncount;
    $list = $MyBBS->getList($ncount, $options);
    # get total number of articles
    $tot = $MyBBS->getCount();
    $pages = intval($tot / $ncount);
    if ($tot % $ncount) {
        $pages++;
    }
    if ($options['mode'] == 'rss') {
        $rss = '<' . '?xml version="1.0" encoding="utf-8"?>' . "\n" . '<rss version="2.0">' . "\n";
        $rss .= "<channel>\n<title>" . $DBInfo->sitename . ": </title>\n";
        $rss .= "<link>" . qualifiedUrl($formatter->link_url($bpage)) . "</link>\n";
        $rss .= "<description></description>\n";
        $rss .= "<pubDate>" . gmdate('D, j M Y H:i:s', time()) . " +0000</pubDate>\n";
        foreach ($list as $l) {
            $item = "<item>\n";
            $item .= "<title><![CDATA[" . $l[7] . "]]></title>\n";
            $item .= "<link>" . qualifiedUrl($formatter->link_url($bpage, "?no={$l['0']}")) . "</link>\n";
            $item .= "<author><![CDATA[" . $l[3] . "]]></author>\n";
            $item .= "<description><![CDATA[" . $l[3] . "]]></description>\n";
            $item .= "<pubDate>" . gmdate('D, j M Y H:i:s', $l[2]) . " +0000</pubDate>\n</item>\n";
            $rss .= $item;
        }
        $rss .= "</channel>\n</rss>\n";
        return $rss;
    } else {
        if ($options['mode'] == 'simple') {
            $simple = "<div class='bbsSimple'><table class='bbsSimple'>\n";
            foreach ($list as $l) {
                $date = date("Y-m-d", $l[2]);
                $my = $l[7];
                $title = '';
                if (function_exists('mb_strimwidth') and strlen($l[7]) > 60) {
                    $title = 'title="' . $l[7] . '"';
                    $my = mb_strimwidth($l[7], 0, 40, '...', $DBInfo->charset);
                }
                $simple .= "<tr><td class='date'>[" . $date . "]</td><td>" . $formatter->link_tag($bpage, "?no={$l['0']}" . $extra, $my, $title) . '</td></tr>';
            }
            $simple .= "<tr><td colspan='2' class='more'>" . $formatter->link_tag($bpage, "", _("More") . '&#187;') . "</td>\n</tr>\n";
            $simple .= "</table>";
            return $simple;
        }
    }
    if ($pages > 1) {
        $pnut = _get_pagelist($formatter, $pages, '?' . $extra . ($extra ? '&amp;p=' : 'p='), $options['p'], $ncount);
    } else {
        $pnut = "<div class='clear'></div>";
    }
    $extra = $options['p'] ? '&amp;p=' . $options['p'] : '';
    #$head=array(_("no"),'C',_("Title"),_("Name"),_("Date"),_("Hit"));
    #$out.="<col width='3%' class='num' /><col width='1%' class='check' /><col width='63%' class='title' /><col width='14%' /><col width='13%' /><col width='7%' class='hit' />\n";
    #$out.='<thead><tr><th>'.implode("</th><th>",$head)."</th></tr><thead>\n";
    #$out.="<tbody>\n";
    $item = array();
    foreach ($list as $l) {
        $nid =& $l[0];
        $ip =& $l[1];
        $date = date("Y-m-d", $l[2]);
        $user = $l[3];
        $subject = $formatter->link_tag($bpage, "?no={$nid}" . $extra, $l[7]);
        $hit = $MyBBS->counter->pageCounter($nid);
        $chk = '<input type="checkbox" value="' . $nid . '">';
        #$item=array(in_array($nid,$nids) ? '<strong>&raquo;</strong>':$nid,$chk,$subject,$user,$date,$hit);
        $item[] = array('num' => in_array($nid, $nids) ? '<strong>&raquo;</strong>' : $nid, 'check' => $chk, 'subject' => $subject, 'name' => $user, 'date' => $date, 'hit' => $hit);
        ##$tmp='<tr><td>'.implode("</td><td>",$item)."</td></tr>\n";
        #$tmp="<tr><td class='no'>$item[0]</td><td class='check'>$item[1]</td>".
        #    "<td class='title'>$item[2]</td><td class='name'>$item[3]</td>".
        #    "<td class='date'>$item[4]</td><td class='hit'>$item[5]</td>".
        #    "</tr>\n";
        #$out.=$tmp;
    }
    $formatter->_vars['item'] =& $item;
    $out .= $formatter->include_theme('plugin/BBS/default', 'list', array());
    #$out.= $formatter->include_theme('plugin/BBS/default_tpl','list',array());
    #$out.= $formatter->processor_repl('tpl_','',array('path'=>'theme/plugin/BBS/blue_tpl/list.tpl'));
    #$out.="</tbody>\n";
    $btn['new'] = $formatter->link_tag($bpage, "?action=bbs&amp;mode=edit", '<span>' . _("New") . '</span>', 'class="button"');
    unset($btn['edit']);
    $bn['view'] = $formatter->link_tag($bpage, "", '<span>' . _("Read") . '</span>', 'onclick="return send_list(this)" onfocus="blur()" class="button"');
    $bn['delete'] = $formatter->link_tag($bpage, "", '<span>' . _("Delete") . '</span>', 'onclick="return send_list(this,\'delete\')" onfocus="blur()" class="button"');
    $del = "<div class='bbsAdminBtn'>" . implode(" ", $bn) . "</div>\n";
    $btns = "<div class='bbsBtn'>" . implode(" ", $btn) . "</div>\n";
    $lnk = $formatter->link_url($bpage, '?action=bbs');
    $form0 = "<form method='get' action='{$lnk}'>\n";
    $form1 = '<input type="hidden" name="no" />';
    if ($options['p']) {
        $form1 .= '<input type="hidden" name="p" value="' . $options['p'] . "\" />\n";
    }
    $form1 .= '<input type="hidden" name="mode" />' . '<input type="hidden" name="action" />';
    $form1 .= "</form>\n";
    $pnut = "<div class='pnut'>{$pnut}</div>";
    $info = '<div class="bbsRSS">' . sprintf(_("Total %s articles."), '<strong>' . $tot . '</strong>') . ' ' . $formatter->link_tag($bpage, '?action=bbs&amp;mode=rss', $formatter->icon['rss']) . '</div>';
    return $info . $pnut . $msg . $js . $form0 . $out . $del . $form1 . $pnut . $btns;
}
Example #11
0
function macro_FullSearch($formatter, $value = "", &$opts)
{
    global $DBInfo;
    $needle = $value;
    if ($value === true) {
        $needle = $value = $formatter->page->name;
        $options['noexpr'] = 1;
    } else {
        # for MoinMoin compatibility with [[FullSearch("blah blah")]]
        #$needle = preg_replace("/^('|\")([^\\1]*)\\1/","\\2",$value);
        $needle = $value;
    }
    // for pagination
    $offset = '';
    if (!empty($opts['offset']) and is_numeric($opts['offset'])) {
        if ($opts['offset'] > 0) {
            $offset = $opts['offset'];
        }
    }
    $url = $formatter->link_url($formatter->page->urlname);
    $fneedle = _html_escape($needle);
    $tooshort = !empty($DBInfo->fullsearch_tooshort) ? $DBInfo->fullsearch_tooshort : 2;
    $m1 = _("Display context of search results");
    $m2 = _("Search BackLinks only");
    $m3 = _("Case-sensitive searching");
    $msg = _("Go");
    $bchecked = !empty($DBInfo->use_backlinks) ? 'checked="checked"' : '';
    $form = <<<EOF
<form method='get' action='{$url}'>
   <input type='hidden' name='action' value='fullsearch' />
   <input name='value' size='30' value="{$fneedle}" />
   <span class='button'><input type='submit' class='button' value='{$msg}' /></span><br />
   <input type='checkbox' name='backlinks' value='1' {$bchecked} />{$m2}<br />
   <input type='checkbox' name='context' value='20' />{$m1}<br />
   <input type='checkbox' name='case' value='1' />{$m3}<br />
   </form>
EOF;
    if (!isset($needle[0]) or !empty($opts['form'])) {
        # or blah blah
        $opts['msg'] = _("No search text");
        return $form;
    }
    $opts['form'] = $form;
    # XXX
    $excl = array();
    $incl = array();
    if (!empty($opts['noexpr'])) {
        $tmp = preg_split("/\\s+/", $needle);
        $needle = $value = join('|', $tmp);
        $raw_needle = implode(' ', $tmp);
        $needle = preg_quote($needle);
    } else {
        if (empty($opts['backlinks'])) {
            $terms = preg_split('/((?<!\\S)[-+]?"[^"]+?"(?!\\S)|\\S+)/s', $needle, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
            $common_words = array('the', 'that', 'where', 'what', 'who', 'how', 'too', 'are');
            $common = array();
            foreach ($terms as $term) {
                if (trim($term) == '') {
                    continue;
                }
                if (preg_match('/^([-+]?)("?)([^\\2]+?)\\2$/', $term, $match)) {
                    $word = str_replace(array('\\', '.', '*'), '', $match[3]);
                    $len = strlen($word);
                    if (!$match[1] and $match[2] != '"') {
                        if ($len < $tooshort or in_array($word, $common_words)) {
                            $common[] = $word;
                            continue;
                        }
                    }
                    if ($match[1] == '-') {
                        $excl[] = $word;
                    } else {
                        $incl[] = $word;
                    }
                }
            }
            $needle = implode('|', $incl);
            $needle = _preg_search_escape($needle);
            $raw_needle = implode(' ', $incl);
            $test = validate_needle($needle);
            if ($test === false) {
                // invalid regex
                $tmp = array_map('preg_quote', $incl);
                $needle = implode('|', $tmp);
            }
            $excl_needle = implode('|', $excl);
            $test = validate_needle($excl_needle);
            if ($test2 === false) {
                // invalid regex
                $tmp = array_map('preg_quote', $excl);
                $excl_needle = implode('|', $tmp);
            }
        } else {
            $cneedle = _preg_search_escape($needle);
            $test = validate_needle($cneedle);
            if ($test === false) {
                $needle = preg_quote($needle);
            } else {
                $needle = $cneedle;
            }
        }
    }
    $test3 = trim($needle);
    if (!isset($test3[0])) {
        $opts['msg'] = _("Empty expression");
        return $form;
    }
    # set arena and sid
    if (!empty($opts['backlinks'])) {
        $arena = 'backlinks';
    } else {
        if (!empty($opts['keywords'])) {
            $arena = 'keywords';
        } else {
            $arena = 'fullsearch';
        }
    }
    if ($arena == 'fullsearch') {
        $sid = md5($value . 'v' . $offset);
    } else {
        $sid = $value;
    }
    $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0;
    # retrieve cache
    $fc = new Cache_text($arena);
    if (!$formatter->refresh and $fc->exists($sid)) {
        $data = $fc->fetch($sid);
        if (!empty($opts['backlinks'])) {
            // backlinks are not needed to check it.
            $hits = $data;
            // also fetch redirects
            $r = new Cache_Text('redirects');
            $redirects = $r->fetch($sid);
        } else {
            if (is_array($data)) {
                # check cache mtime
                $cmt = $fc->mtime($sid);
                # check update or not
                $dmt = $DBInfo->mtime();
                if ($dmt > $cmt + $delay) {
                    # XXX crude method
                    $data = array();
                } else {
                    # XXX smart but incomplete method
                    if (isset($data['hits'])) {
                        $hits =& $data['hits'];
                    } else {
                        $hits =& $data;
                    }
                    foreach ($hits as $p => $c) {
                        $mp = $DBInfo->getPage($p);
                        $mt = $mp->mtime();
                        if ($mt > $cmt + $delay) {
                            $data = array();
                            break;
                        }
                    }
                }
                if (isset($data['searched'])) {
                    extract($data);
                } else {
                    if (!empty($data)) {
                        $hits = $data;
                    }
                }
            }
        }
    }
    $pattern = '/' . $needle . '/';
    if (!empty($excl_needle)) {
        $excl_pattern = '/' . $excl_needle . '/';
    }
    if (!empty($opts['case'])) {
        $pattern .= "i";
        $excl_pattern .= "i";
    }
    if (isset($hits)) {
        if (in_array($arena, array('backlinks', 'keywords'))) {
            $test = key($hits);
            if (is_int($test) and $hits[$test] != -1) {
                // fix compatible issue for keywords, backlinks
                $hits = array_flip($hits);
                foreach ($hits as $k => $v) {
                    $hits[$k] = -1;
                }
                reset($hits);
            }
            // check invert redirect index
            if (!empty($redirects)) {
                $redirects = array_flip($redirects);
                ksort($redirects);
                foreach ($redirects as $k => $v) {
                    $hits[$k] = -2;
                }
                reset($hits);
            }
        }
        //continue;
    } else {
        $hits = array();
        set_time_limit(0);
        if (!empty($opts['backlinks']) and empty($DBInfo->use_backlink_search)) {
            $hits = array();
        } else {
            if (!empty($opts['keywords']) and empty($DBInfo->use_keyword_search)) {
                $hits = array();
            } else {
                if (!empty($opts['backlinks'])) {
                    $pages = $DBInfo->getPageLists();
                    #$opts['context']=-1; # turn off context-matching
                    $cache = new Cache_text("pagelinks");
                    foreach ($pages as $page_name) {
                        $links = $cache->fetch($page_name);
                        if (is_array($links)) {
                            if (in_array($value, $links)) {
                                $hits[$page_name] = -1;
                            }
                            // ignore count if < 0
                        }
                    }
                } else {
                    if (!empty($opts['keywords'])) {
                        $pages = $DBInfo->getPageLists();
                        $opts['context'] = -1;
                        # turn off context-matching
                        $cache = new Cache_text("keyword");
                        foreach ($pages as $page_name) {
                            $links = $cache->fetch($page_name);
                            // XXX
                            if (is_array($links)) {
                                if (stristr(implode(' ', $links), $needle)) {
                                    $hits[$page_name] = -1;
                                }
                                // ignore count if < 0
                            }
                        }
                    } else {
                        $params = array();
                        $ret = array();
                        $params['ret'] =& $ret;
                        $params['offset'] = $offset;
                        $params['search'] = 1;
                        $params['incl'] = $incl;
                        $params['excl'] = $excl;
                        $pages = $DBInfo->getPageLists($params);
                        // set time_limit
                        $mt = explode(' ', microtime());
                        $timestamp = $mt[0] + $mt[1];
                        $j = 0;
                        $time_limit = isset($DBInfo->process_time_limit) ? $DBInfo->process_time_limit : 3;
                        // default 3-seconds
                        $j = 0;
                        while (list($_, $page_name) = each($pages)) {
                            // check time_limit
                            if ($time_limit and $j % 30 == 0) {
                                $mt = explode(' ', microtime());
                                $now = $mt[0] + $mt[1];
                                if ($now - $timestamp > $time_limit) {
                                    break;
                                }
                            }
                            $j++;
                            $p = new WikiPage($page_name);
                            if (!$p->exists()) {
                                continue;
                            }
                            $body = $p->_get_raw_body();
                            #$count = count(preg_split($pattern, $body))-1;
                            $count = preg_match_all($pattern, $body, $matches);
                            if ($count) {
                                foreach ($excl as $ex) {
                                    if (stristr($body, $ex)) {
                                        continue;
                                    }
                                }
                                foreach ($incl as $in) {
                                    if (!stristr($body, $in)) {
                                        continue;
                                    }
                                }
                                $hits[$page_name] = $count;
                            }
                        }
                        $searched = $j > 0 ? $j : 0;
                        $offset = !empty($offset) ? $offset + $j : $j;
                    }
                }
            }
        }
        #krsort($hits);
        #ksort($hits);
        $name = array_keys($hits);
        array_multisort($hits, SORT_DESC, $name, SORT_ASC);
        if (in_array($arena, array('backlinks', 'keywords'))) {
            $fc->update($sid, $name);
        } else {
            $fc->update($sid, array('hits' => $hits, 'offset' => $offset, 'searched' => $searched));
        }
    }
    $opts['hits'] = $hits;
    $opts['hit'] = count($hits);
    $opts['all'] = $DBInfo->getCounter();
    if ($opts['all'] > $searched) {
        $opts['next'] = $offset;
        $opts['searched'] = $searched;
    }
    if (!empty($opts['call'])) {
        return $hits;
    }
    $out = "<!-- RESULT LIST START -->";
    // for search plugin
    $out .= "<ul class='fullsearchResult'>";
    $idx = 1;
    $checkbox = '';
    while (list($page_name, $count) = each($hits)) {
        $pgname = _html_escape($page_name);
        if (!empty($opts['checkbox'])) {
            $checkbox = "<input type='checkbox' name='pagenames[]' value=\"{$pgname}\" />";
        }
        $out .= '<!-- RESULT ITEM START -->';
        // for search plugin
        $out .= '<li>' . $checkbox . $formatter->link_tag(_rawurlencode($page_name), '?action=highlight&amp;value=' . _urlencode($value), $pgname, 'tabindex="' . $idx . '"');
        if ($count > 0) {
            $out .= ' . . . . ' . sprintf($count == 1 ? _("%d match") : _("%d matches"), $count);
        } else {
            if ($count == -2) {
                $out .= " <span class='redirectIcon'><span>" . _("Redirect page") . "</span></span>\n";
            }
        }
        if (!empty($opts['context']) and $opts['context'] > 0) {
            # search matching contexts
            $p = new WikiPage($page_name);
            if ($p->exists()) {
                $body = $p->_get_raw_body();
                $out .= find_needle($body, $needle, $excl_needle, $opts['context']);
            }
        }
        $out .= "</li>\n";
        $out .= '<!-- RESULT ITEM END -->';
        // for search plugin
        $idx++;
        #if ($idx > 50) break;
    }
    $out .= "</ul>\n";
    $out .= "<!-- RESULT LIST END -->";
    // for search plugin
    return $out;
}
Example #12
0
function macro_RecentChanges($formatter, $value = '', $options = '')
{
    global $DBInfo, $Config;
    // get members to hide log
    $members = $DBInfo->members;
    $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['bookmark_action']) ? '?action=bookmark' : '?action=' . $options['bookmark_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;
        }
    }
    // RC cache delay
    // $rc_cache_delay <= $rc_delay
    $cache_delay = isset($DBInfo->rc_cache_delay) ? $DBInfo->rc_cache_delay : 0;
    $avatarlink = $formatter->link_url('', '?action=' . $avatar_type . '&amp;seed=');
    $ipicon = '<img src="' . $DBInfo->imgs_dir . '/misc/ip.png" />';
    $trash = 0;
    $rctype = '';
    $opts = array();
    $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 == "delay") {
                                    $cache_delay = intval($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;
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    ksort($opts);
    if (!empty($nobookmark)) {
        $use_js = 0;
    }
    // set as dynamic macro or not.
    if ($formatter->_macrocache and empty($options['call']) and empty($use_js) || $rctype != 'list') {
        return $formatter->macro_cache_repl('RecentChanges', $value);
    }
    if (empty($options['call'])) {
        $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 = '"<li>$date $title</li>\\n"';
                $template_bra = "<ul>\n";
                $template_cat = "</ul>\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
    // check member
    $ismember = $u->is_member;
    // use uniq avatar ?
    $uniq_avatar = 0;
    if (!empty($DBInfo->use_uniq_avatar)) {
        $uniq_avatar = $DBInfo->use_uniq_avatar;
    }
    if ($ismember) {
        $uniq_avatar = 'Y';
    }
    // change avatar after year :>
    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();
    }
    // 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['Config']);
    unset($locals['args']);
    unset($locals['arg']);
    unset($locals['u']);
    unset($locals['k']);
    unset($locals['v']);
    unset($locals['p']);
    unset($locals['value']);
    unset($locals['tz_offset']);
    unset($locals['members']);
    $rckey = md5(serialize($locals));
    $rckey2 = $rckey;
    $rclog = '<!-- rckey = ' . $rckey . ', cache delay = ' . $cache_delay . ' -->';
    if ($use_js) {
        unset($locals['use_js']);
        $rckey2 = md5(serialize($locals));
        // rckey without js option
    }
    unset($locals);
    // check RC cache
    $lc = new Cache_text('rccache');
    $mtime = $lc->mtime($rckey);
    if (empty($formatter->refresh)) {
        if (($val = $lc->fetch($rckey)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) {
            return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->';
        } else {
            if (!empty($options['ajax']) && $rctype == 'list' && $rckey != $rckey2) {
                // rctype == list with ajax option does not depend on "use_js" option.
                $mtime = $lc->mtime($rckey2);
                if (($val = $lc->fetch($rckey2)) !== false and $DBInfo->checkUpdated($mtime, $cache_delay)) {
                    return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->';
                }
            }
        }
        // need to update cache
        if ($val !== false and $lc->exists($rckey . '.lock')) {
            return $val . '<!-- cached at ' . date('Y-m-d H:i:s', $mtime) . ' -->';
        }
        $lc->update($rckey . '.lock', array('lock'), 5);
        // 5s lock
    } else {
        $lc->update($rckey . '.lock', array('lock'), 5);
        // 5s lock
    }
    // $uniq_avatar is numeric case: change avatar icon after 24 hours
    if (is_numeric($uniq_avatar)) {
        $uniq_avatar = $rckey . date('mdH', time());
    } else {
        if (is_string($uniq_avatar) and preg_match('/^[YmdHi]+$/', $uniq_avatar)) {
            // date format string case: change avatar icon after 'Ymd' etc period
            $uniq_avatar = $rckey . date($uniq_avatar, time());
        }
    }
    $time_current = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : 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 = isset($DBInfo->rc_delay) ? $DBInfo->rc_delay : $rc_cache_delay;
    $rctimestamp = 0;
    $needupdate = false;
    $use_val = false;
    while (($val = $rc->fetch($rckey)) !== false) {
        $use_val = true;
        if (!empty($formatter->refresh) or !$DBInfo->checkUpdated($rc->mtime($rckey), $rc_delay)) {
            $use_val = $rc->exists($rckey . '.lock');
        }
        if (!$use_val) {
            break;
        }
        $editors = $val['editors'];
        $editcount = $val['editcount'];
        $lastmod = $val['lastmod'];
        $rclastline = $val['lastline'];
        $rctimestamp = $val['timestamp'];
        $users = $val['users'];
        break;
    }
    // no cache available
    if (!$use_val) {
        $rc->update($rckey . '.lock', array('lock'), 5);
    }
    // 5s lock
    $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);
    }
    // setup hidelog rule
    $hiderule = null;
    if (!$ismember && !empty($Config['ruleset']['hiderule'])) {
        $rule = implode('|', $Config['ruleset']['hiderule']);
        if (preg_match('@' . $rule . '@', null) !== false) {
            $hiderule = '@' . $rule . '@';
        }
    }
    $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]);
        if (!empty($hiderule)) {
            if (preg_match($hiderule, $page_name)) {
                continue;
            }
        }
        // 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]);
        $via_proxy = false;
        if (($p = strpos($addr, ',')) !== false) {
            // user via Proxy
            $via_proxy = true;
            $real_ip = substr($addr, 0, $p);
            $log_proxy = '<span class="via-proxy">' . $real_ip . '</span>';
            $log = isset($log[0]) ? $log_proxy . ' ' . $log : $log_proxy;
            $dum = explode(',', $addr);
            $addr = array_pop($dum);
        }
        //    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 = _html_escape($title0);
        if ($rctype == '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="' . $title0 . '"';
        $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';
                $title = '<strike>' . $title . '</strike>';
            }
            $list[$page_name] = array($title, $date, $ed_time, $act);
            continue;
        }
        // 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)) {
            if ($last_editor_only) {
                // show last editor only
                $editor = $editors[$page_key][$day];
                if (is_array($editor)) {
                    $editor = $editor[0];
                }
            } 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
                        if (($p = strpos($checkaddr, ',')) !== false) {
                            $dum = explode(',', $checkaddr);
                            $checkaddr = array_pop($dum);
                            // last address is the REMOTE_ADDR
                        }
                        $user = $addr = $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 (isset($DBInfo->interwiki['Whois'])) {
                                $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$addr}' target='_blank'>{$ipicon}</a>";
                            } else {
                                $wip = "<a href='?action=whois&q=" . $addr . "' target='_blank'>{$ipicon}</a>";
                            }
                            if ($ismember) {
                                if (in_array($user, $members)) {
                                    $wip = '';
                                }
                                if (!empty($DBInfo->use_admin_user_url)) {
                                    $user = '******' . $DBInfo->use_admin_user_url . $user . '">' . $user . '</a>' . $wip;
                                } else {
                                    $user = $user . $wip;
                                }
                            } else {
                                if (!empty($DBInfo->mask_hostname)) {
                                    $user = _mask_hostname($addr, intval($DBInfo->mask_hostname));
                                }
                            }
                        }
                        $avatar = '';
                        if (!empty($use_avatar)) {
                            if (!empty($uniq_avatar)) {
                                $key = $addr . $uniq_avatar;
                            } else {
                                $key = $addr . $rckey;
                            }
                            $crypted = md5($key);
                            $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink);
                            $avatar = '<img src="' . $mylnk . '" class="avatar" alt="avatar" />';
                        }
                        $user = $avatar . $user;
                        $users[$ouser] = $user;
                    }
                } else {
                    list($user, $addr) = explode("\t", $user);
                    $ouser = $user;
                    if (!isset($users[$ouser])) {
                        if (isset($DBInfo->interwiki['Whois'])) {
                            $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$addr}' target='_blank'>{$ipicon}</a>";
                        } else {
                            $wip = "<a href='?action=whois&q=" . $addr . "' target='_blank'>{$ipicon}</a>";
                        }
                        $avatar = '';
                        if (!empty($use_avatar)) {
                            if (!empty($uniq_avatar)) {
                                $key = $addr . $uniq_avatar;
                            } else {
                                $key = $addr . $rckey;
                            }
                            if (!$ismember) {
                                $key .= $user;
                            }
                            // not a member: show different avatar for login user
                            $crypted = md5($key);
                            $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink);
                            if ($ouser != 'Anonymous') {
                                $mylnk .= '&amp;user='******'<img src="' . $mylnk . '" class="avatar" alt="avatar" />';
                        }
                    }
                    if (isset($users[$ouser])) {
                        $user = $users[$ouser];
                    } else {
                        if ($ismember) {
                            if (in_array($user, $members)) {
                                $wip = '';
                            }
                            if (!empty($DBInfo->use_admin_user_url)) {
                                $user = $avatar . '<a href="' . $DBInfo->use_admin_user_url . $user . '">' . $user . '</a>' . $wip;
                            } else {
                                $user = $avatar . $user . $wip;
                            }
                            $users[$ouser] = $user;
                        } 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'] . ']');
                                            }
                                        }
                                    }
                                }
                                $user = $avatar . $user;
                                $users[$ouser] = $user;
                            } else {
                                if (strpos($user, ' ') !== false) {
                                    $user = $avatar . $formatter->link_repl($user);
                                    $users[$ouser] = $user;
                                } else {
                                    if (empty($DBInfo->no_wikihomepage) and $DBInfo->hasPage($user)) {
                                        $user = $formatter->link_tag(_rawurlencode($user), "", $user);
                                        $user = $avatar . $user;
                                        $users[$ouser] = $user;
                                    } else {
                                        if (substr($user, 0, 9) == 'Anonymous') {
                                            $addr = substr($user, 10);
                                            $user = _('Anonymous');
                                        }
                                        $uid = $user;
                                        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);
                                            }
                                        }
                                        $user = $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] . "</span>\n";
            }
        } else {
            $user = '******';
        }
        $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);
        }
        $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
        //$url = preg_replace('/^https?:/', '', $url);
        $url = $formatter->link_url('RecentChanges');
        $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');
          }
        }
      }
    }
}
if(window.addEventListener)window.addEventListener("load",update_bookmark,false);
else if(window.attachEvent)window.attachEvent("onload",update_bookmark);
/*]]>*/
</script>
EOF;
    } else {
        if (!empty($list)) {
            $out = '';
            foreach ($list as $k => $v) {
                $out .= '<li><span data-timestamp="' . $v[2] . '" class="date">' . $v[1] . '</span> ' . $v[0] . '</li>' . "\n";
            }
            //if (!empty($options['ajax'])) {
            //  return '<ul>'.$out.'</ul>';
            //}
        }
    }
    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'];
        }
        if (!empty($my_date_fmt)) {
            $extra .= '&datefmt=' . $my_date_fmt;
        }
        $url = $formatter->link_url('RecentChanges', "?action=recentchanges/ajax&type={$rctype}" . $extra);
        $js = <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
(function() {
  var url = "{$url}";
  var txt = HTTPGet(url);
  var rc = document.getElementById("rc{$rc_id}");
  if (txt.substring(0,5) != 'false') {
    var m = null;
    if (m = txt.match(/<ul>[\\s\\S]*<\\/ul>/)) {
      rc.innerHTML = m[0];
    }
  }
})();
/*]]>*/
</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;
        }
    }
    $out = $btnlist . '<div class="recentChanges"' . $rcid . '>' . $rctitle . $template_bra . $out . $template_cat . $cat0 . '</div>' . $js . $rclog;
    $lc->update($rckey, $out);
    $lc->remove($rckey . '.lock');
    // unlock
    $rc->remove($rckey . '.lock');
    // unlock
    return $out;
}
Example #13
0
if (!isset($_GET['username'])) {
    /*
     * Change this to reflect site settings
     */
    echo "<rss version=\"2.0\">\n        <channel><title>{$xerte_toolkits_site->name}</title>\n        <link>{$xerte_toolkits_site->site_url}</link>\n        <description>" . RSS_DESCRIPTION . " " . $xerte_toolkits_site->name . "</description>\n        <language>" . RSS_LANGUAGE . "</language>\n        <image><title>{$xerte_toolkits_site->name}</title>\n        <url>{$xerte_toolkits_site->site_url}website_code/images/xerteLogo.jpg</url>\n        <link>{$xerte_toolkits_site->site_url}</link></image>";
} else {
    $temp_array = explode("_", $_GET['username']);
    $query_created_by = "select login_id from {$xerte_toolkits_site->database_table_prefix}logindetails where (firstname=? AND surname = ?)";
    $rows = db_query($query_created_by, array($temp_array[0], $temp_array[1]));
    if (sizeof($rows) == 0) {
        header("HTTP/1.0 404 Not Found");
        exit(0);
    } else {
        $folder_string = 'public';
        if (isset($_GET['folder_name'])) {
            $folder_string = " - " . _html_escape(str_replace("_", " ", $_GET['folder_name']));
        }
        echo "<rss version=\"2.0\">\n        <channel><title>{$xerte_toolkits_site->name}</title>\n        <link>{$xerte_toolkits_site->site_url}</link>\n        <description>" . RSS_DESCRIPTION . " " . $xerte_toolkits_site->name . "</description>\n        <language>" . RSS_LANGUAGE . "</language>\n        <image><title>{$xerte_toolkits_site->name}</title>\n        <url>{$xerte_toolkits_site->site_url}website_code/images/xerteLogo.jpg</url>\n        <link>{$xerte_toolkits_site->site_url}</link></image>";
        $row_create = $rows[0];
    }
}
$params = array();
if (!isset($_GET['username'])) {
    $query = "select {$xerte_toolkits_site->database_table_prefix}templatedetails.template_id,creator_id,date_created,template_name,description \n        FROM {$xerte_toolkits_site->database_table_prefix}templatedetails, {$xerte_toolkits_site->database_table_prefix}templatesyndication \n        WHERE {$query_modifier}='true' AND {$xerte_toolkits_site->database_table_prefix}templatedetails.template_id = {$xerte_toolkits_site->database_table_prefix}templatesyndication.template_id";
} else {
    if (!isset($_GET['folder_name'])) {
        $query = "select {$xerte_toolkits_site->database_table_prefix}templatedetails.template_id,creator_id,date_created,template_name,description \n            FROM {$xerte_toolkits_site->database_table_prefix}templatedetails, {$xerte_toolkits_site->database_table_prefix}templatesyndication \n            WHERE {$query_modifier}='true' AND creator_id=? AND {$xerte_toolkits_site->database_table_prefix}templatedetails.template_id = {$xerte_toolkits_site->database_table_prefix}templatesyndication.template_id";
        $params[] = $row_create['login_id'];
    } else {
        $row_folder = db_query_one("SELECT folder_id FROM {$xerte_toolkits_site->database_table_prefix}folderdetails WHERE folder_name = ?", array(str_replace("_", " ", $_GET['folder_name'])));
        if (empty($row_folder)) {
Example #14
0
function do_userinfo($formatter, $options)
{
    global $DBInfo;
    $user =& $DBInfo->user;
    $min_ttl = !empty($DBInfo->user_suspend_time_default) ? intval($DBInfo->user_suspend_time_default) : 60 * 30;
    $formatter->send_header('', $options);
    $allowed = $DBInfo->security_class == 'acl' && $DBInfo->security->is_allowed($options['action'], $options);
    $ismember = $user->is_member;
    $suspend = !empty($options['suspend']) ? true : false;
    $pause = !empty($options['pause']) ? true : false;
    $comment_btn = !empty($options['comment_btn']) ? true : false;
    $comment = !empty($options['comment']) ? trim($options['comment']) : '';
    $uids = (array) $options['uid'];
    if ($user->id == 'Anonymous') {
        $myid = $_SERVER['REMOTE_ADDR'];
    } else {
        $myid = $user->id;
    }
    if (!$ismember && $allowed) {
        // not a member users
        $suspend = false;
        if (empty($comment)) {
            $comment_btn = false;
        } else {
            $comment_btn = true;
        }
        // a normal user can pause himself
        if (sizeof($uids) > 1 || $uids[0] != $myid) {
            $pause = false;
        }
        // reset type
        $options['type'] = '';
    }
    // cleanup comment
    $comment = strtr($comment, array("\n" => ' ', "\t" => ' '));
    $comment = _html_escape($comment);
    // FIXME only owners can delete/suspend users
    $can_delete_user = in_array($user->id, $DBInfo->owners);
    if ($allowed || $ismember) {
        if (isset($_POST) and empty($options['act']) and isset($options['uid'])) {
            $udb =& $DBInfo->udb;
            $type = !empty($options['type']) ? $options['type'] : '';
            if (!in_array($type, array('wait', 'del'))) {
                $type = '';
            }
            // normal user not allowed to suspend, delete user
            if (!$can_delete_user) {
                $suspend = false;
                $type = '';
            }
            $change = array();
            if ($can_delete_user and !$pause and !$comment_btn) {
                foreach ($uids as $uid) {
                    $uid = _stripslashes($uid);
                    if ($type == 'del' || $type == 'wait' || $suspend) {
                        $ret = $udb->activateUser($uid, $suspend);
                    } else {
                        $ret = $udb->delUser($uid);
                    }
                    if ($ret) {
                        $change[] = $uid;
                    }
                }
            } else {
                if ($comment_btn and !empty($comment)) {
                    $mb = new Cache_Text('msgboard');
                    foreach ($uids as $uid) {
                        $info = $mb->fetch($uid, 0);
                        $ttl = 0;
                        if ($info === false) {
                            $info = array();
                            $info['comment'] = '';
                        }
                        // add comment
                        if (!empty($comment)) {
                            // upate comments
                            $comments = array();
                            if (!empty($info['comment'])) {
                                $comments = explode("\n", $info['comment']);
                            }
                            $comments[] = date('Y-m-d H:i', time()) . "\t" . $myid . "\t" . $comment;
                            if ($uid == '127.0.0.1' and sizeof($comments) > 500) {
                                array_shift($comments);
                            } else {
                                if (sizeof($comments) > 1000) {
                                    array_shift($comments);
                                }
                            }
                            $info['comment'] = implode("\n", $comments);
                        }
                        $mb->update($uid, $info);
                        $change[] = $uid;
                    }
                } else {
                    if (!empty($uids) && $pause) {
                        // user can suspend temporary himself
                        if ($ismember || sizeof($uids) == 1 && $uid == $user->id) {
                            $change = $uids;
                        }
                    }
                }
            }
            if (!empty($change)) {
                $changed = implode(',', $change);
                if ($suspend) {
                    $options['msg'] = sprintf(_("User \"%s\" are suspended !"), _html_escape($changed));
                } else {
                    if ($pause) {
                        $options['msg'] = sprintf(_("User \"%s\" are temporary suspended !"), _html_escape($changed));
                    } else {
                        if ($type == 'del' || $type == 'wait') {
                            $options['msg'] = sprintf(_("User \"%s\" are activated !"), _html_escape($changed));
                        } else {
                            if ($comment_btn) {
                                $options['msg'] = sprintf(_("Message added to \"%s\"."), _html_escape($changed));
                            } else {
                                $options['msg'] = sprintf(_("User \"%s\" are deleted !"), _html_escape($changed));
                            }
                        }
                    }
                }
            }
            if ((!$suspend and $type == 'del' || $type == 'wait' or $pause) and !empty($change)) {
                // make users temporary suspdended 5-minutes
                // or temporary suspdended 30 minutes for newly suspended user
                // abusefilter cache
                $ac = new Cache_Text('abusefilter');
                // prepare to return
                $ret = array();
                $retval = array();
                $ret['retval'] =& $retval;
                foreach ($change as $q) {
                    // fetch monitor information
                    $info = $ac->fetch($q, 0, $ret);
                    $ttl = 0;
                    if ($info === false) {
                        $new_info = array('create' => 0, 'delete' => 0, 'revert' => 0, 'save' => 0, 'edit' => 0, 'add_lines' => 0, 'del_lines' => 0, 'add_chars' => 0, 'del_chars' => 0);
                        $new_info['id'] = $q;
                        if ($pause) {
                            $ttl = $min_ttl;
                        } else {
                            $ttl = 60 * 5;
                        }
                    } else {
                        $new_info = $info;
                        $ttl = $retval['ttl'] - (time() - $retval['mtime']);
                        $new_info['id'] = $q;
                        if ($pause) {
                            $addttl = $min_ttl;
                        } else {
                            $addttl = 60 * 5;
                        }
                        if ($ttl < $addttl) {
                            $ttl = $addttl;
                        }
                    }
                    $new_info['suspended'] = true;
                    // add comment
                    if (!empty($comment)) {
                        // add comment
                        $comments = array();
                        if (!empty($new_info['comment'])) {
                            $comments = explode("\n", $new_info['comment']);
                        }
                        $comments[] = date('Y-m-d H:i', time()) . "\t" . $user->id . "\t" . $comment;
                        if ($q == '127.0.0.1' and sizeof($comments) > 10) {
                            array_shift($comments);
                        } else {
                            if (sizeof($comments) > 5) {
                                array_shift($comments);
                            }
                        }
                        $new_info['comment'] = implode("\n", $comments);
                    }
                    $ac->update($q, $new_info, $ttl);
                }
            }
        }
        $list = macro_UserInfo($formatter, '', $options);
    } else {
        $options['msg'] = sprintf(_("You are not allowed to \"%s\" !"), "userinfo");
        $list = '';
    }
    $options['.title'] = _("User Information");
    $formatter->send_title('', '', $options);
    print $list;
    $formatter->send_footer('', $options);
    return;
}
Example #15
0
function macro_Comment($formatter, $value, $options = array())
{
    global $DBInfo;
    if (!empty($options['nocomment'])) {
        return '';
    }
    // set as dynamic macro or not.
    if ($formatter->_macrocache and empty($options['call'])) {
        return $formatter->macro_cache_repl('Comment', $value);
    }
    if (empty($options['call'])) {
        $formatter->_dynamic_macros['@Comment'] = 1;
    }
    $user = $DBInfo->user;
    # get from COOKIE VARS
    $options['id'] = $user->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;
        }
    }
    $captcha = '';
    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;
    }
    $hidden = '';
    if (empty($options['page'])) {
        $options['page'] = $formatter->page->name;
    }
    if (empty($options['action']) || $options['action'] == 'show') {
        $action = 'comment';
    } else {
        $action = $options['action'];
    }
    if (!empty($options['mode'])) {
        $hidden .= "<input type='hidden' name='mode' value='" . $options['mode'] . "' />\n";
    }
    if (!empty($options['no'])) {
        $hidden .= "<input type='hidden' name='no' value='" . $options['no'] . "' />\n";
    }
    if (!empty($options['p'])) {
        $hidden .= "<input type='hidden' name='p' value='" . $options['p'] . "' />\n";
    }
    if ($value) {
        $args = explode(',', $value);
        if (in_array('usemeta', $args)) {
            $use_meta = 1;
        }
        if (in_array('oneliner', $args)) {
            $oneliner = 1;
        }
    }
    if (!empty($options['usemeta']) or !empty($use_meta)) {
        $hidden .= "<input type='hidden' name='usemeta' value='1' />\n";
    }
    if (!$DBInfo->security->writable($options)) {
        return '';
    }
    if (!empty($options['mid'])) {
        $mymid = $options['mid'];
    } else {
        $mymid = $formatter->mid;
    }
    $emid = base64_encode($mymid . ',Comment,' . $value);
    $mid = $mymid;
    $cols = get_textarea_cols();
    $rows = (!empty($options['rows']) and $options['rows'] > 5) ? $options['rows'] : 5;
    $cols = (!empty($options['cols']) and $options['cols'] > 60) ? $options['cols'] : $cols;
    if (!empty($options['datestamp'])) {
        $datestamp = $options['datestamp'];
    } else {
        $datestamp = $formatter->page->mtime();
    }
    $savetext = !empty($options['savetext']) ? $options['savetext'] : '';
    $savetext = str_replace(array("&", "<"), array("&amp;", "&lt;"), $savetext);
    $url = $formatter->link_url($formatter->page->urlname);
    if ($emid) {
        $hidden .= '<input type="hidden" name="comment_id" value="' . $emid . '" />';
    }
    $form = "<form id='editform' method='post' action='{$url}'>\n<div>";
    if (!empty($use_meta)) {
        $form .= "<a id='add_comment' name='add_comment'></a>";
    }
    $comment = _("Comment");
    $preview_btn = _("Preview");
    $preview = '';
    $savetext = _html_escape($savetext);
    if (!empty($oneliner)) {
        $form .= <<<FORM
<input class='wiki' size='{$cols}' name="savetext" value="{$savetext}" />&nbsp;
FORM;
    } else {
        if (empty($options['nopreview'])) {
            $preview = '<span class="button"><input type="submit" class="button" name="button_preview" value="' . $preview_btn . '" /></span>';
        }
        $form .= <<<FORM
<textarea class="wiki" name="savetext"
 rows="{$rows}" cols="{$cols}">{$savetext}</textarea><br />
FORM;
    }
    $sig = '';
    if ($options['id'] == 'Anonymous') {
        $name = !empty($options['name']) ? $options['name'] : '';
        $name = _html_escape($name);
        $sig = _("Username") . ": <input name='name' value=\"{$name}\" size='10' />";
    } else {
        if (empty($use_meta)) {
            $sig = "<input name='nosig' type='checkbox' />" . _("Don't add a signature");
        }
    }
    $form .= <<<FORM2
{$hidden}
{$captcha}
{$sig}
<input type="hidden" name="action" value="{$action}" />
<input type="hidden" name="datestamp" value="{$datestamp}" />
<span class="button"><input type="submit" class="button" value="{$comment}" /></span>
{$preview}
</div>
</form>
FORM2;
    return '<div class="commentForm">' . $form . '</div>';
}
Example #16
0
function do_notfound($formatter, $options = array())
{
    global $DBInfo, $Config;
    if ($formatter->page->exists()) {
        echo '<html><head></head><body><h1>' . _("Page found") . '</h1></body></html>';
        return;
    }
    $msg_404 = 'Status: 404 Not found';
    if (!empty($Config['no_404'])) {
        $msg_404 = '';
    }
    // for IE
    if (!empty($options['is_robot']) or !empty($Config['nofancy_404'])) {
        if (!empty($msg_404)) {
            $formatter->header($msg_404);
        }
        echo '<html><head></head><body><h1>' . _("Page not found") . '</h1></body></html>';
        return true;
    }
    $formatter->send_header($msg_404, $options);
    if (empty($DBInfo->metadb)) {
        $DBInfo->initMetaDB();
    }
    $twins = $DBInfo->metadb->getTwinPages($formatter->page->name, 2);
    if ($twins) {
        $formatter->send_title('', '', $options);
        $twins = "\n" . implode("\n", $twins);
        $formatter->send_page(_("See TwinPages : ") . $twins);
        echo "<br />" . $formatter->link_to("?action=edit", $formatter->icon['create'] . _("Create this page"));
    } else {
        $oldver = '';
        if ($DBInfo->version_class) {
            $version = $DBInfo->lazyLoad('version', $DBInfo);
            $oldver = $version->rlog($formatter->page->name, '', '', '-z');
        }
        $button = $formatter->link_to("?action=edit", $formatter->icon['create'] . _("Create this page"));
        if ($oldver) {
            $formatter->send_title(sprintf(_("%s has saved revisions"), $formatter->page->name), '', $options);
            $searchval = _html_escape($options['page']);
            echo '<h2>' . sprintf(_("%s or click %s to fulltext search.\n"), $button, $formatter->link_to("?action=fullsearch&amp;value={$searchval}", _("here"))) . '</h2>';
            $options['info_actions'] = array('recall' => 'view', 'revert' => 'revert');
            $options['title'] = '<h3>' . sprintf(_("Old Revisions of the %s"), _html_escape($formatter->page->name)) . '</h3>';
            // if (empty($formatter->wordrule)) $formatter->set_wordrule();
            echo $formatter->macro_repl('Info', '', $options);
        } else {
            $formatter->send_title(sprintf(_("%s is not found in this Wiki"), $formatter->page->name), '', $options);
            $searchval = _html_escape($options['page']);
            if (!empty($DBInfo->default_fullsearch)) {
                $fullsearch = $DBInfo->default_fullsearch;
                if (strpos($fullsearch, '%s') !== false) {
                    $fullsearch = sprintf($fullsearch, $searchval);
                } else {
                    $fullsearch .= $searchval;
                }
                $fullsearch = '<a href="' . $fullsearch . '">' . _("here") . '</a>';
            } else {
                $fullsearch = $formatter->link_to("?action=fullsearch&amp;value=" . $searchval, _("here"));
            }
            echo '<h2>' . sprintf(_("%s or click %s to fulltext search.\n"), $button, $fullsearch) . '</h2>';
            $err = array();
            echo $formatter->macro_repl('LikePages', $formatter->page->name, $err);
            if (!empty($err['extra'])) {
                echo $err['extra'];
            }
            echo '<h2>' . _("Please try to search with another word") . '</h2>';
            $ret = array('call' => 1);
            $ret = $formatter->macro_repl('TitleSearch', '', $ret);
            //if ($ret['hits'] == 0)
            echo "<div class='searchResult'>" . $ret['form'] . "</div>";
        }
        echo "<hr />\n";
        $options['linkto'] = "?action=edit&amp;template=";
        $options['limit'] = -1;
        $tmpls = $formatter->macro_repl('TitleSearch', $DBInfo->template_regex, $options);
        if ($tmpls) {
            echo sprintf(_("%s or alternativly, use one of these templates:\n"), $button);
            echo $tmpls;
        } else {
            echo "<h3>" . _("You have no templates") . "</h3>";
        }
        echo sprintf(_("To create your own templates, add a page with '%s' pattern.\n"), $DBInfo->template_regex);
    }
    $args = array('editable' => 1);
    $formatter->send_footer($args, $options);
    return;
}
Example #17
0
function do_merge($formatter, $params = array())
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($params)) {
        $params['title'] = _("Page is not writable");
        return do_invalid($formatter, $params);
    }
    // check full permission to edit
    $full_permission = true;
    if (!empty($DBInfo->no_full_edit_permission) or $params['id'] == 'Anonymous' && !empty($DBInfo->anonymous_no_full_edit_permission)) {
        $full_permission = false;
    }
    // members always have full permission to edit
    if (in_array($params['id'], $DBInfo->members)) {
        $full_permission = true;
    }
    $is_new = !$formatter->page->exists();
    if (!$is_new and !$full_permission) {
        $formatter->send_header('', $params);
        $title = _("You do not have full permission to merge this page.");
        $formatter->send_title($title, '', $params);
        $formatter->send_footer('', $params);
        return;
    }
    $pagename = isset($params['name'][0]) ? $params['name'] : '';
    $formatter->send_header('', $params);
    $force = 1;
    if (isset($_POST['name'][0]) and $DBInfo->hasPage($_POST['name'])) {
        $force = 0;
        if ($_POST['force']) {
            $force = 1;
        }
    }
    // validate rev
    if (!empty($params['rev'])) {
        $info = $formatter->page->get_info($params['rev']);
        if (empty($info[0])) {
            unset($params['rev']);
            if (!empty($_POST['rev'])) {
                unset($_POST['rev']);
            }
        }
    }
    if (!empty($_POST['rev']) and isset($_POST['name'][0]) and $pagename !== $formatter->page->name and $DBInfo->hasPage($pagename)) {
        if (!empty($DBInfo->version_class)) {
            $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
            $user =& $DBInfo->user;
            $comment = _stripslashes($params['comment']);
            $tag = '{MERGE}';
            if (!empty($comment)) {
                $comment = $tag . ': ' . $comment . ': ';
            } else {
                $comment = $tag . ': ';
            }
            $log = $REMOTE_ADDR . ';;' . $user->id . ';;' . $comment;
            $version = $DBInfo->lazyLoad('version', $DBInfo);
            if (!method_exists($version, 'merge')) {
                // check merge method
                $formatter->send_title(_("No merge method available."), '', $params);
                $formatter->send_footer('', $params);
                return;
            }
            $params['log'] = $log;
            $ret = array();
            $params['retval'] =& $ret;
            // merge RCS revisions
            $merged = $version->merge($pagename, $formatter->page->name, $params);
            if (!$force) {
                $fname = tempnam($DBInfo->vartmp_dir, 'MERGED');
                $fp = fopen($fname . ',v', 'w');
                if (is_resource($fp)) {
                    fwrite($fp, $merged);
                    fclose($fp);
                }
                // parse rlog
                require_once dirname(__FILE__) . '/Info.php';
                $out = $version->rlog($fname . ',v', '');
                $params['simple'] = true;
                $info = _parse_rlog($formatter, $out, $params);
                @unlink($fname);
                @unlink($fname . ',v');
            } else {
                if ($merged !== false) {
                    // $params['retval']['comment'] has merged versions information
                    $log = $comment . $params['retval']['comment'];
                    $DBInfo->addLogEntry($pagename, $REMOTE_ADDR, $log, 'MERGE');
                    $indexer = $DBInfo->lazyLoad('titleindexer');
                    if ($is_new) {
                        $indexer->addPage($pagename);
                    } else {
                        $indexer->update($pagename);
                    }
                    $info = '';
                }
            }
        } else {
            $formatter->send_title(_("No version control available."), '', $params);
            $formatter->send_footer('', $params);
            return;
        }
        $params['.title'] = _("Merge result.");
        $formatter->send_title(sprintf(_("%s is successfully merged."), $formatter->page->name), '', $params);
        if (!$force) {
            echo '<h3>' . _("This is a testing merge. Please confirm force option to merge it.") . '</h3>';
        }
        echo $info;
        $formatter->send_footer('', $params);
        return;
    } else {
        if (!isset($params['name'][0]) || !$DBInfo->hasPage($params['name'])) {
            $title = _("Please select the original page to merge.");
        } else {
            if (empty($params['rev'])) {
                $title = _("Please select the revision to merge from.");
            } else {
                if ($DBInfo->hasPage($formatter->page->name)) {
                    $title = _("Are you really want to merge this page ?");
                }
            }
        }
        $params['.title'] = _("Merge Page history.");
        $formatter->send_title($title, '', $params);
    }
    $pname = _html_escape($pagename);
    $lab = _("Summary");
    $rev = !empty($params['rev']) ? _html_escape($params['rev']) : '';
    if (!empty($rev) && isset($pagename[0]) && $DBInfo->hasPage($pagename)) {
        $extra = '<input type="checkbox" name="force" />' . _("Force overwrite") . '<br />';
        $placeholder = sprintf(_("Merge [[%s]] with [[%s]] from r%s: "), $pname, _html_escape($formatter->page->name), $rev);
        echo "<form method='post'>\n{$lab}: <input name='comment' size='80' value='{$comment}' placeholder='{$placeholder}' /><br />\n";
        $btn = sprintf(_("Merge [[%s]] to [[%s]]:"), _html_escape($formatter->page->name), $pname);
        $msg = sprintf(_("Only WikiMaster can %s this page"), _("merge"));
        if ($DBInfo->security->is_protected("merge", $params)) {
            echo _("Password") . ": <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n";
        }
        echo <<<FORM
    <input type='hidden' name='name' value='{$pname}' />
    <input type='hidden' name='action' value='merge' />
    <input type='hidden' name='rev' value='{$rev}' />
    <input type='submit' value='{$btn}' />{$extra}
    </form>
FORM;
    } else {
        $btn = _("Select Page to Merge");
        echo <<<FORM
    <form method='get'>
    <input name='name' value='{$pname}' />
    <input type='hidden' name='action' value='merge' />
    <input type='submit' value='{$btn}' />{$extra}
    </form>
FORM;
    }
    if (isset($pagename[0]) && $pagename !== $formatter->page->name && $DBInfo->hasPage($pagename)) {
        echo macro_Merge($formatter, $pagename, $params);
    }
    $formatter->send_footer('', $params);
    return;
}
Example #18
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);
}
Example #19
0
function do_sendping($formatter, $options)
{
    global $DBInfo, $_release;
    if (!$formatter->page->exists()) {
        $options['msg'] = _("Error: Page Not found !");
        do_invalid($formatter, $options);
        return;
    }
    if (strtolower($DBInfo->charset) == 'utf-8') {
        $checked = 'checked="checked"';
    }
    if (!$options['trackback_url']) {
        $url = $formatter->link_url($formatter->page->urlname);
        $raw_body = $formatter->page->_get_raw_body();
        if ($options['value']) {
            $lines = explode("\n", $raw_body);
            $count = count($lines);
            # 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]) {
                            $end_tag = '}}}';
                        }
                        break;
                    }
                }
            }
            if ($found) {
                # a blog page with multiple entries
                $i++;
                if ($end_tag) {
                    for (; $i < $count; $i++) {
                        if (preg_match("/^}}}\$/", $lines[$i])) {
                            break;
                        } else {
                            if (preg_match("/^----\$/", $lines[$i])) {
                                break;
                            }
                        }
                        $excerpt .= $lines[$i] . "\n";
                    }
                } else {
                    # a blog page with a single entry
                    list($dummy, $entry) = explode("\n", $raw_body, 2);
                    list($excerpt, $comments) = explode("\n----\n", $entry, 2);
                }
            } else {
                $options['msg'] = _("Error: No entry found!");
                do_invalid($formatter, $options);
                return;
            }
        } else {
            # a plain wiki page
            $excerpt = substr($raw_body, 0, 400);
            $title = $options['page'];
        }
        $COLS_MSIE = 80;
        $COLS_OTHER = 85;
        $cols = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? $COLS_MSIE : $COLS_OTHER;
        $rows = $options['rows'] > 5 ? $options['rows'] : 8;
        $cols = $options['cols'] > 60 ? $options['cols'] : $cols;
        $formatter->send_header("", $options);
        $formatter->send_title(_("Send TrackBack ping"), "", $options);
        $msg1 = _("TrackBack Ping URL");
        print "<form method='post' action='{$url}'>\n";
        print "<b>{$msg1}</b>: <input name='trackback_url' size='60' maxlength='256' style='width:200' /><br />\n";
        if ($options['value']) {
            $options['value'] = _html_escape($options['value']);
            print "<input type='hidden' name='value' value=\"{$options['value']}\" />\n";
        }
        $msg2 = _("Title");
        $title = _html_escape($title);
        print "<b>{$msg2}</b>: <input name='title' value=\"{$title}\" size='70' maxlength='70' style='width:200' /><br />\n";
        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="excerpt"
 rows="{$rows}" cols="{$cols}" class="wiki">{$excerpt}</textarea></div>
FORM;
        $mb_msg = _("mb encoded");
        $send_msg = _("Send ping");
        $reset = _("Reset");
        print <<<FORM2
<b>{$mb_msg}</b> <input type="checkbox" name="mbencode" {$checked} />&nbsp;
<input type="hidden" name="action" value="sendping" />
<span class="button"><input class="button" type="submit" value="{$send_msg}" /></span>&nbsp;
<span class="button"><input class="button" type="reset" value="{$reset}" /></span>&nbsp;
</form>
FORM2;
        $formatter->send_footer("", $options);
        return;
    }
    # send Trackback ping
    $trackback_url = $options['trackback_url'];
    $title = urlencode(_stripslashes($options['title']));
    $blog_name = urlencode($DBInfo->sitename . ":{$options['id']}");
    $excerpt = _stripslashes($options['excerpt']);
    if ($options['mbencode']) {
        if ($checked and function_exists('iconv') and strtolower($DBInfo->charset) != 'utf-8') {
            $excerpt = iconv($DBInfo->charset, 'utf-8', $excerpt);
        }
        if (function_exists('mb_encode_numericentity')) {
            $new = mb_encode_numericentity($excerpt, $DBInfo->convmap, 'utf-8');
            if ($new) {
                $excerpt = $new;
            }
            $new = mb_encode_numericentity($title, $DBInfo->convmap, 'utf-8');
            if ($new) {
                $title = $new;
            }
        } else {
            include_once 'lib/compat.php';
            $new = utf8_mb_encode($excerpt);
            if ($new) {
                $excerpt = $new;
            }
            $new = utf8_mb_encode($title);
            if ($new) {
                $title = $new;
            }
        }
    }
    $excerpt = urlencode($excerpt);
    $url = $formatter->link_url($options['page'], "#{$options['value']}");
    $url = urlencode(qualifiedUrl($url));
    $query_string = "title={$title}&url={$url}&blog_name={$blog_name}&excerpt={$excerpt}";
    if (strstr($trackback_url, '?')) {
        $trackback_url .= "&" . $query_string;
        $fp = @fopen($trackback_url, 'r');
        $result = @fread($fp, 4096);
        @fclose($fp);
        /* debug code
            $debug_file = 'trackback.log';
            $fp = fopen($debug_file, 'a');
            fwrite($fp, "\n*****\nTrackback URL query:\n\n$trackback_url\n\nResponse:\n\n");
            fwrite($fp, $result);
            fwrite($fp, "\n\n");
            fclose($fp);
        */
    } else {
        $trackback_url = parse_url($trackback_url);
        $http_request = 'POST ' . $trackback_url['path'] . " HTTP/1.0\r\n";
        $http_request .= 'Host: ' . $trackback_url['host'] . "\r\n";
        $http_request .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
        $http_request .= 'Content-Length: ' . strlen($query_string) . "\r\n";
        $http_request .= "\r\n";
        $http_request .= $query_string;
        $fs = @fsockopen($trackback_url['host'], 80);
        @fputs($fs, $http_request);
        /* debug code
            $debug_file = 'trackback.log';
            $fp = fopen($debug_file, 'a');
            fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
            while(!@feof($fs)) {
              fwrite($fp, @fgets($fs, 4096));
            }
            fwrite($fp, "\n\n");
            fclose($fp);
        */
        @fclose($fs);
    }
    $formatter->send_header("", $options);
    $formatter->send_title(_("Trackback sent"), "", $options);
    #$formatter->send_page("Return: $result");
    print "Return: {$result}";
    $formatter->send_footer("", $options);
    return;
}
Example #20
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;
    }
    $scrap_max = !empty($DBInfo->scrap_max) ? $DBInfo->scrap_max : 20;
    $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);
                // trash old
                if (sizeof($pages) > $scrap_max) {
                    array_shift($pages);
                }
            }
            $pages = array_unique($pages);
        }
        $page_list = _html_escape(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);
}
Example #21
0
function do_revoke($formatter, $options)
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    }
    $is_new = false;
    if (!$formatter->page->exists()) {
        $is_new = true;
    }
    if ($is_new) {
        $formatter->send_header('', $options);
        $title = _("You can't revoke already deleted page.");
        $formatter->send_title($title, '', $options);
        $formatter->send_footer('', $options);
        return;
    }
    // check revocable
    $params = array();
    $retval = array();
    $params['retval'] =& $retval;
    macro_Stat($formatter, $value, $params);
    $is_ok = false;
    if ($retval['first_author'] == $options['id'] || in_array($options['id'], $DBInfo->members)) {
        $is_ok = true;
    }
    // get the site specific hash code
    $ticket = $formatter->page->mtime() . getTicket($DBInfo->user->id, $_SERVER['REMOTE_ADDR']);
    $hash = md5($ticket);
    $formatter->send_header('', $options);
    if ($is_ok && $_SERVER['REQUEST_METHOD'] == 'POST' && $hash == $options['hash']) {
        // simple comment check
        $comment = _stripslashes($options['comment']);
        $comment = trim($comment);
        $default = _("Revoke");
        if (isset($comment[0]) && ($p = strpos($comment, $default)) === 0) {
            $comment = substr($comment, strlen($default));
            $comment = trim($comment);
            $comment = ltrim($comment, ': ');
        }
        $options['comment'] = isset($comment[0]) ? $default . ': ' . $comment : $default;
        $options['.revoke'] = true;
        $ret = $DBInfo->deletePage($formatter->page, $options);
        if ($ret == -1) {
            if (!empty($options['retval']['msg'])) {
                $title = $options['retval']['msg'];
            } else {
                $title = sprintf(_("Fail to revoke \"%s\""), _html_escape($formatter->page->name));
            }
        } else {
            $title = sprintf(_("\"%s\" is successfully revoked !"), _html_escape($formatter->page->name));
        }
        $formatter->send_title($title, '', $options);
        $formatter->send_footer('', $options);
        return;
    }
    $pagename = $formatter->page->name;
    $lab = _("Summary");
    if (!$is_ok) {
        $title = _("You are not the first author of this page or do not have enough revoke permission");
        $formatter->send_title($title, '', $options);
        $formatter->send_footer('', $options);
        return;
    }
    if ($retval['first_author'] == $options['id']) {
        $title = _("You are the first author of this page");
    } else {
        $title = _("Do you want to revoke this page?");
    }
    $formatter->send_title($title, '', $options);
    $comment = _("Revoke");
    print "<form method='post'>\n    {$lab} : <input name='comment' size='80' value='{$comment}: ' /><br />\n";
    $btn = _("Revoke page");
    $msg = sprintf(_("Only WikiMaster can %s this page"), _("revoke"));
    if ($DBInfo->security->is_protected("revoke", $options)) {
        print _("Password") . ": <input type='password' name='passwd' size='20' value='' />\n{$msg}<br />\n";
    }
    print "\n    <input type='hidden' name='action' value='revoke' />\n    <input type='hidden' name='hash' value='{$hash}' />\n    <input type='submit' value='{$btn}' />{$extra}\n    </form>";
    $formatter->send_footer('', $options);
    return;
}
Example #22
0
function do_wikidiff($formatter, $params = array())
{
    global $Config;
    $supported = array('default' => '%0%2?action=raw', 'namuwiki' => '%1raw/%2');
    if (!empty($Config['wikidiff_sites'])) {
        $wikis = $Config['wikidiff_sites'];
    } else {
        $wikis = array('kowikipedia' => 'https://ko.wikipedia.org/wiki/', 'librewiki' => 'http://librewiki.net/wiki/', 'namuwiki' => 'https://namu.wiki/raw/');
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['wiki']) && isset($wikis[$_POST['wiki']])) {
        require_once dirname(__FILE__) . '/../lib/HTTPClient.php';
        $wiki = $_POST['wiki'];
        if (isset($supported[$wiki])) {
            $format_url = $supported[$wiki];
        } else {
            $format_url = $supported['default'];
        }
        $url = $wikis[$wiki];
        $parsed = parse_url($url);
        if (isset($_POST['value'][0])) {
            $pagename = rawurlencode($_POST['value']);
        } else {
            $pagename = $formatter->page->urlname;
        }
        // translate table.
        $trs = array('%0' => $url, '%1' => $parsed['scheme'] . '://' . $parsed['host'] . '/', '%2' => $pagename);
        $request_url = strtr($format_url, $trs);
        $save = ini_get('max_execution_time');
        set_time_limit(0);
        $http = new HTTPClient();
        $http->timeout = 15;
        // set timeout
        // support proxy
        if (!empty($Config['proxy_host'])) {
            $http->proxy_host = $Config['proxy_host'];
            if (!empty($Config['proxy_port'])) {
                $http->proxy_port = $Config['proxy_port'];
            }
        }
        $http->sendRequest($request_url, array(), 'GET');
        set_time_limit($save);
        $formatter->send_header('', $params);
        if ($http->status != 200) {
            $params['.title'] = sprintf(_("Fail to connect %s"), $http->status);
            $diff = null;
        } else {
            $diff = $formatter->get_diff($http->resp_body);
            $params['.title'] = sprintf(_("Difference between this wiki and %s."), $wiki);
        }
        $formatter->send_title('', '', $params);
        if (isset($diff[0])) {
            echo "<div id='wikiDiffPreview'>\n";
            echo $formatter->processor_repl('diff', $diff, $params);
            echo "</div>\n";
        } else {
            if ($http->status != 200) {
                echo sprintf(_("Status: %s"), $http->status);
            } else {
                echo _("No difference found.");
            }
        }
        $formatter->send_footer('', $params);
        return;
    }
    $select = '<select name="wiki">';
    $select .= '<option>' . _("-- Select Wiki --") . '</option>';
    foreach ($wikis as $w => $url) {
        $select .= '<option value="' . $w . '">' . $w . '</option>' . "\n";
    }
    $select .= '</select>';
    $name = isset($_GET['value'][0]) ? $_GET['value'] : '';
    $default = _html_escape($formatter->page->name);
    $optional = '<br />' . _("Page name:") . ' <input type="text" name="value" placeholder="' . $default . '" value="' . _html_escape($name) . '" /><br />';
    //$optional .= _("Reverse order:")." <input type='checkbox' name='reverse' /> ";
    $params['.title'] = _("Show difference between wikis.");
    $button = _("Diff");
    $formatter->send_header('', $params);
    $formatter->send_title('', '', $params);
    echo <<<FORM
<form method='post'>
{$select}
{$optional}
<input type='submit' value='{$button}' />
<input type='hidden' name='action' value='wikidiff' />
</form>
FORM;
    $formatter->send_footer('', $params);
    return;
}
Example #23
0
function processor_bts($formatter, $value = '', $options = '')
{
    global $DBInfo;
    $rating_script =& $GLOBALS['rating_script'];
    $script = <<<SCRIPT
<script type="text/javascript">
/*<![CDATA[*/
/* from bugzilla script with small fix */
  /* Outputs a link to call replyToComment(); used to reduce HTML output */
  function addReplyLink(id) {
    /* XXX this should really be updated to use the DOM Core's
     * createElement, but finding a container isn't trivial */
    document.write('[<a href="#add_comment" onclick="replyToComment(' + 
        id + ');">reply<' + '/a>]');
  }

  /* Adds the reply text to the `comment' textarea */
  function replyToComment(id) {
    /* pre id="comment_name_N" */
    var text_elem = document.getElementById('comment_text_'+id);
    var text = getText(text_elem);

    /* make sure we split on all newlines -- IE or Moz use \\r and \\n
     * respectively */
    text = text.split(/\\r|\\n/);

    var replytext = "";
    for (var i=0; i < text.length; i++) {
        replytext += "> " + text[i] + "\\n"; 
    }

    replytext = "(In reply to comment #" + id + ")\\n" + replytext + "\\n";

    /* <textarea name="savetext"> */
    var textarea = document.getElementsByTagName('textarea');
    textarea[0].value += replytext;

    textarea[0].focus();
  }

  if (!Node) {
    /* MSIE doesn't define Node, so provide a compatibility array */
    var Node = {
        TEXT_NODE: 3,
        ENTITY_REFERENCE_NODE: 5
    };
  }

  /* Concatenates all text from element's childNodes. This is used
   * instead of innerHTML because we want the actual text (and
   * innerText is non-standard) */
  function getText(element) {
    var child, text = "";
    for (var i=0; i < element.childNodes.length; i++) {
        child = element.childNodes[i];
        var type = child.nodeType;
        if (type == Node.TEXT_NODE || type == Node.ENTITY_REFERENCE_NODE) {
            text += child.nodeValue;
        } else {
            /* recurse into nodes of other types */
            text += getText(child);
        }
    }
    return text;
  }
/*]]>*/
</script>
SCRIPT;
    if ($value[0] == '#' and $value[1] == '!') {
        list($arg, $value) = explode("\n", $value, 2);
    }
    if (!empty($arg)) {
        # get parameters
        list($tag, $user, $date, $title) = explode(" ", $line, 4);
        if (preg_match('/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/', $user)) {
            $user = "******";
        }
        if ($date && $date[10] == 'T') {
            $date[10] = ' ';
            $time = strtotime($date . ' GMT');
            $date = '@ ' . date('Y-m-d [h:i a]', $time);
        }
    }
    $bts_conf = 'BugTrack/Config';
    if ($DBInfo->hasPage($bts_conf)) {
        $p = new WikiPage($bts_conf);
        $config_raw = $p->get_raw_body();
        $confs = _get_btsConfig($config_raw);
        #print_r($confs);
    }
    $body = $value;
    # parse metadata
    $meta = '';
    while (true) {
        list($line, $body) = explode("\n", $body, 2);
        if (isset($line[0]) and $line[0] == '#') {
            continue;
        }
        if (strpos($line, ':') === false or !trim($line)) {
            break;
        }
        $meta .= $line . "\n";
    }
    $metas = getMetadata($meta);
    $head = "##[[InputForm(form:get:bts)]]\n##[[HTML(<table width='100%'><tr><td @@ valign='top'>)]]\n";
    $extra = '';
    $attr = '<tablewidth="100%">';
    $sep = 1;
    foreach ($metas as $k => $v) {
        $kk = $k;
        if (in_array($k, array('Version', 'Component'))) {
            $kk = str_replace(' ', '-', ucwords($metas['Product'])) . '-' . $k;
        }
        if ($k[0] == 'X' and $k[1] == '-') {
            if (isset($confs[$kk])) {
                $v = '[[InputForm(:' . _($kk) . ':' . str_replace($v, $v . ' 1', $confs[$kk]) . ')]]';
            }
            $k = substr($k, 2);
            if (substr($k, 0, 9) == 'Separator') {
                $sep++;
                $head .= "\n##\n##[[HTML(</td><td @@ valign='top'>)]]\n";
                $attr = '<tablewidth="100%">';
            } else {
                if (substr($k, 0, 4) == 'Date') {
                    $v = '[[DateTime(' . $v . ')]]';
                }
                $head .= "||" . $attr . " ''" . $k . "'' || " . $v . " ||\n";
                $attr = '';
            }
        } else {
            if ($k == 'Summary' or $k == 'Keywords') {
                $v = str_replace(':', '&#58;', $v);
                $v = '[[InputForm(input:' . _($k) . ':' . $confs[$k] . ':' . $v . ')]]';
                $extra .= "|| '''" . _($k) . "'''''':'''||{$v}||\n";
            } else {
                if (isset($confs[$kk])) {
                    $v = '[[InputForm(:' . _($kk) . ':' . str_replace($v, $v . ' 1', $confs[$kk]) . ')]]';
                }
                $head .= "||" . $attr . "<width='30%'> '''" . _($k) . "'''''':'''||" . $v . " ||\n";
                $attr = '';
            }
        }
    }
    $attr = 'width="100%"';
    if ($sep > 1) {
        $attr = 'width="' . 100 / $sep . '%"';
    }
    $head = preg_replace('/@@/', $attr, $head);
    $head .= "\n##\n##[[HTML(</td></tr></table>)]]\n" . $extra . "\n" . "[[InputForm(submit:" . _("Save Changes") . ")]]\n##[[InputForm]]";
    #print '<pre>'.$head.'</pre>';
    print <<<HEAD
<fieldset id="bts-properties"><legend>Change Properties</legend>
HEAD;
    $formatter->send_page($head, $options);
    print <<<TAIL
</fieldset>
TAIL;
    if ($body) {
        $options['nosisters'] = 1;
        $copy = $body;
        $hidden = '';
        #list($comment,$copy)=explode("----\n",$copy,2);
        $tmp = explode("----\n", $copy, 2);
        $comment = $tmp[0];
        $copy = isset($tmp[1]) ? $tmp[1] : '';
        while (!empty($comment)) {
            #list($comment,$copy)=explode("----\n",$copy,2);
            $tmp = explode("----\n", $copy, 2);
            $comment = $tmp[0];
            $copy = isset($tmp[1]) ? $tmp[1] : '';
            if (preg_match('/^Comment-Id:\\s*(\\d+)/i', $comment, $m)) {
                list($myhead, $my) = explode("\n\n", $comment, 2);
                $hidden .= '<pre style="display:none;" id="comment_text_' . $m[1] . '">' . _html_escape($my) . '</pre>';
            }
        }
        ob_start();
        # add some basic rule/repl for bts
        $rule = "/----\nComment-Id:\\s*(\\d+)\n" . "From:\\s*([^\n]+)\nDate:\\s*([^\n]+)\n\n/im";
        $repl = "----\n'''Comment-Id:''' [#c\\1][#c\\1 #\\1] by \\2 on [[DateTime(\\3)]] [reply \\1]\n\n";
        $body = preg_replace($rule, $repl, $body);
        $formatter->quote_style = 'bts-comment';
        $options['usemeta'] = 1;
        #
        $formatter->baserule[] = "/^((-=)+-?\$)/";
        $formatter->baserule[] = "/ comment #(\\d+)\\b/";
        $formatter->baserule[] = "/Bug #?(\\d+)\\b/";
        $formatter->baserule[] = "/\\[reply (\\d+)\\]/";
        $formatter->baserepl[] = "<hr />\n";
        $formatter->baserepl[] = " comment [#c\\1 #\\1]";
        $formatter->baserepl[] = "wiki:BugTrack:\\1";
        $formatter->baserepl[] = "<script type='text/javascript'><!--\n            addReplyLink(\\1); //--></script>";
        #
        $formatter->send_page($body, $options);
        $msg = ob_get_contents();
        ob_end_clean();
    }
    $msg .= $formatter->macro_repl('Comment(meta)', '', $options);
    if (!empty($bts_script)) {
        return $msg . $hidden;
    }
    $bts_script = 1;
    return $script . $msg . $hidden;
}
Example #24
0
function do_post_jme($formatter, $options)
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    }
    $draw_dir = str_replace("./", '', $DBInfo->upload_dir . '/JME');
    $pagename = $options['page'];
    !empty($options['value']) ? $name = $options['value'] : !empty($options['name']) ? $name = $options['name'] : null;
    if (empty($name)) {
        $name = time();
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST' and $options['mol']) {
        $dummy = explode('/', $name);
        $name = $dummy[count($dummy) - 1];
        $molname = $name . '.mol';
        $fp = fopen($draw_dir . '/' . $molname, 'w');
        if ($fp) {
            fwrite($fp, $options['mol']);
            fclose($fp);
        }
        $formatter->send_header('', $options);
        $formatter->send_title(_("Molecule successfully added"), '', $options);
        $formatter->send_footer('', $options);
        return;
    }
    $formatter->send_header('', $options);
    $formatter->send_title(_("Edit Molecule"), '', $options);
    $script = <<<SCRIPT
<script type="text/javascript">
/*<![CDATA[*/
function setMolFile(obj) {
    var mol = document.JME.molFile();
    obj.mol.value = mol;
}

function getGauFile(obj) {
    var mol = document.JME.molFile();
    var lines = mol.split("\\n");
    var i=0;
    var gau="%chk=\\n# ub3lyp/6-311g(d,p) OPT FREQ POP=full\\n\\n";
    gau += obj.name.value + "\\n\\n0 1\\n";

    while (i < lines.length) {
        var mat = lines[i].match(/^\\s+([^\\s]+)\\s+([^\\s]+)\\s+([^\\s]+)\\s+([A-Z]{1,2})\\s+.*/);
        if (mat != null) {
            gau += mat[4] + ' ' + mat[1] + ' ' + mat[2] + ' ' + mat[3] + "\\n";
        }
        i++;
    }

    obj.mol.value = gau + "\\n";
}
/*]]>*/
</script>
SCRIPT;
    $pubpath = $DBInfo->url_prefix . "/applets/JMEPlugin";
    print "<h2>" . _("Edit new molecule") . "</h2>\n";
    $name = _html_escape($name);
    print <<<FORM
{$script}
<form method="POST" action="">
<applet code="JME.class" name="JME" codebase="{$pubpath}" archive="JME.zip"
width="360" height="315">
<param name=" options"  value="multipart; autoez";>
You have to enable Java and JavaScritpt on your machine !
</applet><br />
<input type="hidden" name="action" value="jme" />
<input type="hidden" name="name" value="{$name}" />
<input type="submit" name="submit_button" value="Submit" onclick="setMolFile(this.form)" />
<input type="button" name="gau_button" value="Get Gaussian input" onclick="getGauFile(this.form)" />
<input type="button" value="Get Mol" onclick="setMolFile(this.form)" />
<input type="reset" value="reset" />
<div class="molecule">
<textarea cols="50" rows="20" name="mol" /></textarea></div>
</form>
FORM;
    $formatter->send_footer("", $options);
    return;
}
Example #25
0
function generate_item($formatter, $log)
{
    global $DBInfo;
    list($page, $user, $date, $title, $summary) = $log;
    if (!$title) {
        return "";
    }
    $url = qualifiedUrl($formatter->link_url(_urlencode($page)));
    /* perma link */
    $tag = md5($user . ' ' . $date . ' ' . $title);
    /* RFC 822 date format for RSS 2.0 */
    $date[10] = ' ';
    $pubDate = gmdate('D, j M Y H:i:s T', strtotime(substr($date, 0, 19) . ' GMT'));
    /* description */
    if ($summary) {
        $p = new WikiPage($page);
        $f = new Formatter($p);
        $summary = str_replace('\\}}}', '}}}', $summary);
        ob_start();
        $f->send_page($summary, array('fixpath' => 1, 'nojavascript' => 1));
        $description = '<description><![CDATA[' . ob_get_contents() . ']]></description>';
        ob_end_clean();
    }
    /* convert special characters into HTML entities */
    $title = _html_escape($title);
    return <<<ITEM
<item>
  <title>{$title}</title>
  <link>{$url}#{$tag}</link>
  <guid isPermaLink="true">{$url}#{$tag}</guid>
  {$description}
  <pubDate>{$pubDate}</pubDate>
  <author>{$user}</author>
  <category domain="{$url}">{$page}</category>
  <comments><![CDATA[{$url}?action=blog&value={$tag}#BlogComment]]></comments>
</item>

ITEM;
}
Example #26
0
function macro_PageList($formatter, $arg = "", $options = array())
{
    global $DBInfo;
    $offset = '';
    if (!is_numeric($options['offset']) or $options['offset'] <= 0) {
        unset($options['offet']);
    } else {
        $offset = $options['offset'];
    }
    preg_match("/([^,]*)(\\s*,\\s*)?(.*)?\$/", $arg, $match);
    if ($match[1] == 'date') {
        $options['date'] = 1;
        $arg = '';
    } else {
        if ($match) {
            $arg = $match[1];
            $opts = array();
            if ($match[3]) {
                $opts = explode(",", $match[3]);
            }
            if (in_array('date', $opts)) {
                $options['date'] = 1;
            }
            if (in_array('dir', $opts)) {
                $options['dir'] = 1;
            }
            if (in_array('subdir', $opts)) {
                $options['subdir'] = 1;
            }
            if (in_array('info', $opts)) {
                $options['info'] = 1;
            } else {
                if ($arg and (in_array('metawiki', $opts) or in_array('m', $opts))) {
                    $options['metawiki'] = 1;
                }
            }
        }
    }
    $upper = '';
    if (!empty($options['subdir'])) {
        if (($p = strrpos($formatter->page->name, '/')) !== false) {
            $upper = substr($formatter->page->name, 0, $p);
        }
        $needle = _preg_search_escape($formatter->page->name);
        $needle = '^' . $needle . '\\/';
    } else {
        if (!empty($options['rawre'])) {
            $needle = $arg;
        } else {
            $needle = _preg_search_escape($arg);
        }
    }
    $test = @preg_match("/{$needle}/", "", $match);
    if ($test === false) {
        # show error message
        return "[[PageList(<font color='red'>Invalid \"{$arg}\"</font>)]]";
    }
    $ret = array();
    $options['ret'] =& $ret;
    $options['offset'] = $offset;
    if (!empty($options['date'])) {
        $tz_offset =& $formatter->tz_offset;
        $all_pages = $DBInfo->getPageLists($options);
    } else {
        if (!empty($options['metawiki'])) {
            $all_pages = $DBInfo->metadb->getLikePages($needle);
        } else {
            $all_pages = $DBInfo->getLikePages($needle);
        }
    }
    $hits = array();
    $out = '';
    if (!empty($options['date']) and !is_numeric($k = key($all_pages)) and is_numeric($all_pages[$k])) {
        if ($needle) {
            while (list($pagename, $mtime) = @each($all_pages)) {
                preg_match("/{$needle}/", $pagename, $matches);
                if ($matches) {
                    $hits[$pagename] = $mtime;
                }
            }
        } else {
            $hits = $all_pages;
        }
        arsort($hits);
        while (list($pagename, $mtime) = @each($hits)) {
            $out .= '<li>' . $formatter->link_tag(_rawurlencode($pagename), "", _html_escape($pagename)) . ". . . . [" . gmdate("Y-m-d", $mtime + $tz_offset) . "]</li>\n";
        }
        $out = "<ol>\n" . $out . "</ol>\n";
    } else {
        foreach ($all_pages as $page) {
            preg_match("/{$needle}/", $page, $matches);
            if ($matches) {
                $hits[] = $page;
            }
        }
        sort($hits);
        if (!empty($options['dir']) or !empty($options['subdir'])) {
            $dirs = array();
            $files = array();
            if ($options['subdir']) {
                $plen = strlen($formatter->page->name) + 1;
            } else {
                $plen = 0;
            }
            foreach ($hits as $pagename) {
                if (($rp = strrpos($pagename, '/')) !== false) {
                    $p = strpos($pagename, '/');
                    $name = substr($pagename, $plen);
                    $dum = explode('/', $name);
                    if (sizeof($dum) > 1) {
                        $dirname = array_shift($dum);
                        $orgname = substr($pagename, 0, $p) . '/' . $dirname;
                        if (empty($dirs[$orgname])) {
                            $dirs[$orgname] = array();
                        }
                        $dirs[$orgname][] = implode('/', $dum);
                        $files[$orgname] = $dirname;
                    } else {
                        $files[$pagename] = $name;
                    }
                    continue;
                }
                $files[$pagename] = $pagename;
            }
            $iconset = 'tango';
            $icon_dir = $DBInfo->imgs_dir . '/plugin/UploadedFiles/' . $iconset;
            $dicon = "<img src='{$icon_dir}/folder-16.png' width='16px'/>";
            $uicon = "<img src='{$icon_dir}/up-16.png' width='16px'/>";
            $ficon = "<img src='{$icon_dir}/text-16.png' width='16px'/>";
            $now = time();
            if ($upper) {
                $out .= '<tr><td>' . $uicon . '</td><td>' . $formatter->link_tag(_rawurlencode($upper), "", '..') . '</td>';
            }
            foreach ($dirs as $pg => $name) {
                $out .= '<tr><td>' . $dicon . '</td><td>' . $formatter->link_tag(_rawurlencode($pg), "", _html_escape($files[$pg])) . '</td>';
                if ($options['info']) {
                    $p = new WikiPage($pg);
                    $mtime = $p->mtime();
                    $time_diff = (int) ($now - $mtime) / 60;
                    if ($time_diff < 1440) {
                        $date = sprintf(_("[%sh %sm ago]"), (int) ($time_diff / 60), $time_diff % 60);
                    } else {
                        $date = date("Y/m/d H:i", $mtime);
                    }
                    $out .= '<td>' . $date . '</td>';
                }
                $out .= "</tr>\n";
                if (isset($files[$pg])) {
                    unset($files[$pg]);
                }
            }
            foreach ($files as $pg => $name) {
                $out .= '<tr><td>' . $ficon . '</td><td>' . $formatter->link_tag(_rawurlencode($pg), "", _html_escape($name)) . '</td>';
                if (!empty($options['info'])) {
                    $p = new WikiPage($pg);
                    $mtime = $p->mtime();
                    $time_diff = (int) ($now - $mtime) / 60;
                    if ($time_diff < 1440) {
                        $date = sprintf(_("[%sh %sm ago]"), (int) ($time_diff / 60), $time_diff % 60);
                    } else {
                        $date = date("Y/m/d H:i", $mtime);
                    }
                    $out .= '<td>' . $date . '</td>';
                }
                $out .= "</tr>\n";
            }
            $out = '<table>' . $out . '</table>';
        } else {
            foreach ($hits as $pagename) {
                $out .= '<li>' . $formatter->link_tag(_rawurlencode($pagename), "", _html_escape($pagename)) . "</li>\n";
            }
            $out = "<ol>\n" . $out . "</ol>\n";
            $count = count($hits);
            $total = $DBInfo->getCounter();
            // hide the link of next page for anonymous user
            if (!empty($options['id']) and $options['id'] == 'Anonymous') {
                return $out;
            }
            if ($total > $count or $offset < $total) {
                if (isset($ret['offset']) and $ret['offset'] < $total and $count < $total) {
                    $extra = '';
                    if ($options['date']) {
                        $extra .= '&amp;date=1';
                    }
                    if ($options['info']) {
                        $extra .= '&amp;info=1';
                    }
                    if (isset($needle[0])) {
                        $extra .= '&amp;value=' . $needle;
                    }
                    $qoff = '&amp;offset=' . ($ret['offset'] + $count);
                    $out .= $formatter->link_to("?action=pagelist{$extra}{$qoff}", _("Show next page"));
                }
            }
        }
    }
    return $out;
}
Example #27
0
function _fix_entry($m)
{
    $decoded = _html_escape(urldecode($m[2]));
    return 'href="entry://' . $decoded . '"';
}
Example #28
0
function macro_WantedPages($formatter, $value = '', $params = array())
{
    global $DBInfo;
    // set as dynamic macro
    if ($formatter->_macrocache and empty($params['call'])) {
        return $formatter->macro_cache_repl('WantedPages', $value);
    }
    // set default page_limit
    if (empty($params['limit'])) {
        $params['limit'] = 100;
    }
    $offset = 0;
    if (!empty($params['offset'])) {
        if (is_numeric($params['offset']) and $params['offset'] > 0) {
            $offset = $params['offset'];
        }
    }
    $param = array();
    if (!empty($offset)) {
        $param['offset'] = $offset;
    }
    $param['limit'] = $params['limit'];
    $pages = $DBInfo->getPageLists($param);
    $pagelinks = $formatter->pagelinks;
    // save
    $save = $formatter->sister_on;
    $formatter->sister_on = 0;
    $cache = new Cache_text('pagelinks');
    $j = 0;
    foreach ($pages as $page) {
        $dum = '';
        $p = new WikiPage($page);
        $f = new Formatter($p);
        $pi = $f->page->get_instructions($dum);
        if (!in_array($pi['#format'], array('wiki', 'monimarkup'))) {
            continue;
        }
        $links = $f->get_pagelinks();
        if ($links) {
            $lns =& $links;
            foreach ($lns as $link) {
                if (empty($link) or $DBInfo->hasPage($link)) {
                    continue;
                }
                if (empty($wants[$link])) {
                    $wants[$link] = array('[["' . $page . '"]]');
                } else {
                    $wants[$link][] = '[["' . $page . '"]]';
                }
            }
        }
        $j++;
    }
    if (!count($wants)) {
        return '';
    }
    $pagelinks = $formatter->pagelinks;
    // save
    $formatter->sister_on = 0;
    asort($wants);
    $out = "<ul>\n";
    $old_owns = null;
    foreach ($wants as $name => $owns) {
        if ($old_owns != $owns) {
            $olinks = array_map(array($formatter, 'link_repl'), $owns);
            $olink = implode(', ', $olinks);
            if ($old_owns) {
                $out .= "</ul>\n</li>\n";
            }
            $out .= "<li>\n" . $olink . '<ul>';
            $old_owns = $owns;
        }
        $out .= '<li>' . $formatter->link_repl($name, _html_escape($name)) . '</li>' . "\n";
    }
    $out .= "</ul>\n</li>\n</ul>\n";
    $out .= $formatter->link_to("?action=wantedpages&amp;offset={$j}", _("Show next page"));
    $formatter->sister_on = $save;
    $formatter->pagelinks = $pagelinks;
    // restore
    return $out;
}
Example #29
0
function do_msgfmt($formatter, $options)
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    }
    $po = '';
    $domain = 'PoHello';
    if (isset($options['msgid']) or isset($options['msgstr'])) {
        # just check a single msgstr
        header("Content-type: text/plain");
        $date = date('Y-m-d h:i+0900');
        $charset = strtoupper($DBInfo->charset);
        if (_stripslashes($options['msgid']) != '""') {
            $po = <<<POHEAD
msgid ""
msgstr ""
"Project-Id-Version: {$domain} 1.1\\n"
"POT-Creation-Date: {$date}\\n"
"PO-Revision-Date: {$date}\\n"
"Last-Translator: MoniWiki <nobody@localhost>\\n"
"Language-Team: moniwiki <ko@localhost>\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset={$charset}\\n"
"Content-Transfer-Encoding: 8bit\\n"



#: src/test.c

POHEAD;
        }
        $po .= 'msgid ' . _stripslashes($options['msgid']) . "\n";
        #$msg=preg_replace('/""(?!")/',"\"\n\"",
        #    _stripslashes($options['msgstr']));
        $msg = _stripslashes($options['msgstr']);
        $po .= 'msgstr ' . $msg . "\n";
        $po .= "\n\n";
        $ret = _pocheck($po, 1);
        if ($ret == true) {
            print "true\n" . $po;
        }
        return;
    }
    if ($options['po'] and $options['btn']) {
        $formatter->send_header('', $options);
        $formatter->send_title(sprintf(_("Translation of %s"), $options['page']), '', $options);
        $comment = $options['comment'] ? _stripslashes($options['comment']) : "Translations are updated";
        $po = preg_replace("/(\r\n|\r)/", "\n", _stripslashes($options['po']));
        $formatter->page->write($po);
        $ret = $DBInfo->savePage($formatter->page, $comment, $options);
        if ($ret != -1) {
            print "<h2>" . _("Translations are successfully updated.") . "</h2>";
        } else {
            print "<h2>" . _("Fail to save translations.") . "</h2>";
        }
        $formatter->send_footer('', $options);
        return;
    }
    $msgkeys = array_keys($options);
    $msgids = preg_grep('/^msgid-/', $msgkeys);
    $msgstrs = preg_grep('/^msgstr-/', $msgkeys);
    if (sizeof($msgids) != sizeof($msgstrs)) {
        print "Invalid request.";
        return;
    }
    $rawpo = $formatter->page->_get_raw_body();
    $lines = explode("\n", $rawpo);
    $po = '';
    $comment = '';
    $msgid = array();
    $msgstr = array();
    foreach ($lines as $l) {
        if ($l[0] != 'm' and !preg_match('/^\\s*"/', $l)) {
            if ($msgstr) {
                $mid = implode("\n", $msgid);
                $id = md5($mid);
                $msg = preg_replace("/(\r\n|\r)/", "\n", _stripslashes($options['msgstr-' . $id]));
                $sid = md5(rtrim($msg));
                if ($options['md5sum-' . $id] and $options['md5sum-' . $id] != $sid) {
                    $comment = preg_replace('/#, fuzzy\\n/m', '', $comment);
                    $comment = str_replace(', fuzzy', '', $comment);
                }
                # fix msgstr
                #$msg=preg_replace('/(?!<\\\\)"/','\\"',$msg);
                $po .= $comment;
                $po .= 'msgid ' . preg_replace('/(\\r\\n|\\r)/', "\n", _stripslashes($options['msgid-' . $id])) . "\n";
                $po .= 'msgstr ' . $msg . "\n";
                # init
                $msgid = array();
                $msgstr = array();
                $comment = '';
            }
            if ($l[0] == '#' and $l[1] == ',') {
                if ($comment) {
                    $po .= $comment;
                    $comment = '';
                }
                $comment .= $l . "\n";
            } else {
                if ($comment) {
                    $po .= $comment;
                    $comment = '';
                }
                $po .= $l . "\n";
                continue;
            }
        } else {
            if (preg_match('/^(msgid|msgstr)\\s+(".*")\\s*$/', $l, $m)) {
                if ($m[1] == 'msgid') {
                    $msgid[] = $m[2];
                    continue;
                }
                $msgstr[] = $m[2];
            } else {
                if (preg_match('/^\\s*(".*")\\s*$/', $l, $m)) {
                    if ($msgstr) {
                        $msgstr[] = $m[1];
                    } else {
                        $msgid[] = $m[1];
                    }
                } else {
                    $po .= $l . "\n";
                }
            }
        }
    }
    $formatter->send_header('', $options);
    $formatter->send_title(sprintf(_("Translation of %s"), $options['page']), '', $options);
    $e = _pocheck($po);
    #if ($e != true) return;
    #print $po;
    $url = $formatter->link_url($formatter->page->urlname);
    print "<form method='post' action='{$url}'>\n" . "<input type='hidden' name='action' value='msgfmt' />\n";
    print "<input type='submit' name='btn' value='Save Translation ?' /> ";
    print "Summary:" . " <input type='text' size='60' name='comment' value='Translations are updated' />" . "<br />\n";
    if ($options['patch']) {
        include_once 'lib/difflib.php';
        $rawpo = array_map(create_function('$a', 'return $a."\\n";'), explode("\n", $rawpo));
        $newpo = array_map(create_function('$a', 'return $a."\\n";'), explode("\n", $po));
        $diff = new Diff($rawpo, $newpo);
        $f = new UnifiedDiffFormatter();
        $f->trailing_cr = "";
        $diffs = $f->format($diff);
        $sz = sizeof(explode("\n", $diffs));
        print "<textarea cols='80' rows='{$sz}' style='width:80%'>";
        print $diffs;
        print "</textarea>\n";
    }
    $po = _html_escape($po);
    print "<input type='hidden' name='po' value=\"{$po}\" />\n";
    print "</form>";
    $formatter->send_footer('', $options);
    return;
}
Example #30
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');
}