Example #1
0
function do_print($formatter, $options)
{
    global $DBInfo;
    $options['css_url'] = $DBInfo->url_prefix . "/css/print.css";
    $formatter->nonexists = 'always';
    $dum = false;
    $formatter->pi = $formatter->page->get_instructions($dum);
    $title = $formatter->pi['#title'];
    $formatter->send_header("", $options);
    kbd_handler();
    print "<div id='printHeader'>";
    print "<h2>{$title}</h2>";
    print "</div>";
    print "<div id='wikiContent'>";
    $formatter->external_on = 1;
    $formatter->send_page('', array('fixpath' => 1));
    print "</div></div>";
    print "<div id='printFooter'>";
    print sprintf(_("Retrieved from %s"), qualifiedUrl($formatter->link_url($formatter->page->name))) . '<br/>';
    if ($mtime = $formatter->page->mtime()) {
        $lastedit = date("Y-m-d", $mtime);
        $lasttime = date("H:i:s", $mtime);
        print sprintf(_("last modified %s %s"), $lastedit, $lasttime);
    }
    print "</div></body></html>";
    return;
}
Example #2
0
function do_sitemap($formatter, $options)
{
    global $DBInfo;
    # get page list
    if ($formater->group) {
        $group_pages = $DBInfo->getLikePages($formater->group);
        foreach ($group_pages as $page) {
            $all_pages[] = str_replace($formatter->group, '', $page);
        }
    } else {
        $all_pages = $DBInfo->getPageLists();
    }
    usort($all_pages, 'strcasecmp');
    $items = '';
    // empty string
    # process page list
    $zone = '+00:00';
    foreach ($all_pages as $page) {
        $url = qualifiedUrl($formatter->link_url(_rawurlencode($page)));
        $p = new WikiPage($page);
        $t = $p->mtime();
        $date = gmdate("Y-m-d\\TH:i:s", $t) . $zone;
        // W3C datetime format
        $item = "<url>\n";
        $item .= "  <loc>" . $url . "</loc>\n";
        $item .= "  <lastmod>" . $date . "</lastmod>\n";
        $item .= "</url>\n";
        $items .= $item;
    }
    # process output
    $out = $items;
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $new = iconv($DBInfo->charset, $charset, $items);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
            if ($new) {
                $out = $new;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9"
         url="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
         xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

HEAD;
    $foot = <<<FOOT
</urlset>
FOOT;
    # output
    header("Content-Type: text/xml");
    print $head . $out . $foot;
}
Example #3
0
function macro_RandomBanner($formatter, $value = "")
{
    global $DBInfo;
    $test = preg_match("/^([^ ,0-9]*)\\s*,?\\s*(\\d+)?\$/", $value, $match);
    if ($test) {
        $pagename = !empty($match[1]) ? $match[1] : '';
        $number = !empty($match[2]) ? $match[2] : '';
    }
    if (!$pagename) {
        $pagename = 'RandomBanner';
    }
    if (!$number) {
        $number = 3;
    }
    #print $pagename.";".$number;
    if ($DBInfo->hasPage($pagename)) {
        $page = $DBInfo->getPage($pagename);
        $body = $page->_get_raw_body();
    } else {
        return "[[RandomBanner({$value})]]";
    }
    $banner = array();
    $lines = explode("\n", $body);
    foreach ($lines as $line) {
        if (substr($line, 0, 10) != ' * http://') {
            continue;
        }
        $dummy = explode(" ", substr($line, 3), 3);
        $text = !empty($dummy[1]) ? $dummy[1] : '';
        $title = !empty($dummy[2]) ? $dummy[2] : '';
        if (!empty($text) and preg_match(",^(http|ftp|attachment):.*\\.(gif|png|jpg|jpeg)\$,", $text, $match)) {
            if ($match[1] == 'attachment') {
                $fname = $pagename . '/' . substr($text, 11);
                $ntext = $formatter->macro_repl('Attachment', $fname, 1);
                if (!file_exists($ntext)) {
                    $text = $formatter->macro_repl('Attachment', $fname);
                } else {
                    $text = qualifiedUrl($DBInfo->url_prefix . '/' . $ntext);
                    $text = "<img border='0' alt='{$text}' src='{$text}' title='{$title}' />";
                }
            } else {
                $text = "<img border='0' alt='{$text}' src='{$text}' title='{$title}' />";
            }
            $banner[] = "<a href='{$dummy['0']}'>{$text}</a>";
        }
    }
    $count = count($banner) - 1;
    $number = min($number, $count);
    $selected = array_rand($banner, $number);
    if ($number == 1) {
        $selected = array($selected);
    }
    $out = array();
    foreach ($selected as $idx) {
        $out[] = $banner[$idx];
    }
    $banners = implode(' ', $out);
    return $banners;
}
Example #4
0
function do_moniedit($formatter, $options)
{
    header("Content-Type: application/x-moniedit");
    #header("application/x-bat");
    header("Pragma: no-cache");
    print $options['page'] . " " . qualifiedUrl($formatter->prefix);
    return;
}
Example #5
0
 function smiley_repl($smiley)
 {
     global $DBInfo;
     if (is_array($smiley)) {
         $smiley = $smiley[1];
     }
     // for callback
     $img = $DBInfo->smileys[$smiley][3];
     $alt = str_replace("<", "&lt;", $smiley);
     return $this->_img(qualifiedUrl("{$DBInfo->imgs_dir}/{$img}"));
 }
Example #6
0
function do_Clip($formatter, $options)
{
    global $DBInfo;
    $enable_replace = 1;
    $keyname = $DBInfo->_getPageKey($options['page']);
    $_dir = str_replace("./", '', $DBInfo->upload_dir . '/' . $keyname);
    // support hashed upload dir
    if (!is_dir($_dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $prefix = get_hashed_prefix($keyname);
        $_dir = str_replace('./', '', $DBInfo->upload_dir . '/' . $prefix . $keyname);
    }
    $pagename = _urlencode($options['page']);
    $name = $options['value'];
    if (!$name) {
        $title = _("Fatal error !");
        $formatter->send_header("Status: 406 Not Acceptable", $options);
        $formatter->send_title($title, "", $options);
        print "<h2>" . _("No filename given") . "</h2>";
        $formatter->send_footer("", $options);
        return;
    }
    $pngname = _rawurlencode($name);
    //$imgpath="$_dir/$pngname";
    $imgpath = "{$pngname}";
    $imgparam = '';
    if (file_exists($_dir . '/' . $imgpath . '.png')) {
        $url = qualifiedUrl($DBInfo->url_prefix . '/' . $_dir . '/' . $imgpath . '.png');
        $imgparam = "<param name='image' value='{$url}' />";
    }
    $png_url = "{$imgpath}.png";
    $formatter->send_header("", $options);
    $formatter->send_title(_("Clipboard"), "", $options);
    $prefix = $formatter->prefix;
    $now = time();
    $url_exit = $formatter->link_url($pagename, "?ts={$now}");
    $url_save = $formatter->link_url($pagename, "?action=draw");
    $url_help = $formatter->link_url("ClipMacro");
    $pubpath = $DBInfo->url_prefix . "/applets/ClipPlugin";
    print "<h2>" . _("Cut & Paste a Clipboard Image") . "</h2>\n";
    print <<<APPLET
<applet code="clip"
 archive="clip.jar" codebase="{$pubpath}"
 width='200' height='200' align="center">
        <param name="pngpath"  value="{$png_url}" />
        <param name="savepath" value="{$url_save}" />
        <param name="viewpath" value="{$url_exit}" />
        <param name="compress" value="5" />
{$imgparam}
<b>NOTE:</b> You need a Java enabled browser to edit the drawing example.
</applet><br />
APPLET;
    $formatter->send_footer("", $options);
    return;
}
Example #7
0
function macro_Disqus($formatter, $value = '')
{
    global $Config;
    if (!empty($formatter->pi['#nocomment'])) {
        return '';
    }
    if (empty($Config['disqus_shortname'])) {
        echo "<a href='https://disqus.com/admin/signup/'>" . _("You need to register your forum at DISQUS.") . '</a>';
        return;
    }
    $js = <<<EOF
<script charset="utf-8" type="text/javascript">
/*<![CDATA[*/

EOF;
    // set disqus_identifier
    $id = $Config['disqus_shortname'] . ':';
    $shortname = $Config['disqus_shortname'];
    if (isset($Config['disqus_id'][0])) {
        $id .= $Config['disqus_id'] . ':';
    }
    $id .= addslashes($formatter->page->name);
    if (isset($Config['disqus_devel'])) {
        $js .= 'var disqus_developer = ' . $Config['disqus_devel'] . ";\n";
    }
    $js .= "var disqus_url     = '" . qualifiedUrl($formatter->link_url($formatter->page->urlname)) . "';\n";
    $js .= "var disqus_title   = '" . addslashes($formatter->page->name) . "';\n";
    $js .= "var disqus_identifier = '" . $id . "';\n";
    $js .= 'var disqus_container_id = \'disqus_thread\';' . "\n";
    $js .= "var disqus_shortname = '" . $Config['disqus_shortname'] . "';\n";
    $js .= <<<EOF
(function() {
function init() {
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
if (window.addEventListener) window.addEventListener("load", init, false);
else if (window.attachEvent) window.attachEvent("onload", init);
})();
/*]]>*/
</script>
EOF;
    $formatter->register_javascripts($js);
    $out = '';
    if (empty($value) or $value != 'notitle') {
        $out = '<h3><span class="i18n" title="Comments">' . _("Comments") . '</span>';
    }
    $out .= '</h3><div id="disqus_thread"></div>';
    $out .= '<noscript><a href="http://' . $shortname . '.disqus.com/?url=ref">' . _("View the discussion thread.") . '</a></noscript>';
    return $out;
}
Example #8
0
function postfilter_fiximgpath($formatter, $value, $options = array())
{
    global $DBInfo;
    $prefix = qualifiedUrl('');
    $chunks = preg_split('/(<[^>]+>)/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0, $sz = count($chunks); $i < $sz; $i++) {
        if (preg_match('/^<img /', $chunks[$i])) {
            $dumm = preg_replace('/<(img .*)src=(\'|\\")\\/([^\\2]+)\\2/i', "<\$1" . "src=\$2" . $prefix . "\$3\$2", $chunks[$i]);
            $chunks[$i] = $dumm;
        }
    }
    return implode('', $chunks);
}
Example #9
0
function do_qr($formatter, $params = array())
{
    global $Config;
    if (isset($params['value']) && isset($params['value'][0])) {
        $value = $params['value'];
    } else {
        $encoded = _urlencode(strtr($formatter->page->name, ' ', '_'));
        $value = qualifiedUrl($formatter->link_url($encoded));
    }
    if (!empty($Config['cache_public_dir']) and !empty($Config['cache_public_url'])) {
        $fc = new Cache_text('qr', array('ext' => 'png', 'dir' => $Config['cache_public_dir']));
        $pngname = $fc->getKey($value);
        $pngfile = $Config['cache_public_dir'] . '/' . $pngname;
        $png_url = !empty($Config['cache_public_url']) ? $Config['cache_public_url'] . '/' . $pngname : $Config['url_prefix'] . '/' . $pngfile;
    } else {
        $uniq = md5($value);
        $pngfile = $cache_dir . '/' . $uniq . '.png';
        $png_url = $cache_url . '/' . $uniq . '.png';
    }
    $img_exists = file_exists($pngfile);
    if (!$img_exists || $formatter->refresh) {
        require_once dirname(__FILE__) . '/../lib/phpqrcode.php';
        QRcode::png($value, $pngfile, 'l', 3, 1);
    }
    if (!empty($Config['use_cache_url'])) {
        header("Pragma: no-cache");
        header('Cache-Control: public, max-age=0, s-maxage=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate', false);
        $formatter->send_header(array('Status: 302', 'Location: ' . $png_url));
        return null;
    }
    $down_mode = 'inline';
    header("Content-Type: image/png\r\n");
    $mtime = filemtime($pngfile);
    $lastmod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
    $etag = md5($lastmod . $key);
    header('Last-Modified: ' . $lastmod);
    header('ETag: "' . $etag . '"');
    $maxage = 60 * 60 * 24 * 30;
    header('Cache-Control: public, max-age=' . $maxage);
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        header('HTTP/1.0 304 Not Modified');
        @ob_end_clean();
        return null;
    }
    @ob_clean();
    $ret = readfile($pngfile);
    return null;
}
Example #10
0
function postfilter_nforge($formatter, $value, $options)
{
    global $Config;
    preg_match("@\\/([^\\/]+)\$@", $formatter->url_prefix, $proj_name);
    $group_id = $Config['group_id'];
    $issue = qualifiedUrl('/tracker/index.php?func=detail&group_id=' . $group_id . '&aid=');
    $svn = qualifiedUrl('/scm/viewvc.php/?root=' . $proj_name[1] . '&view=rev&revision=');
    $_rule = array('/(?<![a-zA-Z&])\\!?\\#([0-9]+)/', "/(?<![a-zA-Z&])\\!?r([0-9]+)/");
    $_repl = array("<a href='{$issue}" . '\\1\'>#\\1</a>', "<a href='{$svn}" . '\\1\'>r\\1</a>');
    $chunks = preg_split('/(<[^>]+>)/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0, $sz = count($chunks); $i < $sz; $i++) {
        if ($i % 2 == 0) {
            $chunks[$i] = preg_replace($_rule, $_repl, $chunks[$i]);
        }
    }
    return implode('', $chunks);
}
Example #11
0
function macro_GoogleTrans($formatter, $value)
{
    global $DBInfo;
    $url = qualifiedUrl($formatter->link_url($formatter->page->name));
    $from = empty($value) ? substr($DBInfo->lang, 0, 2) : $value;
    $enc = strtolower($DBInfo->charset);
    $img_dir = $DBInfo->imgs_dir . '/interwiki';
    $supported = array('en' => 'English', 'fr' => 'Francais', 'de' => 'Deutsch', 'es' => 'Espanol', 'it' => 'Italiano', 'pt' => 'Portugues', 'zh' => 'Chinese', 'ru' => 'Russian', 'ja' => 'Japanese', 'ko' => 'Korean');
    if (array_key_exists($from, $supported)) {
        unset($supported[$from]);
    } else {
        $from = 'ko';
    }
    $out = '';
    foreach ($supported as $k => $v) {
        $out .= "<a target='_top' href='http://www.google.com/translate?hl={$from}&amp;ie={$enc}&amp;langpair={$from}%7C" . $k . "&amp;u={$url}' title='" . _($v) . "'><img src='{$img_dir}/" . $k . "-16.png' style='border:0' /></a>";
    }
    return $out;
}
Example #12
0
function macro_FreeMind($formatter, $value)
{
    global $DBInfo;
    $_dir = $DBInfo->upload_dir . '/FreeMind';
    $pubpath = $formatter->url_prefix . '/applets/FreeMind';
    $puburl = qualifiedUrl($formatter->url_prefix . '/' . $_dir);
    return <<<APP
  <applet code="freemind.main.FreeMindApplet.class" codebase="{$pubpath}"
          archive="freemindbrowser.jar" width="100%" height="100%">
  <param name="type" value="application/x-java-applet;version=1.4">
  <param name="scriptable" value="false">

  <param name="modes" value="freemind.modes.browsemode.BrowseMode">
  <param name="browsemode_initial_map"
         value="{$puburl}/{$value}.mm">
  <!--          ^ Put the path to your map here  -->
  <param name="initial_mode" value="Browse">
  </applet>
APP;
}
Example #13
0
function macro_MozTab($formatter, $value)
{
    global $DBInfo;
    $url = qualifiedUrl($formatter->link_url("", "?action=recentchanges"));
    $tab = <<<TAB
<script language="JavaScript">
/*<![CDATA[*/
 function selfside() {
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
          window.sidebar.addPanel ("{$DBInfo->sitename}", "{$url}","");
       }
       else {
          var rv = window.confirm ("This Funkcion should work with Netscape 6.x or Mozilla" + "www.mozilla.org");
          if (rv)
             document.location.href = "http://www.mozilla.org/";
       }
    }
/*]]>*/
</script>
<a href="javascript:selfside();"><img src="{$DBInfo->imgs_dir}/plugin/moztab.png" border=0 title="add mozilla tab"></a>
TAB;
    return $tab;
}
Example #14
0
function macro_BabelFish($formatter, $value, $ret = array())
{
    global $Config;
    $langs = array('ko', 'ja', 'en', 'de', 'fr', 'it', 'es', 'pt', 'zh');
    $supported = array('ko_en', 'en_ko', 'en_de', 'en_fr', 'en_pt', 'en_it', 'en_es', 'en_ja', 'en_zh', 'fr_en', 'es_en', 'pt_en', 'it_en', 'zh_en', 'fr_de', 'de_en', 'de_fr', 'ja_en', 'ru_en');
    $msg = _("BabelFish Translation");
    if (empty($value)) {
        $value = !empty($Config['default_babelfish_translation']) ? $Config['default_babelfish_translation'] : 'ko,en';
    }
    list($from, $to) = preg_split('/,\\s*/', preg_replace("/\\s+/", ' ', strtolower($value)), 2);
    if (!in_array($from, $langs)) {
        $from = 'en';
    }
    if (!in_array($to, $langs)) {
        $to = 'en';
    }
    if ($from and $to and $from != $to) {
        $msg = sprintf(_("Translate %s to %s"), $from, $to);
    }
    $lp = $from . "_" . $to;
    $URL = qualifiedUrl($formatter->link_url($formatter->page->urlname));
    $TR = "http://translate.google.com/translate?";
    if (in_array($lp, $supported)) {
        $URL = urlencode($URL);
        $TR .= "sl={$from}&amp;tl={$to}";
    } else {
        // not supported translation case
        // from => en => to
        $URL = urlencode($TR . "&amp;sl={$from}&amp;tl=en&amp;url={$URL}");
        $TR .= "&amp;sl=en&amp;tl={$to}";
    }
    $goto = $TR . '&amp;u=' . $URL;
    return <<<EOF
<img src='{$formatter->imgs_url_interwiki}{$from}-16.png' alt="{$from}"/> <a href="{$goto}"><img border='0' src='{$formatter->imgs_dir}/plugin/babelfish.png' title='{$msg}' alt='Translation@Google' /></a> <img src='{$formatter->imgs_url_interwiki}{$to}-16.png' alt="{$to}"/>
EOF;
}
Example #15
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 #16
0
function macro_Play($formatter, $value)
{
    global $DBInfo;
    static $autoplay = 1;
    $max_width = 600;
    $max_height = 400;
    $default_width = 320;
    $default_height = 240;
    #
    $media = array();
    #
    preg_match("/^(([^,]+\\s*,?\\s*)+)\$/", $value, $match);
    if (!$match) {
        return '[[Play(error!! ' . $value . ')]]';
    }
    if (($p = strpos($match[1], ',')) !== false) {
        $my = explode(',', $match[1]);
        for ($i = 0, $sz = count($my); $i < $sz; $i++) {
            if (strpos($my[$i], '=')) {
                list($key, $val) = explode('=', $my[$i]);
                $val = trim($val, '"\'');
                if ($key == 'width' and $val > 1) {
                    $width = $val;
                } else {
                    if ($key == 'height' and $val > 1) {
                        $height = $val;
                    }
                }
            } else {
                // multiple files
                $media[] = $my[$i];
            }
        }
    } else {
        $media[] = $match[1];
    }
    # set embeded object size
    $mywidth = !empty($width) ? min($width, $max_width) : null;
    $myheight = !empty($height) ? min($height, $max_height) : null;
    $width = !empty($width) ? min($width, $max_width) : $default_width;
    $height = !empty($height) ? min($height, $max_height) : $default_height;
    $url = array();
    $my_check = 1;
    for ($i = 0, $sz = count($media); $i < $sz; $i++) {
        if (!preg_match("/^(http|ftp|mms|rtsp):\\/\\//", $media[$i])) {
            $fname = $formatter->macro_repl('Attachment', $media[$i], array('link' => 1));
            if ($my_check and !file_exists($fname)) {
                return $formatter->macro_repl('Attachment', $value);
            }
            $my_check = 1;
            // check only first file.
            $fname = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $fname);
            $url[] = qualifiedUrl(_urlencode($fname));
        } else {
            $url[] = $media[$i];
        }
    }
    if ($autoplay == 1) {
        $play = "true";
    } else {
        $play = "false";
    }
    #
    $use_flashplayer_ok = 0;
    if ($DBInfo->use_jwmediaplayer) {
        $use_flashplayer_ok = 1;
        for ($i = 0, $sz = count($media); $i < $sz; $i++) {
            // check type of all files
            if (!preg_match("/(flv|mp3|mp4|swf)\$/i", $media[$i])) {
                $use_flashplayer_ok = 0;
                break;
            }
        }
    }
    if ($use_flashplayer_ok) {
        # set embed flash size
        if (($sz = count($media)) == 1 and preg_match("/(ogg|wav|mp3)\$/i", $media[0])) {
            // only one and a sound file
            $height = 20;
            // override the hegiht of the JW MediaPlayer
        }
        $swfobject_num = !empty($GLOBALS['swfobject_num']) ? $GLOBALS['swfobject_num'] : 0;
        $swfobject_script = '';
        if (!$swfobject_num) {
            $swfobject_script = "<script type=\"text/javascript\" src=\"{$DBInfo->url_prefix}/local/js/swfobject.js\"></script>\n";
            $num = 1;
        } else {
            $num = ++$swfobject_num;
        }
        $GLOBALS['swfobject_num'] = $num;
        if (!$DBInfo->jwmediaplayer_prefix) {
            $_swf_prefix = qualifiedUrl("{$DBInfo->url_prefix}/local/JWPlayers");
            // FIXME
        } else {
            $_swf_prefix = $DBInfo->jwmediaplayer_prefix;
        }
        $addparam = '';
        if ($sz > 1) {
            $md5sum = md5(implode(':', $media));
            if ($DBInfo->cache_public_dir) {
                $fc = new Cache_text('jwmediaplayer', array('dir' => $DBInfo->cache_public_dir));
                $fname = $fc->getKey($md5sum, false);
                $basename = $DBInfo->cache_public_dir . '/' . $fname;
                $urlbase = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $fname : $DBInfo->url_prefix . '/' . $basename;
                $playfile = $basename . '.xml';
            } else {
                $cache_dir = $DBInfo->upload_dir . "/VisualTour";
                $cache_url = $DBInfo->upload_url ? $DBInfo->upload_url . '/VisualTour' : $DBInfo->url_prefix . '/' . $cache_dir;
                $basename = $cache_dir . '/' . $md5sum;
                $urlbase = $cache_url . '/' . $md5sum;
                $playfile = $basename . '.xml';
            }
            $playlist = $urlbase . '.xml';
            $list = array();
            for ($i = 0; $i < $sz; $i++) {
                if (!preg_match("/^(http|ftp):\\/\\//", $url[$i])) {
                    $url = qualifiedUrl($url);
                }
                $ext = substr($media[$i], -3, 3);
                // XXX
                $list[] = '<title>' . $media[$i] . '</title>' . "\n" . '<location>' . $url[$i] . '</location>' . "\n";
            }
            $tracks = "<track>\n" . implode("</track>\n<track>\n", $list) . "</track>\n";
            // UTF-8 FIXME
            $xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
  <title>XSPF Playlist</title>
  <info>XSPF Playlist</info>
  <trackList>
{$tracks}
  </trackList>
</playlist>
XML;
            # check cache dir exists or not and make it
            if (!is_dir(dirname($playfile))) {
                $om = umask(00);
                _mkdir_p(dirname($playfile), 0777);
                umask($om);
            }
            if ($formatter->refresh or !file_exists($playfile)) {
                $fp = fopen($playfile, "w");
                fwrite($fp, $xml);
                fclose($fp);
            }
            $displayheight = $height;
            $height += $sz * 40;
            // XXX
            $addparam = "displayheight: '{$displayheight}'";
            $filelist = qualifiedUrl($playlist);
        } else {
            $filelist = $url[0];
        }
        $jw_script = <<<EOS
<p id="mediaplayer{$num}"></p>
<script type="text/javascript">
    (function() {
        var params = {
          allowfullscreen: "true"
        };

        var flashvars = {
          width: "{$width}",
          height: "{$height}",
          // image: "preview.jpg",
          {$addparam}
          file: "{$filelist}"
        };

        swfobject.embedSWF("{$_swf_prefix}/mediaplayer.swf","mediaplayer{$num}","{$width}","{$height}","0.0.9",
        "expressInstall.swf",flashvars,params);
    })();
</script>
EOS;
        return <<<EOS
      {$swfobject_script}{$jw_script}
EOS;
    } else {
        $out = '';
        $mysize = '';
        if (!empty($mywidth)) {
            $mysize .= 'width="' . $mywidth . 'px" ';
        }
        if (!empty($myheight)) {
            $mysize .= ' height="' . $myheight . 'px" ';
        }
        for ($i = 0, $sz = count($media); $i < $sz; $i++) {
            $mediainfo = 'External object';
            $classid = '';
            $objclass = '';
            $iframe = '';
            $object_prefered = false;
            // http://code.google.com/p/google-code-project-hosting-gadgets/source/browse/trunk/video/video.js
            if (preg_match("@https?://(?:[a-z-]+[.])?(?:youtube(?:[.][a-z-]+)+|youtu\\.be)/(?:watch[?].*v=|v/|embed/)?([a-z0-9_-]+)\$@i", $media[$i], $m)) {
                $movie = "http://www.youtube.com/v/" . $m[1];
                $type = 'type="application/x-shockwave-flash"';
                $attr = $mysize . 'allowfullscreen="true" allowScriptAccess="always"';
                $attr .= ' data="' . $movie . '?version=3' . '"';
                $url[$i] = $movie;
                $params = "<param name='movie' value='{$movie}?version=3'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n";
                $mediainfo = 'Youtube movie';
                $objclass = ' youtube';
            } else {
                if (preg_match("@https?://tvpot\\.daum\\.net\\/v\\/(.*)\$@i", $media[$i], $m)) {
                    $classid = "classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'";
                    $movie = "http://videofarm.daum.net/controller/player/VodPlayer.swf";
                    $type = 'type="application/x-shockwave-flash"';
                    $attr = 'allowfullscreen="true" allowScriptAccess="always" flashvars="vid=' . $m[1] . '&playLoc=undefined"';
                    if (empty($mysize)) {
                        $attr .= ' width="500px" height="281px"';
                    }
                    $url[$i] = $movie;
                    $params = "<param name='movie' value='{$movie}'>\n" . "<param name='flashvars' value='vid=" . $m[1] . "&playLoc=undefined'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n";
                    $mediainfo = 'Daum movie';
                    $objclass = ' daum';
                } else {
                    if (preg_match("@https?://vimeo\\.com\\/(.*)\$@i", $media[$i], $m)) {
                        if ($object_prefered) {
                            $movie = "https://secure-a.vimeocdn.com/p/flash/moogaloop/5.2.55/moogaloop.swf?v=1.0.0";
                            $type = 'type="application/x-shockwave-flash"';
                            $attr = 'allowfullscreen="true" allowScriptAccess="always" flashvars="clip_id=' . $m[1] . '"';
                            if (empty($mysize)) {
                                $attr .= ' width="500px" height="281px"';
                            }
                            $url[$i] = $movie;
                            $params = "<param name='movie' value='{$movie}'>\n" . "<param name='flashvars' value='clip_id=" . $m[1] . "'>\n" . "<param name='allowScriptAccess' value='always'>\n" . "<param name='allowFullScreen' value='true'>\n";
                        } else {
                            $iframe = 'http://player.vimeo.com/video/' . $m[1] . '?portrait=0&color=333';
                            $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen';
                            if (empty($mysize)) {
                                $attr .= ' width="500px" height="281px"';
                            }
                        }
                        $mediainfo = 'Vimeo movie';
                        $objclass = ' vimeo';
                    } else {
                        if (preg_match("/(wmv|mpeg4|mp4|avi|asf)\$/", $media[$i], $m)) {
                            $classid = "classid='clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95'";
                            $type = 'type="application/x-mplayer2"';
                            $attr = $mysize . 'autoplay="' . $play . '"';
                            $params = "<param name='FileName' value='" . $url[$i] . "' />\n" . "<param name='AutoStart' value='False' />\n" . "<param name='ShowControls' value='True' />";
                            $mediainfo = strtoupper($m[1]) . ' movie';
                        } else {
                            if (preg_match("/(wav|mp3|ogg)\$/", $media[$i], $m)) {
                                $classid = "classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'";
                                $type = '';
                                $attr = 'codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="30"';
                                $attr .= ' autoplay="' . $play . '"';
                                $params = "<param name='src' value='" . $url[$i] . "'>\n" . "<param name='AutoStart' value='{$play}' />";
                                $mediainfo = strtoupper($m[1]) . ' sound';
                            } else {
                                if (preg_match("/swf\$/", $media[$i])) {
                                    $type = 'type="application/x-shockwave-flash"';
                                    $classid = "classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'";
                                    $attr = 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"';
                                    $attr .= ' autoplay="' . $play . '"';
                                    $params = "<param name='movie' value='" . $url[$i] . "' />\n" . "<param name='AutoStart' value='{$play}' />";
                                } else {
                                    if (preg_match("/\\.xap/", $media[$i])) {
                                        $type = 'type="application/x-silverlight-2"';
                                        $attr = $mysize . 'data="data:application/x-silverlight,"';
                                        $params = "<param name='source' value='" . $url[$i] . "' />\n";
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $autoplay = 0;
            $play = 'false';
            if ($iframe) {
                $out .= <<<IFRAME
<div class='externalObject{$objclass}'><div>
<iframe src="{$iframe}" {$attr}></iframe>
<div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div>
IFRAME;
            } else {
                $myurl = $url[$i];
                $out .= <<<OBJECT
<div class='externalObject{$objclass}'><div>
<object class='external' {$classid} {$type} {$attr}>
{$params}
<param name="AutoRewind" value="True">
<embed {$type} src="{$myurl}" {$attr}></embed>
</object>
<div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div>
OBJECT;
            }
        }
    }
    if (empty($GLOBALS['js_macro_play'])) {
        $js = <<<JS
<script type='text/javascript'>
/*<![CDATA[*/
function openExternal(obj, display) {
  var el;
  (el = obj.parentNode.parentNode.firstElementChild) && (el.style.display = display);
}
/*]]>*/
</script>
JS;
        $formatter->register_javascripts($js);
        $GLOBALS['js_macro_play'] = 1;
    }
    return $out;
}
Example #17
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');
}
Example #18
0
function macro_Attachment($formatter, $value, $options = array())
{
    global $DBInfo;
    if (!is_array($options) and $options == 1) {
        $options = array('link' => 1);
    }
    // compatible
    $attr = '';
    if (!empty($DBInfo->force_download) or !empty($DBInfo->pull_url)) {
        $force_download = 1;
    }
    if (!empty($DBInfo->download_action)) {
        $mydownload = $DBInfo->download_action;
    } else {
        $mydownload = 'download';
    }
    $extra_action = '';
    $pull_url = $fetch_url = '';
    if (!empty($DBInfo->pull_url)) {
        $pull_url = $DBInfo->pull_url;
        if (empty($formatter->fetch_action)) {
            $fetch_url = $formatter->link_url('', '?action=fetch&url=');
        } else {
            $fetch_url = $formatter->fetch_action;
        }
    }
    $text = '';
    $caption = '';
    $cap_bra = '';
    $cap_ket = '';
    $bra = '';
    $ket = '';
    if ($options and !$DBInfo->security->is_allowed($mydownload, $options)) {
        return $text;
    }
    if (!empty($formatter->wikimarkup) and empty($options['nomarkup'])) {
        $ll = $rr = '';
        if (strpos($value, ' ') !== false) {
            $ll = '[';
            $rr = ']';
        }
        $bra = "<span class='wikiMarkup'><!-- wiki:\n{$ll}attachment:{$value}{$rr}\n-->";
        $ket = '</span>';
    }
    #  if ($value[0]=='"' and ($p2=strpos(substr($value,1),'"')) !== false)
    #    $value=substr($value,1,$p2); # attachment:"my image.png" => my image.png
    # FIXME attachment:"hello.png" => error
    if (($p = strpos($value, ' ')) !== false and strpos(substr($value, 0, $p), ',') === false) {
        // [[Attachment(my.png,width=100,height=200,caption="Hello(space)World")]]
        // [attachment:my.ext(space)hello]
        // [attachment:my.ext(space)attachment:my.png]
        // [attachment:my.ext(space)http://url/../my.png]
        if ($value[0] == '"' and ($p2 = strpos(substr($value, 1), '"')) !== false) {
            $text = $ntext = substr($value, $p2 + 3);
            $dummy = substr($value, 1, $p2);
            # "my image.png" => my image.png
            $args = substr($value, $p2 + 2);
            $value = $dummy . $args;
            # append query string
        } else {
            $text = $ntext = substr($value, $p + 1);
            $value = substr($value, 0, $p);
        }
        if (substr($text, 0, 11) == 'attachment:') {
            $fname = substr($text, 11);
            $ntext = macro_Attachment($formatter, $fname, array('link' => 1));
        }
        if (preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $ntext)) {
            $_l_ntext = _l_filename($ntext);
            if (!file_exists($_l_ntext)) {
                $fname = preg_replace('/^"([^"]*)"$/', "\\1", $fname);
                $mydownload = 'UploadFile&amp;rename=' . $fname;
                $text = sprintf(_("Upload new Attachment \"%s\""), $fname);
                $text = str_replace('"', '\'', $text);
            }
            $ntext = qualifiedUrl($DBInfo->url_prefix . '/' . $ntext);
            $img_link = '<img src="' . $ntext . '" alt="' . $text . '" border="0" />';
        } else {
            if (($q = strpos($ntext, ',')) !== false) {
                $alt = substr($ntext, 0, $q);
                $caption = substr($ntext, $q + 1);
            } else {
                $alt = $ntext;
            }
        }
    } else {
        $value = str_replace('%20', ' ', $value);
    }
    $lightbox_attr = '';
    $imgalign = '';
    // allowed thumb widths.
    $thumb_widths = isset($DBInfo->thumb_widths) ? $DBInfo->thumb_widths : array('120', '240', '320', '480', '600', '800', '1024');
    // parse query string of macro arguments
    if ($dummy = strpos($value, '?')) {
        # for attachment: syntax
        parse_str(substr($value, $dummy + 1), $attrs);
        $value = substr($value, 0, $dummy);
    } else {
        if (($dummy = strpos($value, ',')) !== false) {
            # for Attachment macro
            $tmp = substr($value, $dummy + 1);
            $tmp = preg_replace('/,+\\s*/', ',', $tmp);
            $tmp = preg_replace('/\\s*=\\s*/', '=', $tmp);
            $tmp = str_replace(',', '&', $tmp);
            parse_str($tmp, $attrs);
            $value = substr($value, 0, $dummy);
        }
    }
    $use_thumb = !empty($DBInfo->use_thumb_by_default) && empty($options['link_url']) ? true : false;
    if (!empty($attrs)) {
        if (!empty($attrs['action'])) {
            // check extra_action
            if ($attrs['action'] == 'deletefile') {
                $extra_action = $attrs['action'];
            } else {
                $mydownload = $attrs['action'];
            }
            unset($attrs['action']);
        }
        foreach ($attrs as $k => $v) {
            if (in_array($k, array('width', 'height'))) {
                $attr .= "{$k}=\"{$v}\" ";
                if (!empty($DBInfo->use_lightbox)) {
                    $lightbox_attr = ' rel="lightbox" ';
                }
            } else {
                if ($k == 'align') {
                    $imgalign = 'img' . ucfirst($v);
                } else {
                    if (in_array($k, array('caption', 'alt', 'title'))) {
                        $caption = preg_replace("/^([\"'])([^\\1]+)\\1\$/", "\\2", $v);
                        $caption = trim($caption);
                    } else {
                        if (in_array($k, array('thumb', 'thumbwidth', 'thumbheight'))) {
                            if ($k == 'thumbwidth' || $k == 'thumbheight') {
                                if (!empty($thumb_widths)) {
                                    if (in_array($v, $thumb_widths)) {
                                        $thumb[$k] = $v;
                                    }
                                } else {
                                    $thumb[$k] = $v;
                                }
                            } else {
                                $thumb[$k] = $v;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($thumb)) {
            $use_thumb = true;
        }
    }
    if (preg_match('/^data:image\\/(gif|jpe?g|png);base64,/', $value)) {
        // need to hack for IE ?
        return "<img src='" . $value . "' {$attr} />";
    }
    $attr .= $lightbox_attr;
    $info = '';
    if (($p = strrpos($value, ':')) !== false or ($p = strrpos($value, '/')) !== false) {
        $subpage = substr($value, 0, $p);
        $file = substr($value, $p + 1);
        $value = $subpage . '/' . $file;
        # normalize page arg
        if (isset($subpage[0])) {
            $pagename = $subpage;
            $key = $DBInfo->pageToKeyname($subpage);
            $value = $file;
        } else {
            $pagename = '';
            $key = '';
        }
    } else {
        $pagename = $formatter->page->name;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        $file = $value;
    }
    if (isset($key[0])) {
        $dir = $DBInfo->upload_dir . '/' . $key;
        // support hashed upload_dir
        if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
            $pre = get_hashed_prefix($key);
            $dir = $DBInfo->upload_dir . '/' . $pre . $key;
            if (!is_dir($dir)) {
                $dir = $DBInfo->upload_dir;
            }
        }
    } else {
        $dir = $DBInfo->upload_dir;
    }
    // check file name XXX
    if (!$file) {
        if (!empty($options['link']) and $options['link'] == 1) {
            return 'attachment:' . $value;
        }
        return $bra . 'attachment:/' . $ket;
    }
    $upload_file = $dir . '/' . $file;
    if (!empty($options['link']) and $options['link'] == 1) {
        return $upload_file;
    }
    if (!$text) {
        $text = $file;
    }
    $_l_file = _l_filename($file);
    $_l_upload_file = $dir . '/' . $_l_file;
    if (file_exists($_l_upload_file)) {
        $file_ok = 1;
    } else {
        if (!empty($pull_url)) {
            if (isset($subpage[0])) {
                $pagename = $subpage;
                $val = _urlencode($file);
            } else {
                $val = _urlencode($value);
            }
            $url = $pull_url . _rawurlencode($pagename) . "?action={$mydownload}&value=" . $val;
            $hsz = $formatter->macro_repl('ImageFileSize', $url);
            $info = ' (' . $hsz . ')';
            $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $url);
            // check url to retrieve the size of file
            if (empty($formatter->preview) or floatval($sz) != 0) {
                $file_ok = 2;
            }
        }
    }
    if (empty($file_ok) and !empty($formatter->wikimarkup) and empty($options['nomarkup'])) {
        if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
            $depth = $DBInfo->swfupload_depth;
        } else {
            $depth = 2;
        }
        if (session_id() == '') {
            // ip based
            $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI');
            // FIXME
        } else {
            $myid = session_id();
        }
        $prefix = substr($myid, 0, $depth);
        $mydir = $DBInfo->upload_dir . '/.swfupload/' . $prefix . '/' . $myid;
        if (file_exists($mydir . '/' . $_l_file)) {
            if (!$img_link && preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $upload_file)) {
                $ntext = qualifiedUrl($DBInfo->url_prefix . '/' . $mydir . '/' . $text);
                $img_link = '<img src="' . $ntext . '" alt="' . $text . '" border="0" />';
                return $bra . "<span class=\"attach\">{$img_link}</span>" . $ket;
            } else {
                $sz = filesize($mydir . '/' . $_l_file);
                $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
                for ($i = 0; $i < 4; $i++) {
                    if ($sz <= 1024) {
                        #$sz= round($sz,2).' '.$unit[$i];
                        break;
                    }
                    $sz = $sz / 1024;
                }
                $info = ' (' . round($sz, 2) . ' ' . $unit[$i] . ') ';
                return $bra . "<span class=\"attach\">" . $formatter->icon['attach'] . $text . '</span>' . $info . $ket;
            }
        }
    }
    if (!empty($file_ok)) {
        $imgcls = 'imgAttach';
        if ($imgalign == 'imgCenter' or $caption && empty($imgalign)) {
            if ($file_ok == 1 and !$attrs['width']) {
                $size = getimagesize($_l_upload_file);
                // XXX
                $attrs['width'] = $size[0];
            }
        }
        $img_width = '';
        if (!empty($attrs['width'])) {
            $img_width = ' style="width:' . $attrs['width'] . 'px"';
        }
        if ($caption) {
            $cls = $imgalign ? 'imgContainer ' . $imgalign : 'imgContainer';
            $cap_bra = '<div class="' . $cls . '"' . '>';
            $cap_ket = '</div>';
            $img_width = '';
        } else {
            $imgcls = $imgalign ? 'imgAttach ' . $imgalign : 'imgAttach';
        }
        if ($file_ok == 1) {
            $sz = filesize($_l_upload_file);
            $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
            for ($i = 0; $i < 4; $i++) {
                if ($sz <= 1024) {
                    break;
                }
                $sz = $sz / 1024;
            }
            $info = ' (' . round($sz, 2) . ' ' . $unit[$i] . ')';
        }
        if (!in_array('UploadedFiles', $formatter->actions)) {
            $formatter->actions[] = 'UploadedFiles';
        }
        if (empty($img_link) && preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $upload_file, $m)) {
            // get the extension of the image
            $ext = $m[1];
            $type = strtoupper($m[1]);
            if (!empty($caption)) {
                $caption = '<div class="caption">' . $caption . ' <span>[' . $type . ' ' . _("image") . $info . ']</span></div>';
            } else {
                $caption = '<div class="info"><span>[' . $type . ' ' . _("image") . $info . ']</span></div>';
            }
            if ($file_ok == 1 and !empty($use_thumb)) {
                $thumb_width = !empty($DBInfo->thumb_width) ? $DBInfo->thumb_width : 320;
                if (!empty($thumb['thumbwidth'])) {
                    $thumb_width = $thumb['thumbwidth'];
                }
                // guess thumbnails
                $thumbfiles = array();
                $thumbfiles[] = $_l_file;
                $thumbfiles[] = preg_replace('@' . $ext . '$@i', 'w' . $thumb_width . '.' . $ext, $_l_file);
                $thumb_ok = false;
                foreach ($thumbfiles as $thumbfile) {
                    if (file_exists($dir . '/thumbnails/' . $thumbfile)) {
                        $thumb_ok = true;
                        break;
                    }
                }
                // auto generate thumbnail
                if (!empty($DBInfo->use_convert_thumbs) and !$thumb_ok) {
                    if (!file_exists($dir . "/thumbnails")) {
                        @mkdir($dir . "/thumbnails", 0777);
                    }
                    $fname = $dir . '/' . $_l_file;
                    list($w, $h) = getimagesize($fname);
                    // generate thumbnail using the gd func or the ImageMagick(convert)
                    if ($w > $thumb_width) {
                        require_once 'lib/mediautils.php';
                        resize_image($ext, $fname, $dir . '/thumbnails/' . $thumbfile, $w, $h, $thumb_width);
                        $thumb_ok = true;
                    }
                }
            }
            $alt = !empty($alt) ? $alt : $file;
            if ($key != $pagename || !empty($force_download)) {
                $val = _urlencode($value);
                if ($thumb_ok and !empty($use_thumb)) {
                    if (($p = strrpos($val, '/')) > 0) {
                        $val = substr($val, 0, $p) . '/thumbnails/' . $thumbfile;
                    } else {
                        $val = 'thumbnails/' . $thumbfile;
                    }
                    // use download link ?
                    if (!empty($DBInfo->use_thumb_with_download_link)) {
                        $extra_action = 'download';
                    }
                }
                if ($file_ok == 2 and !empty($pull_url)) {
                    if (isset($subpage[0])) {
                        $pagename = $subpage;
                        $val = _urlencode($file);
                    }
                    $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $pull_url . urlencode(_rawurlencode($pagename)) . "?action={$mydownload}&value=" . $val);
                    if ($use_thumb and isset($thumb['thumb'])) {
                        $url .= '&thumb=' . $thumb['thumb'];
                    }
                } else {
                    $url = $formatter->link_url(_rawurlencode($pagename), "?action={$mydownload}&amp;value=" . $val);
                }
            } else {
                if ($thumb_ok and !empty($use_thumb)) {
                    // FIXME
                    $url = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir . '/thumbnails/' . _urlencode($thumbfile));
                } else {
                    $_my_file = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir . '/' . $file);
                    $url = _urlencode($_my_file);
                }
            }
            if (!empty($options['link_url'])) {
                return qualifiedUrl($url);
            }
            $img = "<img src='{$url}' title='{$alt}' alt='{$alt}' style='border:0' {$attr}/>";
            if ($extra_action) {
                $url = $formatter->link_url(_rawurlencode($pagename), "?action={$extra_action}&amp;value=" . urlencode($value));
                if ($file_ok == 2 and !empty($pull_url)) {
                    if (isset($subpage[0])) {
                        $pagename = $subpage;
                    }
                    $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $pull_url . urlencode(_rawurlencode($pagename)) . "?action={$mydownload}&value=" . $val);
                }
                $img = "<a href='{$url}'>{$img}</a>";
            } else {
                if (preg_match('@^(https?|ftp)://@', $alt)) {
                    $img = "<a href='{$alt}'>{$img}</a>";
                }
            }
            return $bra . $cap_bra . "<div class=\"{$imgcls}\"><div>{$img}{$caption}</div></div>" . $cap_ket . $ket;
            #return $bra.$cap_bra."<span class=\"$cls\">$img$caption</span>".$cap_ket.$ket;
        } else {
            $mydownload = $extra_action ? $extra_action : $mydownload;
            $link = $formatter->link_url(_rawurlencode($pagename), "?action={$mydownload}&amp;value=" . urlencode($value), $text);
            if (!empty($options['link_url'])) {
                return qualifiedUrl($link);
            }
            if (!empty($img_link)) {
                return $bra . "<span class=\"attach\"><a href='{$link}'>{$img_link}</a></span>" . $ket;
            }
            return $bra . "<span class=\"attach\">" . $formatter->icon['attach'] . '<a href="' . $link . '">' . $text . '</a></span>' . $info . $ket;
        }
    }
    // no attached file found.
    if (!empty($options['link_url'])) {
        return 'attachment:' . $value;
    }
    if ($formatter->_macrocache and empty($options['call'])) {
        return $formatter->macro_cache_repl('Attachment', $value);
    }
    if (empty($options['call'])) {
        $formatter->_dynamic_macros['@Attachment'] = 1;
    }
    $paste = '';
    if (!empty($DBInfo->use_clipmacro) and preg_match('/^(.*)\\.png$/i', $file, $m)) {
        $now = time();
        $url = $formatter->link_url($pagename, "?action=clip&amp;value={$m['1']}&amp;now={$now}");
        $paste = " <a href='{$url}'>" . _("or paste a new png picture") . "</a>";
    }
    if (!empty($DBInfo->use_drawmacro) and preg_match('/^(.*)\\.gif$/i', $file, $m)) {
        $now = time();
        $url = $formatter->link_url($pagename, "?action=draw&amp;mode=attach&amp;value={$m['1']}&amp;now={$now}");
        $paste = " <a href='{$url}'>" . _("or draw a new gif picture") . "</a>";
    }
    if ($pagename == $formatter->page->name) {
        return $bra . '<span class="attach">' . $formatter->link_to("?action=UploadFile&amp;rename=" . urlencode($file), sprintf(_("Upload new Attachment \"%s\""), $file)) . $paste . '</span>' . $ket;
    }
    if (!$pagename) {
        $pagename = 'UploadFile';
    }
    return $bra . '<span class="attach">' . $formatter->link_tag($pagename, "?action=UploadFile&amp;rename=" . urlencode($file), sprintf(_("Upload new Attachment \"%s\" on the \"%s\""), $file, $pagename)) . $paste . '</span>' . $ket;
}
Example #19
0
function generate_textInput($formatter)
{
    $url = qualifiedUrl($formatter->link_url("FindPage"));
    return <<<FORM
<textInput>
  <title>Search</title>
  <link>{$url}</link>
  <name>goto</name>
</textInput>

FORM;
}
Example #20
0
function macro_InterWiki($formatter, $value, $options = array())
{
    global $DBInfo;
    while (!isset($DBInfo->interwiki) or !empty($options['init'])) {
        $cf = new Cache_text('settings', array('depth' => 0));
        $force_init = 0;
        if (!empty($DBInfo->shared_intermap) and file_exists($DBInfo->shared_intermap) and $cf->mtime('interwiki') < filemtime($DBInfo->shared_intermap)) {
            $force_init = 1;
        }
        if (empty($formatter->refresh) and $cf->exists('interwiki') and !$force_init) {
            $info = $cf->fetch('interwiki');
            $DBInfo->interwiki = $info['interwiki'];
            $DBInfo->interwikirule = $info['interwikirule'];
            $DBInfo->intericon = $info['intericon'];
            break;
        }
        $interwiki = array();
        # intitialize interwiki map
        $map = file($DBInfo->intermap);
        if (!empty($DBInfo->sistermap) and file_exists($DBInfo->sistermap)) {
            $map = array_merge($map, file($DBInfo->sistermap));
        }
        # read shared intermap
        if (file_exists($DBInfo->shared_intermap)) {
            $map = array_merge($map, file($DBInfo->shared_intermap));
        }
        $interwikirule = '';
        for ($i = 0, $sz = sizeof($map); $i < $sz; $i++) {
            $line = rtrim($map[$i]);
            if (!$line || $line[0] == "#" || $line[0] == " ") {
                continue;
            }
            if (preg_match("/^[A-Z]+/", $line)) {
                $wiki = strtok($line, ' ');
                $url = strtok(' ');
                $dumm = trim(strtok(''));
                if (preg_match('/^(http|ftp|attachment):/', $dumm, $match)) {
                    $icon = strtok($dumm, ' ');
                    if ($icon[0] == 'a') {
                        $url = $formatter->macro_repl('Attachment', substr($icon, 11), 1);
                        $icon = qualifiedUrl($DBInfo->url_prefix . '/' . $url);
                    }
                    preg_match('/^(\\d+)(x(\\d+))?\\b/', strtok(''), $msz);
                    $sx = $msz[1];
                    $sy = $msz[3];
                    $sx = $sx ? $sx : 16;
                    $sy = $sy ? $sy : 16;
                    $intericon[$wiki] = array($sx, $sy, trim($icon));
                }
                $interwiki[$wiki] = trim($url);
                $interwikirule .= "{$wiki}|";
            }
        }
        $interwikirule .= "Self";
        $interwiki['Self'] = get_scriptname() . $DBInfo->query_prefix;
        # set default TwinPages interwiki
        if (empty($interwiki['TwinPages'])) {
            $interwiki['TwinPages'] = ($DBInfo->query_prefix == '?' ? '&amp;' : '?') . 'action=twinpages&amp;value=';
        }
        # read shared intericons
        $map = array();
        if (!empty($DBInfo->shared_intericon) and file_exists($DBInfo->shared_intericon)) {
            $map = array_merge($map, file($DBInfo->shared_intericon));
        }
        $intericon = array();
        for ($i = 0, $isz = sizeof($map); $i < $isz; $i++) {
            $line = rtrim($map[$i]);
            if (!$line || $line[0] == "#" || $line[0] == " ") {
                continue;
            }
            if (preg_match("/^[A-Z]+/", $line)) {
                $wiki = strtok($line, ' ');
                $icon = trim(strtok(' '));
                if (!preg_match('/^(http|ftp|attachment):/', $icon, $match)) {
                    continue;
                }
                preg_match('/^(\\d+)(x(\\d+))?\\b/', strtok(''), $sz);
                $sx = $sz[1];
                $sy = $sz[3];
                $sx = $sx ? $sx : 16;
                $sy = $sy ? $sy : 16;
                if ($icon[0] == 'a') {
                    $url = $formatter->macro_repl('Attachment', substr($icon, 11), 1);
                    $icon = qualifiedUrl($DBInfo->url_prefix . '/' . $url);
                }
                $intericon[$wiki] = array($sx, $sy, trim($icon));
            }
        }
        $DBInfo->interwiki = $interwiki;
        $DBInfo->interwikirule = $interwikirule;
        $DBInfo->intericon = $intericon;
        $interinfo = array('interwiki' => $interwiki, 'interwikirule' => $interwikirule, 'intericon' => $intericon);
        $cf->update('interwiki', $interinfo);
        break;
    }
    if (!empty($options['init'])) {
        return;
    }
    $out = "<table border='0' cellspacing='2' cellpadding='0'>";
    foreach (array_keys($DBInfo->interwiki) as $wiki) {
        $href = $DBInfo->interwiki[$wiki];
        if (strpos($href, '$PAGE') === false) {
            $url = $href . 'RecentChanges';
        } else {
            $url = str_replace('$PAGE', 'index', $href);
            #$href=$url;
        }
        $icon = $DBInfo->imgs_url_interwiki . strtolower($wiki) . '-16.png';
        $sx = 16;
        $sy = 16;
        if (!empty($DBInfo->intericon[$wiki])) {
            $icon = $DBInfo->intericon[$wiki][2];
            $sx = $DBInfo->intericon[$wiki][0];
            $sy = $DBInfo->intericon[$wiki][1];
        }
        $out .= "<tr><td><tt><img src='{$icon}' width='{$sx}' height='{$sy}' " . "class='interwiki' alt='{$wiki}:' /><a href='{$url}'>{$wiki}</a></tt></td>";
        $out .= "<td><tt><a href='{$href}'>{$href}</a></tt></td></tr>\n";
    }
    $out .= "</table>\n";
    return $out;
}
Example #21
0
function macro_SWFUpload($formatter, $value, $opts = array())
{
    global $DBInfo;
    $swf_ver = 10;
    if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
        $depth = $DBInfo->swfupload_depth;
    } else {
        $depth = 2;
    }
    if (session_id() == '') {
        // ip based
        $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI');
        // FIXME
    } else {
        if (!empty($_SESSION['_swfupload'])) {
            $myid = $_SESSION['_swfupload'];
        } else {
            $myid = session_id();
            $_SESSION['_swfupload'] = $myid;
        }
    }
    $prefix = substr($myid, 0, $depth);
    $mysubdir = $prefix . '/' . $myid . '/';
    $myoptions = "<input type='hidden' name='mysubdir' value='{$mysubdir}' />";
    if (!empty($DBInfo->use_lightbox)) {
        $myoptions .= "\n<input type='hidden' name='use_lightbox' value='1' />";
    } else {
        $myoptions .= "\n<input type='hidden' name='use_lightbox' value='0' />";
    }
    $jsPreview = '';
    if (!empty($formatter->preview)) {
        $js_tag = 1;
        $jsPreview = ' class="previewTag"';
        $uploader = 'UploadForm';
    } else {
        if (!empty($options['preview'])) {
            $jsPreview = ' class="previewTag"';
        }
    }
    $default_allowed = '*.gif;*.jpg;*.png;*.psd';
    $allowed = $default_allowed;
    if (!empty($DBInfo->pds_allowed)) {
        $allowed = '*.' . str_replace('|', ';*.', $DBInfo->pds_allowed);
    }
    $swfupload_num = !empty($GLOBALS['swfupload_num']) ? $GLOBALS['swfupload_num'] : 0;
    // get already uploaded files list
    $uploaded = '';
    if (is_dir($DBInfo->upload_dir . '/.swfupload/' . $mysubdir)) {
        $mydir = $DBInfo->upload_dir . '/.swfupload/' . $mysubdir . '/';
        $handle = @opendir($mydir);
        if ($handle) {
            $files = array();
            while ($file = readdir($handle)) {
                if (is_dir($mydir . $file) or $file[0] == '.') {
                    continue;
                }
                $files[] = $file;
            }
            closedir($handle);
            foreach ($files as $f) {
                $uploaded .= "<li id='{$f}'><input checked=\"checked\" type=\"checkbox\">" . "<a href='javascript:showImgPreview(\"{$f}\")'>{$f}</a></li>";
            }
        }
    }
    //
    // check already uploaed files
    //
    if (1) {
        $value = $formatter->page->urlname;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        $mydir = $DBInfo->upload_dir . "/{$key}";
        // support hashed upload dir
        if (!is_dir($mydir) and !empty($DBInfo->use_hashed_upload_dir)) {
            $prefix = get_hashed_prefix($key);
            $mydir = $DBInfo->upload_dir . '/' . $prefix . $key;
        }
        $handle = @opendir($mydir);
        if ($handle) {
            $files = array();
            while ($file = readdir($handle)) {
                if (is_dir($mydir . $file) or $file[0] == '.') {
                    continue;
                }
                $files[] = $file;
            }
            closedir($handle);
            foreach ($files as $f) {
                $uploaded .= "<li><input checked=\"checked\" disabled=\"disabled\" type=\"checkbox\">" . "<a href='javascript:showImgPreview(\"{$f}\",true)'>{$f}</a></li>";
            }
        }
    }
    if (empty($swfupload_num)) {
        if ($swf_ver == 9) {
            $formatter->register_javascripts(array('js/swfobject.js', 'SWFUpload/mmSWFUpload.js', 'SWFUpload/preview.js', 'SWFUpload/moni.js'));
        } else {
            $formatter->register_javascripts(array('js/swfobject.js', 'SWFUpload/swfupload.js', 'SWFUpload/swfupload.swfobject.js', 'SWFUpload/swfupload.queue.js', 'SWFUpload/preview.js', 'SWFUpload/handlers.js'));
        }
    }
    $swf_css = <<<CSS
<style type="text/css">
@import url("{$DBInfo->url_prefix}/local/SWFUpload/swfupload.css");
</style>
CSS;
    $btn = _("Files...");
    $btn2 = _("Upload files");
    $btn3 = _("Cancel All files");
    $prefix = qualifiedUrl($DBInfo->url_prefix . '/local');
    $action = $formatter->link_url($formatter->page->urlname);
    $action2 = $action . '----swfupload';
    if ($mysubdir) {
        $action2 .= '----' . $mysubdir;
    }
    $action2 = qualifiedUrl($action2);
    $myprefix = qualifiedUrl($DBInfo->url_prefix);
    $swfupload_script = '';
    if ($swf_ver == 9) {
        $swf_js = <<<EOF
        <script type="text/javascript">
        /*<![CDATA[*/
\t\tmmSWFUpload.init({
\t\t\t//debug : true,
\t\t\tupload_backend : "{$action2}",
\t\t\ttarget : "SWFUpload",
\t\t\t// cssClass : "myCustomClass",
\t\t\t_prefix : "{$myprefix}",
\t\t\tallowed_filesize : "40000",
\t\t\tallowed_filetypes : "{$allowed}",
\t\t\tupload_start_callback : 'uploadStart',
\t\t\tupload_progress_callback : 'uploadProgress',
\t\t\tupload_complete_callback : 'uploadComplete',
\t\t\t// upload_error_callback : 'uploadError',
                        upload_cancel_callback : 'uploadCancel'
                });
        /*]]>*/
\t</script>
EOF;
        $submit_btn = "<input type='button' value='{$btn}' onclick='javascript:mmSWFUpload.callSWF();' />\n";
        $cancel_btn = '';
    } else {
        $submit_btn = '<span id="spanButtonPlaceHolder"><input type="file" name="upload" /></span>';
        $cancel_btn = "<button id='btnCancel' onclick='swfu.cancelQueue();' disabled='disabled' ><span>" . $btn3 . "</span></button>\n";
        $swf_js = <<<EOF
<script type="text/javascript">
/*<![CDATA[*/
var swfu;

SWFUpload.onload = function () {
    var settings = {
        flash_url : "{$DBInfo->url_prefix}/local/SWFUpload/swfupload.swf",
        upload_url: "{$action2}", // Relative to the SWF file
        file_size_limit : "10 MB",
        file_types : "{$allowed}",
        file_types_description : "Files",
        file_upload_limit : 100,
        file_queue_limit : 0,
        custom_settings : {
            progressTarget : "fsUploadProgress",
            cancelButtonId : "btnCancel"
        },
        debug: false, // true

        // Button Settings
        button_image_url : "{$DBInfo->url_prefix}/local/SWFUpload/images/btn0.png",
        button_text : '<span class="button" style="text-align:center">{$btn}</span>',
        button_text_style : '.button {font-family:Gulim,Sans-serif;text-align:center;}',
        button_text_top_padding : 3,
        button_placeholder_id : "spanButtonPlaceHolder",
        button_width: 61,
        button_height: 22,
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_cursor: SWFUpload.CURSOR.HAND,

        // The event handler functions are defined in handlers.js
        swfupload_loaded_handler : swfUploadLoaded,
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        queue_complete_handler : queueComplete, // Queue plugin event
        
        // SWFObject settings
        minimum_flash_version : "9.0.28",
        swfupload_pre_load_handler : swfUploadPreLoad,
        swfupload_load_failed_handler : swfUploadLoadFailed
    };

    swfu = new SWFUpload(settings);
}
/*]]>*/
</script>

EOF;
    }
    $form = <<<EOF
\t<div id="SWFUpload" style='display:none'>
\t\t<form action="" onsubmit="return false;">
\t\t\t<input type="file" name="upload" />
\t\t\t<input type="submit" value="Upload" onclick="javascript:alert('disabled...'); return false;" />
\t\t</form>
\t</div>
{$swf_js}
\t<div class="fileList">
\t<table border='0' cellpadding='0'>
\t<tr>
\t<td>
\t<div id="previewAlign">
\t</div>
\t<div id="filePreview"{$jsPreview}>
\t</div>
\t</td>
\t<td>

\t<div id="filesDisplay">
            <form id="form1" target='_blanl' action="{$action}" method="POST" enctype="multipart/form-data">
\t        <ul id="mmUploadFileListing">{$uploaded}</ul>
\t\t<span id="fileButton">
                <input type='hidden' name='action' value='swfupload' />
                <input type='hidden' name='value' value='{$mysubdir}' />
                <input type='hidden' name='popup' value='1' />
                {$myoptions}
                {$submit_btn}
\t\t<button type='submit' onclick='javascript:fileSubmit(this);' ><span>{$btn2}</span></button>
                {$cancel_btn}
\t\t</span>
            </form>
        </div>
        <noscript style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px;">
            We're sorry.  SWFUpload could not load.  You must have JavaScript enabled to enjoy SWFUpload.
        </noscript>
        <div id="divLoadingContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            SWFUpload is loading. Please wait a moment...
        </div>
        <div id="divLongLoading" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            SWFUpload is taking a long time to load or the load has failed.  Please make sure that the Flash Plugin is enabled and that a working version of the Adobe Flash Player is installed.
        </div>
        <div id="divAlternateContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">

            We're sorry.  SWFUpload could not load.  You may need to install or upgrade Flash Player.
            Visit the <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe website</a> to get the Flash Player.
        </div>

\t</td>
        </tr>
\t<tr>
\t<td colspan='2'>
\t\t<div id="fileProgressInfo"></div>
\t</td>
\t</tr>
\t</table>
\t</div>
EOF;
    return $swfupload_script . $swf_css . $form;
}
Example #22
0
function do_trackback($formatter, $options)
{
    global $DBInfo, $_release;
    $entry = '';
    if (!$formatter->page->exists()) {
        $pos = strrpos($formatter->page->name, '/');
        if ($pos > 0) {
            $entry = substr($formatter->page->name, $pos + 1);
            $pagename = substr($formatter->page->name, 0, $pos);
            $page = new WikiPage($pagename);
            $formatter = new Formatter($page, $options);
            $options['page'] = $pagename;
        } else {
            $options['msg'] = _("Error: Page Not found !");
            send_error(1, $options['msg']);
        }
    }
    if (empty($options['url'])) {
        $anchor = '';
        if ($options['value']) {
            $anchor = '/' . $options['value'];
        }
        $formatter->send_header("", $options);
        if ($DBInfo->use_trackback) {
            $ping_url = qualifiedUrl($formatter->link_url($formatter->page->urlname . $anchor, "?action=trackback"));
        } else {
            $ping_url = _("TrackBack is not activated !");
        }
        $sendping_action = $formatter->link_tag($formatter->page->urlname, "?action=sendping&amp;value={$options['value']}", _("send ping"));
        $tb_cache = new Cache_text('trackback');
        if ($tb_cache->exists($options['page'])) {
            $formatter->send_title(sprintf(_("TrackBack list of %s"), $options['page']), "", $options);
            $trackbacks = explode("\n", $tb_cache->fetch($options['page']));
            unset($trackbacks[sizeof($trackbacks) - 1]);
            # trim the last empty line
            print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n";
            print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n<br />";
            foreach ($trackbacks as $trackback) {
                list($dummy, $entry, $url, $date, $sitename, $title, $excerpt) = explode("\t", $trackback);
                if ($anchor and '/' . $entry != $anchor) {
                    continue;
                }
                $date[10] = " ";
                # 2003-07-11T12:08:33+09:00
                # $time=strtotime($date);
                $time = strtotime($date);
                $date = date("@ m-d [h:i a]", $time);
                print "<div class='blog'>\n";
                print "<div class='blog-title'><a href='{$url}'>{$title}</a></div>\n";
                print "<div class='blog-user'>Submitted by <a href='{$url}'>{$sitename}</a> {$date}</div>\n";
                print "<div class='blog-comment'>{$excerpt}</div>\n</div><br />\n";
            }
        } else {
            $formatter->send_title(sprintf(_("No TrackBack entry found for %s"), $options['page']), "", $options);
            print "<div class='trackback-hint'><b>" . _("TrackBack URL for this page:") . "</b><br />\n{$ping_url}<br /><br />\n";
            print "<b>" . _("Send TrackBack Ping to another Blog:") . "</b> {$sendping_action}</div>\n";
        }
        $formatter->send_footer("", $options);
        return;
    }
    if (!$DBInfo->use_trackback) {
        send_error(1, "TrackBack is not enabled");
    }
    if (empty($options['title']) or empty($options['excerpt']) or empty($options['blog_name']) or empty($options['url'])) {
        send_error(1, "Invalid TrackBack Ping");
    }
    # receivie Trackback ping
    # strip \n
    $title = strtr(_stripslashes($options['title']), "\t\n", " \r");
    $excerpt = strtr(_stripslashes($options['excerpt']), "\t\n", " \r");
    $blog_name = strtr(_stripslashes($options['blog_name']), "\t\n", " \r");
    $url = strtr(_stripslashes($options['url']), "\t\n", " \r");
    $timestamp = time();
    $date = gmdate("Y-m-d\\TH:i:s", $timestamp);
    $receive = $timestamp . "\t" . $entry . "\t" . $url . "\t" . $date . "\t" . $blog_name . "\t" . $title . "\t" . $excerpt . "\n";
    $tb_cache = new Cache_text('trackback');
    $old = $tb_cache->fetch($options['page']);
    $ret = $tb_cache->update($options['page'], $old . $receive, time());
    if ($ret === false) {
        send_error(0, "Can't update Trackback list. Please try again");
    }
    send_error(0, 'Successfully added');
}
Example #23
0
function macro_ISBN($formatter, $value = "")
{
    global $DBInfo;
    // http://www.isbn-international.org/en/identifiers/allidentifiers.html
    $default_map = array('89' => 'Aladdin');
    $ISBN_MAP = "IsbnMap";
    $DEFAULT = <<<EOS
Amazon http://www.amazon.com/exec/obidos/ISBN= http://images.amazon.com/images/P/\$ISBN.01.MZZZZZZZ.gif
Aladdin http://www.aladdin.co.kr/shop/wproduct.aspx?ISBN= http://image.aladdin.co.kr/cover/cover/\$ISBN_1.gif @(http://image\\..*/cover/(?:[^\\s_/]*\$ISBN_\\d\\.(?:jpe?g|gif)))@
Gang http://kangcom.com/common/qsearch/search.asp?s_flag=T&s_text= http://kangcom.com/l_pic/\$ISBN.jpg @bookinfo\\.asp\\?sku=(\\d+)"@

EOS;
    $DEFAULT_ISBN = "Amazon";
    $re_isbn = "/^([0-9\\-]+[xX]?)(?:,\\s*)?(([A-Z][A-Za-z]*)?(?:,)?(.*))?/x";
    if ($value != '') {
        $test = preg_match($re_isbn, $value, $match);
        if ($test === false) {
            return "<p><strong class=\"error\">Invalid ISBN \"%value\"</strong></p>";
        }
    }
    $list = $DEFAULT;
    $map = new WikiPage($ISBN_MAP);
    if ($map->exists()) {
        $list .= $map->get_raw_body();
    }
    $lists = explode("\n", $list);
    $ISBN_list = array();
    foreach ($lists as $line) {
        if (!$line or !preg_match("/^[A-Z]/", $line[0])) {
            continue;
        }
        $dum = explode(" ", rtrim($line));
        $re = '';
        $sz = sizeof($dum);
        if (!preg_match('/^(http|ftp)/', $dum[1])) {
            continue;
        }
        if ($sz == 2) {
            $dum[] = $ISBN_list[$DEFAULT_ISBN][1];
        } else {
            if ($sz != 3) {
                if ($sz == 4) {
                    if (($p = strpos(substr($dum[3], 1), $dum[3][0])) !== false) {
                        $retest = substr($dum[3], 0, $p + 2);
                    } else {
                        $retest = $dum[3];
                    }
                    if (preg_match($retest, '') !== false) {
                        $re = $dum[3];
                    }
                } else {
                    continue;
                }
            }
        }
        $ISBN_list[$dum[0]] = array($dum[1], $dum[2], $re);
    }
    if ($value == '') {
        $out = "<ul>";
        foreach ($ISBN_list as $interwiki => $v) {
            $href = $ISBN_list[$interwiki][0];
            if (strpos($href, '$ISBN') === false) {
                $url = $href . '0738206679';
            } else {
                $url = str_replace('$ISBN', '0738206679', $href);
            }
            $icon = $DBInfo->imgs_url_interwiki . strtolower($interwiki) . '-16.png';
            $sx = 16;
            $sy = 16;
            if ($DBInfo->intericon[$interwiki]) {
                $icon = $DBInfo->intericon[$interwiki][2];
                $sx = $DBInfo->intericon[$interwiki][0];
                $sy = $DBInfo->intericon[$interwiki][1];
            }
            $out .= "<li><img src='{$icon}' width='{$sx}' height='{$sy}' " . "align='middle' alt='{$interwiki}:' /><a href='{$url}'>{$interwiki}</a>: " . "<tt class='link'>{$href}</tt></li>";
        }
        $out .= "</ul>\n";
        return $out;
    }
    $isbn2 = $match[1];
    $isbn = str_replace('-', '', $isbn2);
    #print_r($match);
    if ($match[3]) {
        if (strtolower($match[2][0]) == 'k') {
            $lang = 'Aladdin';
        } else {
            $lang = $match[3];
        }
    } else {
        $cl = strlen($isbn);
        if ($cl == 13) {
            $lang_code = substr($isbn, 3, 2);
        } else {
            $lang_code = substr($isbn, 0, 2);
        }
        // 89
        if (!empty($default_map[$lang_code])) {
            $lang = $default_map[$lang_code];
        } else {
            $lang = $DEFAULT_ISBN;
        }
    }
    $attr = '';
    $ext = '';
    if ($match[2]) {
        $args = explode(',', $match[2]);
        foreach ($args as $arg) {
            $arg = trim($arg);
            if ($arg == 'noimg') {
                $noimg = 1;
            } else {
                if (strtolower($arg) == 'k') {
                    $lang = 'Aladdin';
                } else {
                    $name = strtok($arg, '=');
                    $val = strtok(' ');
                    if ($val) {
                        $attr .= $name . '="' . $val . '" ';
                    }
                    #XXX
                    if ($name == 'align') {
                        $attr .= 'class="img' . ucfirst($val) . '" ';
                    }
                    if ($name == 'img') {
                        $ext = $val;
                    }
                }
            }
        }
    }
    if ($ISBN_list[$lang]) {
        $booklink = $ISBN_list[$lang][0];
        $imglink = $ISBN_list[$lang][1];
        $imgre = $ISBN_list[$lang][2];
    } else {
        $booklink = $ISBN_list[$DEFAULT_ISBN][0];
        $imglink = $ISBN_list[$DEFAULT_ISBN][1];
    }
    if (strpos($booklink, '$ISBN') === false) {
        $booklink .= $isbn;
    } else {
        if (strpos($booklink, '$ISBN2') === false) {
            $booklink = str_replace('$ISBN', $isbn, $booklink);
        } else {
            $booklink = str_replace('$ISBN2', $isbn2, $booklink);
        }
    }
    if (empty($noimg) and $imgre and get_cfg_var('allow_url_fopen')) {
        if (($p = strpos(substr($imgre, 1), $imgre[0])) !== false) {
            $imgrepl = substr($imgre, $p + 2);
            $imgre = substr($imgre, 0, $p + 2);
            if ($imgrepl == '@') {
                $imgrepl = '';
            }
            $imgre = str_replace('$ISBN', $isbn, $imgre);
        }
        $md5sum = md5($booklink);
        // check cache
        $bcache = new Cache_text('isbn');
        if (empty($formatter->refresh) and $bcache->exists($md5sum)) {
            $imgname = trim($bcache->fetch($md5sum));
            $fetch_ok = 1;
        } else {
            // fetch the bookinfo page and grep the imagname of the book.
            $fd = fopen($booklink, 'r');
            if (is_resource($fd)) {
                while (!feof($fd)) {
                    $line = fgets($fd, 1024);
                    preg_match($imgre, $line, $match);
                    if (!empty($match[1])) {
                        $bcache->update($md5sum, $match[1]);
                        $imgname = $match[1];
                        $fetch_ok = 1;
                        break;
                    }
                }
                fclose($fd);
            }
        }
        if ($fetch_ok) {
            if ($imgrepl) {
                $imglink = preg_replace('@' . $imgrepl . '@', $imgname, $imglink);
            } else {
                if (!preg_match('/^https?:/', $imgname)) {
                    $imglink = str_replace('$ISBN', $imgname, $imglink);
                } else {
                    $imglink = $imgname;
                }
            }
        }
        if (!empty($fetch_ok) and !empty($DBInfo->isbn_img_download)) {
            # some sites such as the IMDB check the referer and
            # do not permit to show any of its images
            # the $isbn_img_download option is needed to show such images
            preg_match('/^(.*)\\.(jpeg|jpg|gif|png)$/i', $imglink, $m);
            if (!empty($m[1]) and isset($m[2])) {
                $myimglink = md5($m[1]) . '.' . $m[2];
            }
            if (isset($m[2])) {
                # skip XXX
            } else {
                if (file_exists($DBInfo->upload_dir . '/isbn/' . $myimglink)) {
                    $mlink = $formatter->macro_repl('attachment', 'isbn:' . $myimglink, 1);
                    $imglink = qualifiedUrl($DBInfo->url_prefix . '/' . $mlink);
                } else {
                    $fd = fopen($imglink, 'r');
                    if (is_resource($fd)) {
                        $myimg = '';
                        while (!feof($fd)) {
                            $myimg .= fread($fd, 1024);
                        }
                        fclose($fd);
                        if (!is_dir($DBInfo->upload_dir . '/isbn/')) {
                            umask(00);
                            mkdir($DBInfo->upload_dir . '/isbn/', 0777);
                            umask($DBInfo->umask);
                        }
                        $fd = fopen($DBInfo->upload_dir . '/isbn/' . $myimglink, 'w');
                        if (is_resource($fd)) {
                            fwrite($fd, $myimg);
                            fclose($fd);
                        }
                    }
                }
            }
        }
    }
    if (empty($fetch_ok)) {
        if (strpos($imglink, '$ISBN') === false) {
            $imglink .= $isbn;
        } else {
            if (strpos($imglink, '$ISBN2') === false) {
                $imglink = str_replace('$ISBN', $isbn, $imglink);
            } else {
                $imglink = str_replace('$ISBN2', $isbn2, $imglink);
            }
            if ($ext) {
                $imglink = preg_replace('/\\.(gif|jpeg|jpg|png|bmp)$/i', $ext, $imglink);
            }
        }
    }
    if (!empty($noimg)) {
        $icon = $DBInfo->imgs_url_interwiki . strtolower($lang) . '-16.png';
        $sx = 16;
        $sy = 16;
        if (!empty($DBInfo->intericon[$lang])) {
            $icon = $DBInfo->intericon[$lang][2];
            $sx = $DBInfo->intericon[$lang][0];
            $sy = $DBInfo->intericon[$lang][1];
        }
        return "<img src='{$icon}' alt='{$lang}:' align='middle' width='{$sx}' height='{$sy}' title='{$lang}' />" . "[<a href='{$booklink}'>ISBN-{$isbn2}</a>]";
    } else {
        return "<a href='{$booklink}'><img src='{$imglink}' border='1' title='{$lang}" . ":ISBN-{$isbn}' alt='[ISBN-{$isbn2}]' class='isbn' {$attr} /></a>";
    }
}
Example #24
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 #25
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 #26
0
function _parse_rlog($formatter, $log, $options = array())
{
    global $DBInfo;
    $tz_offset = $formatter->tz_offset;
    if (!empty($DBInfo->wikimasters) and is_array($DBInfo->wikimasters) and in_array($options['id'], $DBInfo->wikimasters)) {
        $admin = 1;
    }
    if (!empty($options['info_actions'])) {
        $actions = $options['info_actions'];
    } else {
        if (isset($DBInfo->info_actions)) {
            $actions = $DBInfo->info_actions;
        } else {
            $actions = array('recall' => 'view', 'raw' => 'source', 'diff' => 'diff');
        }
    }
    if (!$formatter->page->exists() && !in_array('revert', $actions)) {
        $actions['revert'] = 'revert';
    }
    if (!empty($DBInfo->use_avatar)) {
        if (is_string($DBInfo->use_avatar)) {
            $type = $DBInfo->use_avatar;
        } else {
            $type = 'identicon';
        }
        $avatarlink = qualifiedUrl($formatter->link_url('', '?action=' . $type . '&amp;seed='));
    }
    $ipicon = '<img src="' . $DBInfo->imgs_dir . '/misc/ip.png" />';
    $members = $DBInfo->members;
    // do not check admin member users
    $user = $DBInfo->user;
    $ismember = $user->is_member;
    $diff_action = null;
    if (isset($actions['diff'])) {
        $diff_action = _($actions['diff']);
        unset($actions['diff']);
    }
    $state = 0;
    $flag = 0;
    $time_current = time();
    $simple = !empty($options['simple']) ? 1 : 0;
    $url = $formatter->link_url($formatter->page->urlname);
    $diff_btn = _("Compare");
    $out = "<div class='wikiInfo'>\n";
    if (!empty($options['title'])) {
        $out .= $options['title'];
    } else {
        $out .= "<h2>" . _("Revision History") . "</h2>\n";
    }
    $out .= "<form id='infoform' method='get' action='{$url}'>";
    $out .= "<div><table class='info'><thead><tr>\n";
    $out .= "<th>" . _("Ver.") . "</th><th>" . _("Date") . "</th>" . "<th>" . _("Changes") . "</th>" . "<th>" . _("Editor") . "</th>" . "<th><button type='submit'><span>{$diff_btn}</span></button></th>\n";
    if (!$simple) {
        if (!empty($actions)) {
            $out .= "<th>" . _("View") . "</th>";
        }
        if (isset($admin)) {
            $out .= "<th>" . _("admin.") . "</th>";
        }
    }
    $out .= "</tr>\n</thead>\n";
    $out .= "<tbody>\n";
    $users = array();
    $rr = 0;
    #foreach ($lines as $line) {
    $count = 0;
    $showcount = (!empty($options['count']) and $options['count'] > 5) ? $options['count'] : 10;
    $line = '';
    $ok = 0;
    $log .= "\n";
    // hack
    $ii = 0;
    for (; !empty($line) or !empty($log); list($line, $log) = explode("\n", $log, 2)) {
        if (!$state) {
            if (!preg_match("/^---/", $line)) {
                continue;
            } else {
                $state = 1;
                continue;
            }
        }
        if ($state == 1 and $ok == 1) {
            if (!empty($options['action'])) {
                $act = $options['action'];
            } else {
                $act = 'info';
            }
            $lnk = $formatter->link_to('?action=' . $act . '&amp;rev=' . $rev, _("Show next revisions"), ' class="button small"');
            $out .= '<tr><td colspan="2"></td><td colspan="' . (!empty($admin) ? 5 : 4) . '">' . $lnk . '</td></tr>';
            break;
        }
        switch ($state) {
            case 1:
                $rr++;
                preg_match("/^revision ([0-9a-f\\.]+)\\s*/", $line, $match);
                $rev = $match[1];
                if (isset($match[2]) and preg_match("/\\./", $match[2])) {
                    $state = 0;
                    break;
                }
                $state = 2;
                break;
            case 2:
                $change = '';
                $inf = preg_replace("/date:\\s([0-9\\/:\\s]+)(;\\s+author:.*;\\s+state:.*;)?/", "\\1", $line);
                if (strstr($inf, 'lines:') !== FALSE) {
                    list($inf, $change) = explode('lines:', $inf, 2);
                }
                if (!empty($options['ago'])) {
                    if (preg_match('/^[0-9]+$/', $inf)) {
                        $rrev = '#' . $rr;
                        $ed_time = $inf;
                        $inf = gmdate("Y-m-d H:i:s", $ed_time + $tz_offset);
                    } else {
                        $ed_time = strtotime($inf . ' GMT');
                    }
                    $time_diff = (int) ($time_current - $ed_time) / 60;
                    if ($time_diff > 1440 * 31) {
                        $inf = gmdate("Y-m-d H:i:s", strtotime($inf . ' GMT') + $tz_offset);
                    } else {
                        if (($time_diff = $time_diff / 60) > 24) {
                            $day = (int) ($time_diff / 24);
                            if ($day == 1) {
                                $inf = _("Yesterday");
                            } else {
                                $inf = sprintf(_("%s days ago"), (int) ($time_diff / 24));
                            }
                        } else {
                            if ($time_diff > 1) {
                                $inf = sprintf(_("%s hours ago"), (int) $time_diff);
                            } else {
                                $inf = sprintf(_("%s min ago"), $time_diff % 60);
                            }
                        }
                    }
                } else {
                    if (preg_match('/^[0-9]+$/', $inf)) {
                        $rrev = '#' . $rr;
                        $ed_time = $inf;
                        $inf = gmdate("Y-m-d H:i:s", $inf + $tz_offset);
                    } else {
                        if ($tz_offset != '') {
                            $inf = gmdate("Y-m-d H:i:s", strtotime($inf . ' GMT') + $tz_offset);
                        } else {
                            $inf = date("Y-m-d H:i:s", strtotime($inf));
                        }
                        // localtime
                    }
                }
                $inf = $formatter->link_to("?action=recall&rev={$rev}", $inf);
                $change = preg_replace("/\\+(\\d+)\\s\\-(\\d+)/", "<span class='diff-added'><span>+\\1</span></span><span class='diff-removed'><span>-\\2</span></span>", $change);
                $state = 3;
                break;
            case 3:
                $dummy = explode(';;', $line, 3);
                $ip = $dummy[0];
                $realip = $lastip = $ip;
                if (($p = strpos($ip, ',')) !== false) {
                    // IP addresses via proxies
                    $realip = substr($ip, 0, $p);
                    $tmp = explode(',', $ip);
                    $lastip = $ip = array_pop($tmp);
                }
                $user = trim($dummy[1]);
                if (($p = strpos($user, ' ')) !== false) {
                    // XXX
                    $user = substr($user, 0, $p);
                } else {
                    if (substr($user, 0, 9) == 'Anonymous') {
                        $user = '******';
                    }
                }
                if (!empty($DBInfo->use_avatar)) {
                    $crypted = crypt($ip, $ip);
                    $mylnk = preg_replace('/seed=/', 'seed=' . $crypted, $avatarlink);
                    $avatar = '<img src="' . $mylnk . '" style="width:16px;height:16px;vertical-align:middle" alt="avatar" />';
                } else {
                    $avatar = '';
                }
                if ($user and $user != 'Anonymous') {
                    if (array_key_exists($user, $users)) {
                        $ip = $users[$user];
                    } else {
                        if (!empty($DBInfo->use_nick)) {
                            $u = $DBInfo->udb->getUser($user);
                            if (!empty($u->info['nick'])) {
                                if ($DBInfo->interwiki['User']) {
                                    $ip = $formatter->link_repl('[wiki:User:'******' ' . $u->info['nick'] . ']');
                                } else {
                                    if (!empty($u->info['home'])) {
                                        $ip = $formatter->link_repl('[' . $u->info['home'] . ' ' . $u->info['nick'] . ']');
                                    } else {
                                        $ip = $formatter->link_repl('[wiki:' . $user . ' ' . $u->info['nick'] . ']');
                                    }
                                }
                            }
                            $ip = $avatar . $ip;
                            $users[$user] = $ip;
                        } else {
                            if (strpos($user, ' ') !== false) {
                                $ip = $avatar . $formatter->link_repl($user);
                                $users[$user] = $ip;
                            } else {
                                if (empty($DBInfo->no_wikihomepage)) {
                                    if (empty($DBInfo->use_hostname) or $DBInfo->hasPage($user)) {
                                        $ip = $avatar . $formatter->link_tag($user);
                                    } else {
                                        $ip = $avatar . $user;
                                    }
                                    $users[$user] = $ip;
                                }
                            }
                        }
                    }
                }
                if (empty($users[$user])) {
                    $rip = $ip;
                    $u = $user;
                    if ($u == 'Anonymous') {
                        $u = $ip;
                    }
                    if (isset($DBInfo->interwiki['Whois'])) {
                        $wip = "<a href='" . $DBInfo->interwiki['Whois'] . "{$ip}' target='_blank'>{$ipicon}</a>";
                    } else {
                        $wip = "<a href='?action=whois&amp;q=" . $ip . "' target='_blank'>{$ipicon}</a>";
                    }
                    if ($ismember) {
                        if (!empty($DBInfo->use_admin_user_url)) {
                            $u = '<a href="' . $DBInfo->use_admin_user_url . $u . '">' . $u . '</a>';
                        }
                        if (!in_array($user, $members)) {
                            $ip = $u . $wip;
                        } else {
                            $ip = $u;
                        }
                    } else {
                        if (empty($DBInfo->show_hosts)) {
                            $ip = $user;
                        } else {
                            if (!empty($DBInfo->mask_hostname)) {
                                if ($user == 'Anonymous') {
                                    $ip = _mask_hostname($ip);
                                } else {
                                    $ip = $user;
                                }
                            } else {
                                if (!empty($members) and in_array($u, $members)) {
                                    $ip = $user;
                                } else {
                                    if (!empty($avatar)) {
                                        if ($user == 'Anonymous') {
                                            $u = _($user);
                                        }
                                        $ip = $u;
                                    } else {
                                        $ip = $u . $wip;
                                    }
                                }
                            }
                        }
                    }
                    $ip = $avatar . $ip;
                    if ($user != 'Anonymous') {
                        $users[$user] = $ip;
                    } else {
                        $users[$rip] = $ip;
                    }
                }
                $comment = !empty($dummy[2]) ? _stripslashes($dummy[2]) : '';
                if ($realip != $lastip) {
                    $via = '<span class="via-proxy">' . $realip . '</span>';
                    $comment = isset($comment[0]) ? $via . ' ' . $comment : $via;
                }
                $state = 4;
                break;
            case 4:
                if (!$rev) {
                    break;
                }
                $rowspan = 1;
                if (!$simple and $comment) {
                    $rowspan = 2;
                }
                $rrev = !empty($rrev) ? $rrev : $formatter->link_to("?action=recall&rev={$rev}", $rev);
                $alt = $ii++ % 2 == 0 ? ' class="alt"' : '';
                $out .= "<tr{$alt}>\n";
                $out .= "<th class='rev' valign='top' rowspan={$rowspan}>{$rrev}</th><td nowrap='nowrap' class='date'>{$inf}</td><td class='change'>{$change}</td><td class='author'>{$ip}&nbsp;</td>";
                $rrev = '';
                $achecked = "";
                $bchecked = "";
                if ($flag == 1) {
                    $achecked = "checked ";
                } else {
                    if (!$flag) {
                        $bchecked = "checked ";
                    }
                }
                $onclick = "onclick='ToggleRev(this)'";
                $out .= "<th nowrap='nowrap' class='check'><input type='radio' name='rev' value='{$rev}' {$achecked} {$onclick} />\n";
                $out .= "<input type='radio' name='rev2' value='{$rev}' {$bchecked} {$onclick} /></th>";
                if (!$simple) {
                    $out .= "<td nowrap='nowrap' class='view'>";
                    foreach ($actions as $k => $v) {
                        $k = is_numeric($k) ? $v : $k;
                        $out .= $formatter->link_to("?action={$k}&amp;rev={$rev}", _($v), ' class="button-small"') . ' ';
                    }
                    if ($flag) {
                        if ($diff_action) {
                            $out .= " " . $formatter->link_to("?action=diff&amp;rev={$rev}", $diff_action, ' class="button-small"');
                        }
                        $out .= "</td>";
                        if (isset($admin)) {
                            $out .= "<td><input type='checkbox' name='range[{$flag}]' value='{$rev}' /></td>";
                        }
                    } else {
                        $out .= "</td>";
                        if (isset($admin)) {
                            $out .= "<td><input type='image' src='{$DBInfo->imgs_dir}/smile/checkmark.png' onClick=\"ToggleAll('infoform');return false;\"/></td>";
                        }
                    }
                }
                $out .= "</tr>\n";
                if (!$simple and $comment) {
                    $out .= "<tr class='log'><td colspan='" . (!empty($admin) ? 6 : 5) . "'><p>{$comment}&nbsp;</p></td></tr>\n";
                }
                $state = 1;
                $flag++;
                $count++;
                if ((empty($options['all']) or $options['all'] != 1) and $count >= $showcount) {
                    $ok = 1;
                }
                break;
        }
    }
    if (!$simple and !empty($admin)) {
        $out .= "<tr><td colspan='" . (!empty($admin) ? 7 : 6) . "' align='right'><input type='checkbox' name='show' checked='checked' />" . _("show only") . ' ';
        if ($DBInfo->security->is_protected("rcspurge", $options)) {
            $out .= "<input type='password' name='passwd'>";
        }
        $out .= "<input type='submit' name='rcspurge' value='" . _("purge") . "'></td></tr>";
    }
    $out .= "<input type='hidden' name='action' value='diff'/>\n</tbody></table></div></form>\n";
    $out .= "<script type='text/javascript' src='{$DBInfo->url_prefix}/local/checkbox.js'></script></div>\n";
    return $out;
}
Example #27
0
function macro_ImageFileSize($formatter, $value = '', $params = array())
{
    global $Config;
    if (empty($value)) {
        return '';
    }
    $sz = 0;
    // check if it is valid or not
    while (preg_match('/^((?:https?|ftp):\\/\\/.*(\\.(?:jpg|jpeg|gif|png)))(?:\\?|&)?/i', $value, $m)) {
        $value = $m[1];
        // check the file size saved by the fetch plugin
        $si = new Cache_text('fetchinfo');
        if ($si->exists($value) && ($info = $si->fetch($value)) !== false) {
            $sz = $info['size'];
            break;
        }
        $sc = new Cache_text('imagefilesize');
        if (empty($params['.refresh']) and $sc->exists($value) and $sc->mtime($value) < time() + 60 * 60 * 24 * 20) {
            $sz = $sc->fetch($value);
        } else {
            // dynamic macro
            if ($formatter->_macrocache and empty($params['call'])) {
                return $formatter->macro_cache_repl('ImageFileSize', $value);
            }
            if (empty($params['call'])) {
                $formatter->_dynamic_macros['@ImageFileSize'] = 1;
            }
            // do not fetch the size of image right now. just fetch the cached info by the fetch plugin
            if (empty($params['call']) and !empty($Config['fetch_imagesize']) and $Config['fetch_imagesize'] == 2) {
                return _("Unknown");
            }
            require_once dirname(__FILE__) . '/../lib/HTTPClient.php';
            $http = new HTTPClient();
            // support proxy
            if (!empty($Config['proxy_host'])) {
                $http->proxy_host = $Config['proxy_host'];
                if (!empty($Config['proxy_port'])) {
                    $http->proxy_port = $Config['proxy_port'];
                }
            }
            // set referrer
            $referer = '';
            if (!empty($Config['fetch_referer_re'])) {
                foreach ($Config['fetch_referer_re'] as $re => $ref) {
                    if (preg_match($re, $value)) {
                        $referer = $ref;
                        break;
                    }
                }
            }
            // default referrer
            if (empty($referer) and !empty($Config['fetch_referer'])) {
                $referer = $Config['fetch_referer'];
            }
            if (empty($referer)) {
                $referer = qualifiedUrl($formatter->link_url($formatter->page->urlname));
            }
            $http->nobody = true;
            $http->referer = $referer;
            // check HEAD support for the internal fetch plugin
            $method = 'GET';
            if (!empty($Config['fetch_imagesize_head']) && strstr($value, $Config['fetch_action'])) {
                $method = 'HEAD';
            }
            $http->sendRequest($value, array(), $method);
            if ($http->status != 200) {
                return _("Unknown");
            }
            if (isset($http->resp_headers['content-length'])) {
                $sz = $http->resp_headers['content-length'];
            }
            $sc->update($value, $sz);
        }
        break;
    }
    if ($sz > 0) {
        $unit = array('Bytes', 'KB', 'MB', 'GB');
        for ($i = 0; $i < 4; $i++) {
            if ($sz <= 1024) {
                break;
            }
            $sz = $sz / 1024;
        }
        return round($sz, 2) . ' ' . $unit[$i];
    }
    // set as dynamic macro or not.
    if ($formatter->_macrocache and empty($options['call'])) {
        return $formatter->macro_cache_repl('ImageFileSize', $value);
    }
    if (empty($options['call'])) {
        $formatter->_dynamic_macros['@ImageFileSize'] = 1;
    }
    return _("Unknown");
}
Example #28
0
function do_SearchPlugin($formatter, $options)
{
    global $DBInfo;
    if ($options['name']) {
        $name = $options['name'];
    } else {
        $name = $DBInfo->sitename;
    }
    if ($options['type']) {
        // fullsearch,titlesearch,fastsearch
        $type = $options['type'];
    } else {
        $type = "fullsearch";
        // by default fullsearch
    }
    if (strpos($name, ".png") != false) {
        header("Content-Type: image/png\r\n");
        header("Content-Disposition: inline; filename=\"{$name}\"");
        #header("Content-Disposition: attachment; filename=\"$name\"" );
        header("Content-Description: MoniWiki Search Plugin Descriptor");
        Header("Pragma: no-cache");
        Header("Expires: 0");
        $fp = readfile("imgs/interwiki/moniwiki-16.png");
        // XXX
        return;
    }
    if (strpos($name, ".src") == false) {
        // error! invalid options
        // name=xxx.[src|png]
        print "invalid option!";
        return;
    }
    $update_url = qualifiedUrl($formatter->link_url('FindPage', "?action=SearchPlugin&amp;name="));
    // FIXME: what's the valid way to get http://.../wiki.php ?
    // alternative: $_SERVER["PHP_SELF"]
    $base_url = qualifiedUrl($formatter->link_url("FindPage"));
    // FIXME: what's the valid search page name for all moniwiki sites?
    $form_url = qualifiedUrl($formatter->link_url("FindPage"));
    #header("Content-Type: application/x-wais-source\r\n");
    header("Content-Type: text/plain\r\n");
    header("Content-Disposition: inline; filename=\"{$name}\"");
    #header("Content-Disposition: attachment; filename=\"$name\"" );
    header("Content-Description: MoniWiki Search Plugin Descriptor");
    Header("Pragma: no-cache");
    Header("Expires: 0");
    // remove file extension part(should be ".src") from url
    // it's just a dummy to deceive stupid mozilla :@
    $name = substr($name, 0, -4);
    $charset = $DBInfo->charset;
    print <<<EOS
# Firefox/Mozilla Search Plugin for MoniWiki by iolo@hellocity.net
<search
  version="7.1"
  name="{$name}"
  description="MoniWiki Search Plugin for {$name}"
  method="GET"
  action="{$base_url}"
  searchForm="{$form_url}"
  queryEncoding="{$charset}"
  queryCharset="{$charset}"
  routeType="internet"
>

<input name="sourceid" value="mozilla-search">
#<inputnext name="start" factor="10">
#<inputprev name="start" factor="10">

<input name="value" user>

# TODO: support various search actions and parameters
<input name="action" value="{$type}">
<input name="context" value="20">
<input name="backlinks" value="0">
<input name="case" value="0">
#<input name="ie" value="utf-8">
#<input name="oe" value="utf-8">

<interpret
  browserResultType="result"
  charset = "{$charset}"
  resultListStart="<!-- RESULT LIST START -->"
  resultListEnd="<!-- RESULT LIST END -->"
  resultItemStart="<!-- RESULT ITEM START -->"
  resultItemEnd="<!-- RESULT ITEM END -->"
>
</search>

<browser
  update="{$update_url}{$name}.src"
  updateIcon="{$update_url}{$name}.png"
  updateCheckDays=1
>

EOS;
}
Example #29
0
function macro_Keywords($formatter, $value, $options = array())
{
    global $DBInfo;
    $supported_lang = array('ko');
    $limit = isset($options['limit']) ? $options['limit'] : 40;
    $opts = explode(',', $value);
    $sort = '';
    foreach ($opts as $opt) {
        $opt = trim($opt);
        if ($opt == 'delicious' or $opt == 'del.icio.us') {
            $tag_link = 'http://del.icio.us/tag/$TAG';
        } else {
            if ($opt == 'technorati') {
                $tag_link = 'http://www.technorati.com/tag/$TAG';
            } else {
                if ($opt == 'flickr') {
                    $tag_link = 'http://www.flickr.com/photos/tags/$TAG';
                } else {
                    if ($opt == 'all') {
                        $options['all'] = 1;
                        $limit = 0;
                    } else {
                        if ($opt == 'random') {
                            $options['random'] = $options['all'] = 1;
                        } else {
                            if ($opt == 'suggest') {
                                $options['suggest'] = 1;
                            } else {
                                if ($opt == 'tour') {
                                    $options['tour'] = 1;
                                } else {
                                    if ($opt == 'cloud') {
                                        $options['cloud'] = 1;
                                    } else {
                                        if ($opt == 'freq') {
                                            $sort = 'freq';
                                        } else {
                                            if (($p = strpos($opt, '=')) !== false) {
                                                $k = substr($opt, 0, $p);
                                                $v = substr($opt, $p + 1);
                                                if ($k == 'limit') {
                                                    $limit = $v;
                                                } else {
                                                    if ($k == 'random') {
                                                        $options['all'] = 1;
                                                        $v = (int) $v;
                                                        $v = $v > 0 ? $v : 1;
                                                        $options['random'] = $v;
                                                    } else {
                                                        if ($k == 'sort' and in_array($v, array('freq', 'alpha'))) {
                                                            $sort = $v;
                                                        } else {
                                                            if ($k == 'type' and in_array($v, array('full', 'title'))) {
                                                                $search = $v . 'search';
                                                            } else {
                                                                if ($k == 'url') {
                                                                    $tag_link = $v;
                                                                    if (preg_match('/\\$TAG/', $tag_link) === false) {
                                                                        $tag_link .= '$TAG';
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                // else ignore
                                            } else {
                                                $pagename = $opt;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (isset($options['random']) and empty($limit)) {
        $limit = 0;
    }
    if (isset($options['sort']) and $options['sort'] == 'freq') {
        $sort = 'freq';
    }
    if (empty($pagename)) {
        $pagename = $formatter->page->name;
    }
    # get cached keywords
    $cache = new Cache_text('keyword');
    $pkey = $pagename;
    $mc = new Cache_text('macro');
    $mkey = 'Keywords.' . md5($pagename . $value);
    $mykeys = array();
    # check cache mtime
    $cmt = $mc->mtime($mkey);
    $pmt = $cache->mtime($pkey);
    if ($cmt > $pmt) {
        # check update or not
        $dmt = $cache->mtime();
        if ($dmt > $cmt) {
            # XXX crude method
            $mykeys = array();
        } else {
            $mykeys = $mc->fetch($mkey);
        }
    } else {
        $mc->remove($mkey);
    }
    if (!$mykeys) {
        if (!empty($options['all'])) {
            $pages = $DBInfo->getPageLists();
        } else {
            $pages = array($pagename);
        }
        foreach ($pages as $pn) {
            if ($keys = $cache->fetch($pn)) {
                $mykeys = array_merge($mykeys, $keys);
            }
        }
        $mc->update($mkey, $mykeys);
    }
    if (!empty($options['all'])) {
        $use_sty = 1;
        $words = array_count_values($mykeys);
        unset($words['']);
        $ncount = array_sum($words);
        // total count
        arsort($words);
        $max = current($words);
        // get max hit number
        if (!empty($options['random'])) {
            $rws = array();
            $selected = array_rand($words, min($options['random'], count($words)));
            foreach ($selected as $k) {
                $rws[$k] = $words[$k];
            }
            $words =& $rws;
        }
        if ($sort != 'freq') {
            ksort($words);
        }
        #sort($words);
        #print $sort." $value";
        #print "<pre>";
        #print_r($words);
        #print "</pre>";
    } else {
        $max = 3;
        // default weight
        $words = array();
        foreach ($mykeys as $key) {
            $words[$key] = $max;
            // give weight to all selected keywords
        }
    }
    # automatically generate list of keywords
    if (empty($options['all']) and (empty($words) or isset($options['suggest']))) {
        $common = <<<EOF
am an a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9
if on in by it at up as down over into for from to of he his him she her back
is are be being been or no not nor and all through under until
these there the top
with here only has had both did faw few little most almost much off on out
also each were was too any very more within then
across before behind beneath beyond after again against around among
so such since because but yet however ever during
it its the this that what where how when who whoever which their them
you your will shall may might we us our
get got would could have
can't won't didn't don't
aiff arj arts asp au avi bin biz css cgi com doc edu exe firm gif gz gzip
htm html info jpeg jpg js jsp mp3 mpeg mpg mov
nom pdf php pl qt ra ram rec shop sit tar tgz tiff txt wav web zip
one two three four five six seven eight nine ten eleven twelve
ftp http https www web net org or kr co us de
EOF;
        $page = $DBInfo->getPage($pagename);
        if (!$page->exists()) {
            return '';
        }
        $raw = $page->get_raw_body();
        $raw = rtrim($raw);
        // strip macros, entities
        $raw = preg_replace("/&[^;\\s]+;|\\[\\[[^\\[]+\\]\\]/", ' ', $raw);
        $raw = preg_replace("/^##.*\$/m", ' ', $raw);
        $raw = preg_replace("/([;\"',`\\\\\\/\\.:@#\\!\\?\$%\\^&\\*\\(\\)\\{\\}\\[\\]\\-_\\+=\\|<>])/", ' ', strip_tags($raw . ' ' . $pagename));
        // pagename also
        $raw = preg_replace("/((?<=[a-z0-9]|[B-Z]{2})([A-Z][a-z]))/", " \\1", $raw);
        $raw = strtolower($raw);
        $raw = preg_replace("/\\b/", ' ', $raw);
        //$raw=preg_replace("/\b([0-9a-zA-Z'\"])\\1+\s*/",' ',$raw);
        $words = preg_split("/\\s+|\n/", $raw);
        // remove common words
        $common_word_page0 = LOCAL_KEYWORDS . '/CommonWords';
        $lines0 = array();
        if ($DBInfo->hasPage($common_word_page0)) {
            $p = $DBInfo->getPage($common_word_page0);
            $lines0 = explode("\n", $p->get_raw_body());
        }
        $lang = isset($formatter->pi['#language']) ? $formatter->pi['#language'] : $DBInfo->default_language;
        if ($lang and in_array($lang, $supported_lang)) {
            $common_word_page = LOCAL_KEYWORDS . '/CommonWords' . ucfirst($lang);
            if ($DBInfo->hasPage($common_word_page)) {
                $p = $DBInfo->getPage($common_word_page);
                $lines = explode("\n", $p->get_raw_body());
                $lines = array_merge($lines, $lines0);
                foreach ($lines as $line) {
                    if (isset($line[0]) and $line[0] == '#') {
                        continue;
                    }
                    $common .= "\n" . $line;
                }
                $common = rtrim($common);
            }
        }
        $words = array_diff($words, preg_split("/\\s+|\n/", $common));
        while (!empty($DBInfo->use_stemmer)) {
            include_once dirname(__FILE__) . '/../lib/stemmer.ko.php';
            include_once dirname(__FILE__) . '/../lib/stemmer.php';
            $indexer = new KoreanStemmer();
            if (!is_resource($indexer->_dict)) {
                break;
            }
            $founds = array();
            foreach ($words as $key) {
                if (preg_match('/^[a-zA-Z0-9]+$/', $key)) {
                    // ignore alphanumeric
                    $stem = PorterStemmer::Stem($key);
                    $founds[] = $stem;
                    continue;
                }
                $match = null;
                $stem = $indexer->getStem(trim($key), $match, $type);
                if (!empty($stem)) {
                    $founds[] = $stem;
                } else {
                    if (!empty($last)) {
                        //print_r($match);
                    }
                }
            }
            $words = $founds;
            $indexer->close();
            break;
        }
        $preword = '';
        $bigwords = array();
        foreach ($words as $word) {
            if (strlen($word) > 2 and strlen($preword) > 2) {
                if ($word == $preword) {
                    continue;
                }
                $key = $preword . ' ' . $word;
                $rkey = $word . ' ' . $preword;
                if (isset($bigwords[$key])) {
                    $bigwords[$key]++;
                } else {
                    if (isset($bigwords[$rkey])) {
                        $bigwords[$rkey]++;
                    } else {
                        $bigwords[$key] = 1;
                    }
                }
            }
            $preword = $word;
        }
        $words = array_count_values($words);
        unset($words['']);
        $ncount = array_sum($words);
        // total count
        /*   
            $words=array_diff(array_keys($counts),preg_split("/\s+|\n/",$common));
        
            if (function_exists('array_intersect_key')) {
                $words=array_intersect_key($counts,$words);
            } else {
                $ret = array();
                foreach($words as $key) {
                    if(array_key_exists($key, $counts))
                        $ret[$key] = $counts[$key];
                }
                $words=&$ret;
            }
        */
        if ($bigwords) {
            //
            $bigwords = array_filter($bigwords, create_function('$a', 'return ($a != 1);'));
            foreach ($bigwords as $k => $v) {
                $words["{$k}"] = $v;
            }
        }
        arsort($words);
        $max = current($words);
        // get max hit number
        $nwords = array();
        if (isset($options['merge'])) {
            foreach ($mykeys as $key) {
                $nwords[$key] = $max;
                // give weight to all selected keywords
            }
        }
        if ($nwords) {
            foreach ($nwords as $k => $v) {
                $words[$k] = $v;
            }
        }
        $use_sty = 1;
    }
    //
    if (!empty($options['call'])) {
        return $words;
    }
    if ($limit and ($sz = sizeof($words)) > $limit) {
        arsort($words);
        $mywords = array_keys($words);
        $mywords = array_slice($mywords, 0, $limit);
        $nwords = array();
        foreach ($mywords as $k) {
            $nwords[$k] = $words[$k];
        }
        $words =& $nwords;
    }
    // make criteria list
    $fz = 0;
    $min = 0;
    $sty = array();
    if (!empty($use_sty)) {
        $fact = array();
        $weight = $max;
        // $ncount
        #print 'max='.$max.' ratio='.$weight/$ncount.':';
        $test = array(0.8, 0.6, 0.4, 0.5, 0.5, 0.5);
        // six level
        for ($i = 0; $i < 6 and $weight > 0; $i++) {
            $weight = (int) ($weight * $test[$i]);
            if ($weight > 0) {
                $fact[] = $weight;
            }
            #print $weight.'--';
        }
        $max = current($fact);
        $min = $limit ? max(1, end($fact)) - 1 : 0;
        // XXX
        // make font-size style
        $fz = max(sizeof($fact), 2);
        $fsh = (MAX_FONT_SZ - MIN_FONT_SZ) / ($fz - 1);
        $fs = MAX_FONT_SZ;
        // max font-size:24px;
        for ($i = 0; $i < $fz; $i++) {
            $ifs = (int) ($fs + 0.5);
            $sty[] = " style='font-size:{$ifs}px;'";
            #print '/'.$ifs;
            $fs -= $fsh;
            $fs = max($fs, 9);
            // min font-size:9px
        }
    }
    if (empty($sort) or $sort != 'freq') {
        ksort($words);
    }
    $link = $formatter->link_url(_rawurlencode($pagename), '');
    if (!isset($tag_link)) {
        if (empty($search)) {
            $search = 'fullsearch&amp;keywords=1';
        }
        if (!empty($options['tour'])) {
            $search = 'tour&amp;arena=keylinks';
        }
        $tag_link = $formatter->link_url(_rawurlencode($pagename), '?action=' . $search . '&amp;value=$TAG');
    }
    $out = '';
    if (!empty($options['add'])) {
        $out = "<form method='post' action='{$link}'>\n";
        $out .= "<input type='hidden' name='action' value='keywords' />\n";
    }
    if (isset($options['cloud'])) {
        $out = '';
        foreach ($words as $key => $val) {
            $style = $sty[$fz - 1];
            for ($i = 0; $i < $fz; $i++) {
                if ($val > $fact[$i]) {
                    $style = $sty[$i];
                    break;
                }
            }
            if ($val > $min) {
                $out .= "<a href='" . qualifiedUrl(str_replace('$TAG', $key, $tag_link)) . "'";
                if ($use_sty) {
                    $out .= ' ' . $style;
                } else {
                    $out .= " style='12'";
                }
                $out .= ">" . $key . "</a>";
            }
        }
        $out = preg_replace('/&amp;/', urlencode('&'), $out);
        $tout = "<a href='http://www.roytanck.com/tag1' style='font-size:20px'>Tag name</a><a href='http://www.roytanck.com/tag2' style='font-size:10px'>Tag two</a>";
        $formatter->register_javascripts(array('js/swfobject.js'));
        $_swf_prefix = qualifiedUrl("{$DBInfo->url_prefix}/local/wp-cumulus");
        // FIXME
        return <<<SWF
<script type="text/javascript">
var flashvars = {
   mode : "tags",
   distr : "true",
   tcolor : "0xffffff",
   tcolor2 : "0x86B9F2",
   hicolor : "0xBAD8F8",
   tagcloud : "<tags>{$out}</tags>"
};

var params = {
   wmode: "opaque",
   bgcolor: "#333333"
};

var attrs = {
   id: "myCloudContent"
};

swfobject.embedSWF("{$_swf_prefix}/tagcloud.swf", "myCloud", "200", "200", "9.0.0","expressInstall.swf", flashvars, params, attrs);
</script>
<div id="myCloud">
</div>
SWF;
    }
    $out .= '<ul>';
    $checkbox = '';
    foreach ($words as $key => $val) {
        $style = '';
        if ($fz > 0) {
            $style = $sty[$fz - 1];
            for ($i = 0; $i < $fz; $i++) {
                if ($val > $fact[$i]) {
                    $style = $sty[$i];
                    break;
                }
            }
        }
        if ($val > $min) {
            $checked = '';
            if ($val >= $max) {
                $checked = 'checked="checked"';
                $ok = 1;
            }
            if (!empty($options['add'])) {
                $checkbox = "<input type='checkbox' {$checked} name='key[]' " . "value='{$key}' />";
            }
            $out .= " <li class=\"tag-item\"";
            if (!empty($use_sty)) {
                $out .= " {$style} title=\"{$val} " . _("hits") . '"';
            }
            $out .= ">{$checkbox}" . "<a href='" . str_replace('$TAG', $key, $tag_link) . "' rel='nofollow'>" . $key . "</a></li>\n";
        }
    }
    $inp = '';
    $form_close = '';
    if (!empty($options['add'])) {
        $msg = _("add keywords");
        $inp = "<li><input type='text' name='keywords' size='12' />: {$msg}</li>";
        if ($ok) {
            $btn = _("Update keywords");
        } else {
            $btn = _("Add keywords");
        }
        $btn1 = _("Add as common words");
        $btn2 = _("Unselect all");
        $btnc = _("Suggest new Keywords");
        $form_close = "<input type='submit' value='{$btn}'/>\n";
        $form_close .= "<input type='submit' name='suggest' value='{$btnc}' />\n";
        $form_close .= "<input type='submit' name='common' value='{$btn1}' />\n";
        $form_close .= "<input type='button' value='{$btn2}' onClick='UncheckAll(this)' />\n";
        $form_close .= "<select name='lang'><option>---</option>\n";
        foreach ($supported_lang as $l) {
            $form_close .= "<option value='{$l}'>{$l}</option>\n";
        }
        $langmsg = _("select language");
        $form_close .= "</select>: {$langmsg}\n</form>\n";
        $form_close .= <<<EOF
<script type='text/javascript' src='{$DBInfo->url_prefix}/local/checkbox.js'>
</script>
EOF;
    }
    return "<div class='cloudView'>" . $out . "{$inp}</ul></div>{$form_close}";
}
Example #30
0
function do_rdf_blog($formatter, $options)
{
    global $DBInfo;
    #  if (!$options['date'] or !preg_match('/^\d+$/',$date)) $date=date('Ym');
    #  else $date=$options['date'];
    $date = $options['date'];
    if ($options['all']) {
        # check error and set default value
        $blog_rss = new Cache_text('blogrss');
        #    $blog_mtime=filemtime($DBInfo->cache_dir."/blog");
        #    if ($blog_rss->exists($date'.xml') and ($blog_rss->mtime($date.'.xml') > $blog_mtime)) {
        #      print $blog_rss->fetch($date.'.xml');
        #      return;
        #    }
        $blogs = Blog_cache::get_rc_blogs($date);
        $logs = Blog_cache::get_summary($blogs, $date);
        $rss_name = $DBInfo->sitename . ': ' . _("Blog Changes");
    } else {
        $blogs = array($DBInfo->pageToKeyname($formatter->page->name));
        $logs = Blog_cache::get_summary($blogs, $date);
        $rss_name = $formatter->page->name;
    }
    usort($logs, 'BlogCompare');
    $time_current = time();
    $URL = qualifiedURL($formatter->prefix);
    $img_url = qualifiedURL($DBInfo->logo_img);
    $url = qualifiedUrl($formatter->link_url("BlogChanges"));
    $desc = sprintf(_("BlogChanges at %s"), $DBInfo->sitename);
    $channel = <<<CHANNEL
<channel rdf:about="{$URL}">
  <title>{$rss_name}</title>
  <link>{$url}</link>
  <description>{$desc}</description>
  <image rdf:resource="{$img_url}"/>
  <items>
  <rdf:Seq>
CHANNEL;
    $items = "";
    #          print('<description>'."[$data] :".$chg["action"]." ".$chg["pageName"].$comment.'</description>'."\n");
    #          print('</rdf:li>'."\n");
    #        }
    $ratchet_day = FALSE;
    if (!$logs) {
        $logs = array();
    }
    foreach ($logs as $log) {
        #print_r($log);
        list($page, $user, $date, $title, $summary) = $log;
        $url = qualifiedUrl($formatter->link_url(_urlencode($page)));
        if (!$title) {
            continue;
        }
        #$tag=md5("#!blog ".$line);
        $tag = md5($user . " " . $date . " " . $title);
        #$tag=_rawurlencode(normalize($title));
        $channel .= "    <rdf:li rdf:resource=\"{$url}#{$tag}\"/>\n";
        $items .= "     <item rdf:about=\"{$url}#{$tag}\">\n";
        $items .= "     <title>{$title}</title>\n";
        $items .= "     <link>{$url}#{$tag}</link>\n";
        if ($summary) {
            $p = new WikiPage($page);
            $f = new Formatter($p);
            ob_start();
            #$f->send_page($summary);
            $f->send_page($summary, array('fixpath' => 1));
            #$summary=_html_escape(ob_get_contents());
            $summary = '<![CDATA[' . ob_get_contents() . ']]>';
            ob_end_clean();
            $items .= "     <description>{$summary}</description>\n";
        }
        $items .= "     <dc:date>{$date}+00:00</dc:date>\n";
        $items .= "     <dc:contributor>\n<rdf:Description>\n" . "<rdf:value>{$user}</rdf:value>\n" . "</rdf:Description>\n</dc:contributor>\n";
        $items .= "     </item>\n";
    }
    $url = qualifiedUrl($formatter->link_url($DBInfo->frontpage));
    $channel .= <<<FOOT
    </rdf:Seq>
  </items>
</channel>
<image rdf:about="{$img_url}">
<title>{$DBInfo->sitename}</title>
<link>{$url}</link>
<url>{$img_url}</url>
</image>
FOOT;
    $url = qualifiedUrl($formatter->link_url("FindPage"));
    $form = <<<FORM
<textinput>
<title>Search</title>
<link>{$url}</link>
<name>goto</name>
</textinput>
FORM;
    $new = "";
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
        if (function_exists('iconv')) {
            $out = $head . $channel . $items . $form;
            $new = iconv($DBInfo->charset, $charset, $out);
            if (!$new) {
                $charset = $DBInfo->charset;
            }
        }
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<rdf:RDF xmlns:wiki="http://purl.org/rss/1.0/modules/wiki/"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:dc="http://purl.org/dc/elements/1.1/"
         xmlns="http://purl.org/rss/1.0/">

<!--
    Add "oe=utf-8" to convert the charset of this rss to UTF-8.
-->
HEAD;
    header("Content-Type: text/xml");
    if ($new) {
        print $head . $new;
    } else {
        print $head . $channel . $items . $form;
    }
    #print $head;
    #print $channel;
    #print $items;
    #print $form;
    print "</rdf:RDF>";
}