function html_no_comment($url)
{
    $url = _urlencode($url);
    // create HTML DOM
    $check_curl = _isCurl();
    if (!($html = file_get_html($url))) {
        if (!($html = str_get_html(file_get_contents_curl($url))) or !$check_curl) {
            return false;
        }
    }
    // remove all comment elements
    foreach ($html->find('comment') as $e) {
        $e->outertext = '';
    }
    $ret = $html->save();
    // clean up memory
    $html->clear();
    unset($html);
    return $ret;
}
function _getParametersAsString(array $parameters)
{
    $queryParameters = array();
    foreach ($parameters as $key => $value) {
        $queryParameters[] = $key . '=' . _urlencode($value);
    }
    return implode('&', $queryParameters);
}
Beispiel #3
0
function _urlencode($elem)
{
    if (is_array($elem)) {
        foreach ($elem as $k => $v) {
            $na[_urlencode($k)] = _urlencode($v);
        }
        return $na;
    }
    return urlencode($elem);
}
Beispiel #4
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;
}
Beispiel #5
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;
}
Beispiel #6
0
function _interwiki_repl($formatter, $url)
{
    global $DBInfo;
    if ($url[0] == "w") {
        $url = substr($url, 5);
    }
    $dum = explode(":", $url, 2);
    $wiki = $dum[0];
    if (isset($dum[1])) {
        $page = $dum[1];
    } else {
        $page = $dum[0];
        return array($formatter->link_url($page));
    }
    $url = $DBInfo->interwiki[$wiki];
    # invalid InterWiki name
    if (!$url) {
        return array();
    }
    $urlpage = _urlencode(trim($page));
    #$urlpage=trim($page);
    if (strpos($url, '$PAGE') === false) {
        $url .= $urlpage;
    } else {
        # GtkRef http://developer.gnome.org/doc/API/2.0/gtk/$PAGE.html
        # GtkRef:GtkTreeView#GtkTreeView
        # is rendered as http://...GtkTreeView.html#GtkTreeView
        $page_only = strtok($urlpage, '#?');
        $query = substr($urlpage, strlen($page_only));
        #if ($query and !$text) $text=strtok($page,'#?');
        $url = str_replace('$PAGE', $page_only, $url) . $query;
    }
    $img = $formatter->imgs_dir_interwiki . strtolower($wiki) . '-16.png';
    if (preg_match("/\\.(png|gif|jpeg|jpg)\$/i", $url)) {
        $img = $url;
    }
    return array($url, $img);
}
Beispiel #7
0
function macro_Attachments($formatter, $value, $params = array())
{
    global $DBInfo;
    if ($value and $DBInfo->hasPage($value)) {
        $p = $DBInfo->getPage($value);
        $body = $p->get_raw_body();
        $baseurl = $formatter->link_url(_urlencode($value));
        //$formatter->page=&$p;
    } else {
        if ($params['text']) {
            $body = $params['text'];
        } else {
            $body = $formatter->page->get_raw_body();
        }
    }
    // from wiki.php
    $punct = "<\\'}\\]\\|\\.\\!";
    # , is omitted for the WikiPedia
    $url = 'attachment';
    $urlrule = "((?:{$url}):\"[^\"]+\"[^\\s{$punct}]*|(?:{$url}):([^\\s{$punct}]|(\\.?[^\\s{$punct}]))+|\\[\\[Attachment\\([^\\)]+\\)\\]\\])";
    // do not include pre block
    $body = preg_replace("/\\{\\{\\{.+?\\}\\}\\}/s", '', $body);
    $my = array();
    $lines = explode("\n", $body);
    foreach ($lines as $line) {
        preg_match_all("/{$urlrule}/i", $line, $match);
        if (!$match) {
            continue;
        }
        $my = array_merge($my, $match[0]);
    }
    $my = array_unique($my);
    if (!empty($params['call'])) {
        return $my;
    }
    return " * " . implode("\n * ", $my);
}
Beispiel #8
0
function macro_Fetch($formatter, $url = '', $params = array())
{
    global $DBInfo;
    if (empty($url)) {
        $params['retval']['error'] = _("Empty URL");
        return false;
    }
    // check valid url
    if (!preg_match('@^((ftp|https?)://[^/]+)/@', $url, $m)) {
        return false;
    }
    $siteurl = $m[1];
    require_once "lib/HTTPClient.php";
    $sz = 0;
    $allowed = 'png|jpeg|jpg|gif';
    if (!empty($DBInfo->fetch_exts)) {
        $allowed = $DBInfo->fetch_exts;
    }
    // urlencode()
    $url = _urlencode($url);
    // set default params
    $maxage = !empty($DBInfo->fetch_maxage) ? (int) $DBInfo->fetch_maxage : 60 * 60 * 24 * 7;
    $timeout = !empty($DBInfo->fetch_timeout) ? (int) $DBInfo->fetch_timeout : 15;
    $vartmp_dir = $DBInfo->vartmp_dir;
    $buffer_size = 2048 * 1024;
    // default buffer size
    if (!empty($DBInfo->fetch_buffer_size) and $DBInfo->fetch_buffer_size > 2048 * 1024) {
        $buffer_size = $DBInfo->fetch_buffer_size;
    }
    // set referrer
    $referer = '';
    if (!empty($DBInfo->fetch_referer_re)) {
        foreach ($DBInfo->fetch_referer_re as $re => $ref) {
            if (preg_match($re, $url)) {
                $referer = $ref;
                break;
            }
        }
    }
    // default referrer
    if (empty($referer) and !empty($DBInfo->fetch_referer)) {
        $referer = $DBInfo->fetch_referer;
    }
    // check site available
    $si = new Cache_text('siteinfo');
    if ($si->exists($siteurl)) {
        if (!empty($params['refresh'])) {
            $si->remove($siteurl);
        } else {
            if (empty($params['refresh']) && ($check = $si->fetch($siteurl)) !== false) {
                $params['retval']['status'] = $check['status'];
                $params['retval']['error'] = $check['error'];
                return false;
            }
        }
    }
    $sc = new Cache_text('fetchinfo');
    $error = null;
    if (empty($params['refresh']) and $sc->exists($url) and $sc->mtime($url) < time() + $maxage) {
        $info = $sc->fetch($url);
        $sz = $info['size'];
        $mimetype = $info['mimetype'];
        $error = !empty($info['error']) ? $info['error'] : null;
        // already retrived and found some error
        if (empty($params['refresh']) and !empty($error)) {
            $params['retval']['status'] = $info['status'];
            $params['retval']['error'] = $error;
            $params['retval']['mimetype'] = $mimetype;
            $params['retval']['size'] = $sz;
            return false;
        }
    } else {
        // check connection
        $http = new HTTPClient();
        // get file header
        $http->nobody = true;
        $http->referer = $referer;
        $http->sendRequest($url, array(), 'GET');
        //if ($http->status == 301 || $http->status == 302 ) {
        //
        //}
        if ($http->status != 200) {
            if ($http->status == 404) {
                $params['retval']['error'] = '404 File Not Found';
            } else {
                $params['retval']['error'] = !empty($http->error) ? $http->error : sprintf(_("Invalid Status %d"), $http->status);
            }
            $params['retval']['status'] = $http->status;
            // check alive site
            if ($http->status == -210) {
                $si->update($siteurl, array('status' => $http->status, 'error' => $params['retval']['error']), 60 * 60 * 24);
                return false;
            }
            $sc->update($url, array('size' => -1, 'mimetype' => '', 'error' => $params['retval']['error'], 'status' => $params['retval']['status']), 60 * 60 * 24 * 3);
            return false;
        }
        if (isset($http->resp_headers['content-length'])) {
            $sz = $http->resp_headers['content-length'];
        }
        if (isset($http->resp_headers['content-type'])) {
            $mimetype = $http->resp_headers['content-type'];
        } else {
            $mimetype = 'application/octet-stream';
        }
        $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype));
    }
    // size info
    if (is_numeric($sz)) {
        $unit = array('Bytes', 'KB', 'MB', 'GB');
        $tmp = $sz;
        for ($i = 0; $i < 4; $i++) {
            if ($tmp <= 1024) {
                break;
            }
            $tmp = $tmp / 1024;
        }
        $hsz = round($tmp, 2) . ' ' . $unit[$i];
        if (empty($buffer_size) && !empty($DBInfo->fetch_max_size) and $sz > $DBInfo->fetch_max_size) {
            $params['retval']['error'] = sprintf(_("Too big file size (%s). Please contact WikiMasters to increase \$fetch_max_size"), $hsz);
            $params['retval']['mimetype'] = $mimetype;
            return false;
        }
    } else {
        $params['retval']['error'] = _("Can't get file size info");
        $params['retval']['mimetype'] = $mimetype;
        return false;
    }
    $is_image = false;
    if (preg_match('/^image\\/(jpe?g|gif|png)$/', $mimetype, $m)) {
        $ext = isset($m[1]) ? '.' . $m[1] : '';
        $is_image = true;
    } else {
        $ext = '.' . get_extension('data/mime.types', $mimetype);
    }
    if (!empty($DBInfo->fetch_images_only) and !$is_image) {
        // always check the content-type
        $params['retval']['error'] = sprintf(_("Invalid mime-type %s"), $mimetype);
        $params['retval']['mimetype'] = $mimetype;
        return false;
    }
    if (empty($params['call'])) {
        if ($is_image) {
            $img_url = $formatter->link_url('', '?action=fetch&amp;url=' . $url);
            return '<div class="externalImage"><div><img src="' . $img_url . '">' . '<div><a href="' . $url . '"><span>[' . strtoupper($m[1]) . ' ' . _("external image") . ' (' . $hsz . ')' . ']</span></a></div></div>';
        }
        return $formatter->link_to('?action=fetch&amp;url=' . $url, $mimetype . ' (' . $hsz . ')');
    }
    // cache dir/filename/cache url
    if (!empty($DBInfo->cache_public_dir) and !empty($DBInfo->cache_public_url)) {
        $fc = new Cache_text('fetchfile', array('dir' => $DBInfo->cache_public_dir));
        $fetchname = $fc->getKey($url);
        $fetchfile = $DBInfo->cache_public_dir . '/' . $fetchname . $ext;
        $fetch_url = $DBInfo->cache_public_url . '/' . $fetchname . $ext;
    } else {
        $fc = new Cache_text('fetchfile');
        $fetchname = $fc->getKey($url);
        $fetchfile = $fc->cache_dir . '/' . $fetchname;
        $fetch_url = null;
    }
    // real fetch job.
    if (!empty($params['refresh']) or !file_exists($fetchfile)) {
        $fp = fopen($fetchfile, 'w');
        if (!is_resource($fp)) {
            $params['retval']['error'] = sprintf(_("Fail to open %s"), $fetchfile);
            return false;
        }
        // retry to get all info
        $http = new HTTPClient();
        if (!empty($buffer_size)) {
            $http->max_buffer_size = $buffer_size;
        }
        $http->vartmp_dir = $vartmp_dir;
        $save = ini_get('max_execution_time');
        set_time_limit(0);
        $http->timeout = $timeout;
        $http->referer = $referer;
        $http->sendRequest($url, array(), 'GET');
        set_time_limit($save);
        if ($http->status != 200) {
            fclose($fp);
            unlink($fetchfile);
            // Error found! save error status to the info cache
            $params['retval']['status'] = $http->status;
            $params['retval']['error'] = $http->error;
            $params['retval']['mimetype'] = $mimetype;
            $params['retval']['size'] = $sz;
            $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype, 'error' => $http->error, 'status' => $params['retval']['status']));
            return false;
        }
        if (!empty($http->resp_body)) {
            fwrite($fp, $http->resp_body);
            fclose($fp);
        } else {
            fclose($fp);
            if (!empty($http->resp_body_file) && file_exists($http->resp_body_file)) {
                copy($http->resp_body_file, $fetchfile);
                unlink($http->resp_body_file);
            }
        }
        // update error status.
        if (!empty($error)) {
            $sc->update($url, array('size' => $sz, 'mimetype' => $mimetype));
        }
    }
    if (!empty($fetch_url) and !empty($DBInfo->fetch_use_cache_url)) {
        $formatter->send_header(array('Status: 302', 'Location: ' . $fetch_url));
        return null;
    }
    if (!empty($params['thumbwidth'])) {
        // check allowed thumb widths.
        $thumb_widths = isset($DBInfo->thumb_widths) ? $DBInfo->thumb_widths : array('120', '240', '320', '480', '600', '800', '1024');
        $width = 320;
        // default
        if (!empty($DBInfo->default_thumb_width)) {
            $width = $DBInfo->default_thumb_width;
        }
        if (!empty($thumb_widths)) {
            if (in_array($params['thumbwidth'], $thumb_widths)) {
                $width = $params['thumbwidth'];
            } else {
                header("HTTP/1.1 404 Not Found");
                echo "Invalid thumbnail width", "<br />", "valid thumb widths are ", implode(', ', $thumb_widths);
                return;
            }
        } else {
            $width = $params['thumbwidth'];
        }
        $thumb_width = $width;
        $force_thumb = true;
    } else {
        // automatically generate thumb images to support low-bandwidth mobile version
        if (is_mobile()) {
            $force_thumb = (!isset($params['m']) or $params['m'] == 1);
        }
    }
    // generate thumb file to support low-bandwidth mobile version
    $thumbfile = '';
    while ((!empty($params['thumb']) or $force_thumb) and preg_match('/^image\\/(jpe?g|gif|png)$/', $mimetype)) {
        if (empty($thumb_width)) {
            $thumb_width = 320;
            // default
            if (!empty($DBInfo->fetch_thumb_width)) {
                $thumb_width = $DBInfo->fetch_thumb_width;
            }
        }
        $thumbfile = preg_replace('@' . $ext . '$@', '.w' . $thumb_width . $ext, $fetchfile);
        if (empty($params['refresh']) && file_exists($thumbfile)) {
            break;
        }
        list($w, $h) = getimagesize($fetchfile);
        if ($w <= $thumb_width) {
            $thumbfile = $fetchfile;
            break;
        }
        require_once 'lib/mediautils.php';
        // generate thumbnail using the gd func or the ImageMagick(convert)
        resize_image($ext, $fetchfile, $thumbfile, $w, $h, $thumb_width);
        break;
    }
    $down_mode = 'inline';
    if (!empty($thumbfile)) {
        $fetchfile = $thumbfile;
    }
    header("Content-Type: {$mimetype}\r\n");
    header("Content-Length: " . filesize($fetchfile));
    //header("Content-Disposition: $down_mode; ".$fname );
    header("Content-Description: MoniWiki PHP Fetch Downloader");
    $mtime = filemtime($fetchfile);
    $lastmod = gmdate("D, d M Y H:i:s", $mtime) . ' GMT';
    $etag = md5($lastmod . $url . $thumbfile);
    header("Last-Modified: " . $lastmod);
    header('ETag: "' . $etag . '"');
    header("Pragma:");
    header('Cache-Control: public, max-age=' . $maxage);
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        header('X-Cache-Debug: Cached OK');
        header('HTTP/1.0 304 Not Modified');
        @ob_end_clean();
        return null;
    }
    @ob_clean();
    $ret = readfile($fetchfile);
    return null;
}
Beispiel #9
0
 function interwiki_repl($url, $text = "")
 {
     global $DBInfo;
     if ($url[0] == "w") {
         $url = substr($url, 5);
     }
     $dum = explode(":", $url, 2);
     $wiki = $dum[0];
     $page = $dum[1];
     #    if (!$page) { # wiki:Wiki/FrontPage
     #      $dum1=explode("/",$url,2);
     #      $wiki=$dum1[0]; $page=$dum1[1];
     #    }
     if (!$page) {
         # wiki:FrontPage(not supported in the MoinMoin
         # or [wiki:FrontPage Home Page]
         $page = $dum[0];
         if (!$text) {
             return $this->word_repl($page, '', '', 1);
         }
         return $this->word_repl($page, $text, '', 1);
     }
     $url = $DBInfo->interwiki[$wiki];
     # invalid InterWiki name
     if (!$url) {
         return $dum[0] . ":" . $this->word_repl($dum[1], $text);
     }
     $urlpage = _urlencode(trim($page));
     #$urlpage=trim($page);
     if (strpos($url, '$PAGE') === false) {
         $url .= $urlpage;
     } else {
         # GtkRef http://developer.gnome.org/doc/API/2.0/gtk/$PAGE.html
         # GtkRef:GtkTreeView#GtkTreeView
         # is rendered as http://...GtkTreeView.html#GtkTreeView
         $page_only = strtok($urlpage, '#?');
         $query = substr($urlpage, strlen($page_only));
         #if ($query and !$text) $text=strtok($page,'#?');
         $url = str_replace('$PAGE', $page_only, $url) . $query;
     }
     $img = $this->_img($DBInfo->imgs_dir . "/" . strtolower($wiki) . "-16.png");
     #"<a href='$url' target='wiki'><img border='0' src='$DBInfo->imgs_dir/".
     #         strtolower($wiki)."-16.png' align='middle' height='16' width='16' ".
     #         "alt='$wiki:' title='$wiki:' /></a>";
     if (!$text) {
         $text = str_replace("%20", " ", $page);
     } else {
         if (preg_match("/^(http|ftp).*\\.(png|gif|jpeg|jpg)\$/i", $text)) {
             $text = $this->_a($text);
             $img = '';
         }
     }
     if (preg_match("/\\.(png|gif|jpeg|jpg)\$/i", $url)) {
         #return "<img border='0' alt='$text' src='$url' />";
         return $this->_a($url);
     }
     return $img . $this->_a($url, $text);
 }
Beispiel #10
0
function macro_Scrap($formatter, $value = '', $options = array())
{
    global $DBInfo;
    $user =& $DBInfo->user;
    # get cookie
    if ($user->id == 'Anonymous') {
        return '';
    }
    $userinfo = $DBInfo->udb->getUser($user->id);
    $pages = array();
    if (!empty($userinfo->info['scrapped_pages'])) {
        $pages = explode("\t", $userinfo->info['scrapped_pages']);
    }
    if (!empty($options['page']) and !in_array($options['page'], $pages)) {
        $pages[] = $options['page'];
    }
    $out = '';
    if ($value == 'js') {
        // get the scrapped pages dynamically
        $script = get_scriptname() . $DBInfo->query_prefix;
        $js = <<<JS
<script type="text/javascript">
/*<![CDATA[*/
(function() {
var script_name = "{$script}";
function get_scrap()
{
    var scrap = document.getElementById('scrap');
    if (scrap == null) {
        // silently ignore
        return;
    }

    // get the scrapped pages
    var qp = '?'; // query_prefix
    var loc = location.protocol + '//' + location.host;
    if (location.port) loc+= ':' + location.port;
    loc+= location.pathname + qp + 'action=scrap/ajax';

    var ret = HTTPGet(loc);
    if (ret) {
        var list = JSON.parse(ret);
        var html = '';
        for (i = 0; i < list.length; i++) {
            html+= '<li><a href="' + script_name + list[i] + '">' + list[i] + "</a></li>\\n";
        }
        scrap.innerHTML = "<ul>" + html + "</ul>";
    }
}

// onload
var oldOnload = window.onload;
window.onload = function(ev) {
    try { oldOnload(); } catch(e) {};
    get_scrap();
}
})();
/*]]>*/
</script>

JS;
        #$formatter->register_javascripts('local/scrap.js');
        $formatter->register_javascripts($js);
        return '<i></i>';
        // dummy
    }
    foreach ($pages as $p) {
        if ($DBInfo->hasPage($p)) {
            $out .= '<li>' . $formatter->link_tag(_urlencode($p), '', $p) . '</li>';
        } else {
            if (!empty($p)) {
                $list = $formatter->macro_repl('PageList', $p, array('rawre' => 1));
                if (empty($list)) {
                    $out .= substr($list, 4, -6);
                }
            }
        }
    }
    if (!empty($out)) {
        return '<ul>' . $out . '</ul>';
    }
    return '';
}
Beispiel #11
0
function macro_trackback($formatter, $value)
{
    preg_match('/(\\d+)?(\\s*,?\\s*.*)?$/', $value, $match);
    $opts = explode(",", $match[2]);
    if ($match[1]) {
        $limit = $match[1];
    } else {
        $limit = 10;
    }
    #  if (in_array('all',$opts))
    $lines = TrackBack_text::get_all();
    $date_fmt = "m-d [h:i a]";
    $template_bra = '';
    $template = '$out.= "<a href=\\"$link\\">$title</a>&nbsp;&nbsp;<span class=\\"blog-user\\">by <a href=\\"$url\\">$site</a> @ $date</span><br />\\n";';
    $template_ket = '';
    if (in_array('simple', $opts)) {
        $template_bra = '<ul>';
        $template = '$out.= "<li><span class=\\"blog-user\\"><a href=\\"$link\\">$title</a></span><br/><span class=\\"blog-user\\">by <a href=\\"$url\\">$site</a> @ $date</span></li>\\n";';
        $template_bra = '</ul>';
        $date_fmt = "m-d";
    }
    $logs = array();
    foreach ($lines as $line) {
        $logs[] = explode("\t", $line, 8);
    }
    usort($logs, 'TrackBackCompare');
    $out = '';
    foreach ($logs as $log) {
        if ($limit <= 0) {
            break;
        }
        list($page, $dum, $entry, $url, $date, $site, $title, $dum2) = $log;
        if (!$title) {
            continue;
        }
        if ($entry) {
            $entry = '&amp;value=' . $entry;
        }
        $link = $formatter->link_url(_urlencode($page), '?action=trackback' . $entry);
        $date[10] = ' ';
        $time = strtotime($date . " GMT");
        $date = date($date_fmt, $time);
        $tmp = explode(':', $site);
        $wiki = $tmp[0];
        if (!empty($tmp[1])) {
            $user = $tmp[1];
            $site = $tmp[1];
        }
        #$out.=$page."<a href='$url'>$title</a> @ $date from $site<br />\n";
        #$out.="<a href='$url'>$title</a> @ $date from $site<br />\n";
        eval($template);
        $limit--;
    }
    return $template_bra . $out . $template_ket;
}
Beispiel #12
0
function macro_Scrap($formatter, $value = '', $options = array())
{
    global $DBInfo;
    $user =& $DBInfo->user;
    # get cookie
    if ($user->id == 'Anonymous') {
        return '';
    }
    $userinfo = $DBInfo->udb->getUser($user->id);
    $pages = array();
    if (!empty($userinfo->info['scrapped_pages'])) {
        $pages = explode("\t", $userinfo->info['scrapped_pages']);
    }
    $scrapped = 0;
    $pgname = '';
    if (!empty($formatter->page->name)) {
        $pgname = $formatter->page->name;
        if (!in_array($formatter->page->name, $pages)) {
            $pages[] = $options['page'];
        } else {
            $scrapped = 1;
        }
    }
    $out = '';
    if ($value == 'js') {
        // get the scrapped pages dynamically
        $script = get_scriptname() . $DBInfo->query_prefix;
        $pgname = _rawurlencode($pgname);
        $js = <<<JS
<script type="text/javascript">
/*<![CDATA[*/
(function() {
var script_name = "{$script}";
var page_name = "{$pgname}";
function get_scrap()
{
    var scrap = document.getElementById('scrap');
    if (scrap == null) {
        // silently ignore
        return;
    }
    var pgname = decodeURIComponent(page_name);
    var scrapped = false;

    // get the scrapped pages
    var qp = '?'; // query_prefix
    var loc = '//' + location.host;
    if (location.port) loc+= ':' + location.port;
    loc+= location.pathname + qp + 'action=scrap/ajax';

    var ret = HTTPGet(loc);
    if (ret) {
        var list = JSON.parse(ret);
        var html = '';
        for (i = 0; i < list.length; i++) {
            if (list[i] == pgname) scrapped = true;
            html+= '<li><a href="' + script_name + list[i] + '">' + list[i] + "</a></li>\\n";
        }
        if (html != '')
            scrap.innerHTML = "<ul>" + html + "</ul>";

        if (scrapped) {
            // change scrap icon
            var iconmenu = document.getElementById("wikiIcon");
            var icons = iconmenu.getElementsByTagName("A");
            for (i = 0; i < icons.length; i++) {
                if (icons[i].href.match(/action=scrap/)) {
                    icons[i].href = icons[i].href.replace(/=scrap/, '=scrap&unscrap=1');
                    icons[i].firstChild.firstChild.src =
                        icons[i].firstChild.firstChild.src.replace('scrap', 'unscrap');
                    break;
                }
            }
        }
    }
}

// onload
var oldOnload = window.onload;
window.onload = function(ev) {
    try { oldOnload(); } catch(e) {};
    get_scrap();
}
})();
/*]]>*/
</script>

JS;
        #$formatter->register_javascripts('local/scrap.js');
        $formatter->register_javascripts($js);
        return '<i></i>';
        // dummy
    }
    foreach ($pages as $p) {
        if ($DBInfo->hasPage($p)) {
            $out .= '<li>' . $formatter->link_tag(_urlencode($p), '', $p) . '</li>';
        } else {
            if (!empty($p)) {
                $list = $formatter->macro_repl('PageList', $p, array('rawre' => 1));
                if (empty($list)) {
                    $out .= substr($list, 4, -6);
                }
            }
        }
    }
    if (!empty($out)) {
        return '<ul>' . $out . '</ul>';
    }
    return '';
}
Beispiel #13
0
function macro_WordIndex($formatter, $value, $params = array())
{
    global $DBInfo;
    $pagelinks = $formatter->pagelinks;
    // save
    $save = $formatter->sister_on;
    $formatter->sister_on = 0;
    if (!empty($DBInfo->use_titlecache)) {
        $cache = new Cache_text('title');
    }
    $word_limit = 50;
    $start = 0;
    $prev = 0;
    if (!empty($params['start']) and is_numeric($params['start'])) {
        $start = $params['start'];
    }
    if (!empty($params['prev']) and is_numeric($params['prev'])) {
        $prev = $params['prev'];
    }
    $value = strval($value);
    if ($value == '' or $value == 'all') {
        $sel = '';
    } else {
        $sel = $value;
    }
    if (@preg_match('/' . $sel . '/i', '') === false) {
        $sel = '';
    }
    $keys = array();
    $dict = array();
    // cache wordindex
    $wc = new Cache_text('wordindex');
    $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0;
    $lock_file = _fake_lock_file($DBInfo->vartmp_dir, 'wordindex');
    $locked = _fake_locked($lock_file, $DBInfo->mtime());
    if ($locked or $wc->exists('key') and $DBInfo->checkUpdated($wc->mtime('key'), $delay)) {
        if ($formatter->group) {
            $keys = $wc->fetch('key.' . $formatter->group);
            $dict = $wc->fetch('wordindex.' . $formatter->group);
        } else {
            $keys = $wc->fetch('key');
            $dict = $wc->fetch('wordindex');
        }
        if (empty($dict) and $locked) {
            // no cache found
            return _("Please wait...");
        }
    }
    if (empty($keys) or empty($dict)) {
        _fake_lock($lock_file);
        $all_pages = array();
        if ($formatter->group) {
            $group_pages = $DBInfo->getLikePages($formatter->group);
            foreach ($group_pages as $page) {
                $all_pages[] = str_replace($formatter->group, '', $page);
            }
        } else {
            $all_pages = $DBInfo->getPageLists();
        }
        foreach ($all_pages as $page) {
            if (!empty($DBInfo->use_titlecache) and $cache->exists($page)) {
                $title = $cache->fetch($page);
            } else {
                $title = $page;
            }
            $tmp = preg_replace("/[\\?!\$%\\.\\^;&\\*()_\\+\\|\\[\\]<>\"' \\-~\\/:]/", " ", $title);
            $tmp = preg_replace("/((?<=[A-Za-z0-9])[A-Z][a-z0-9])/", " \\1", ucwords($tmp));
            $words = preg_split("/\\s+/", $tmp);
            foreach ($words as $word) {
                $word = ltrim($word);
                if (!$word) {
                    continue;
                }
                $key = get_key($word);
                $keys[$key] = $key;
                if (!empty($dict[$key][$word])) {
                    $dict[$key][$word][] = $page;
                } else {
                    if (empty($dict[$key])) {
                        $dict[$key] = array();
                    }
                    $dict[$key][$word] = array($page);
                }
            }
        }
        sort($keys);
        foreach ($keys as $k) {
            #ksort($dict[$k]);
            #ksort($dict[$k], SORT_STRING);
            #uksort($dict[$k], "strnatcasecmp");
            uksort($dict[$k], "strcasecmp");
        }
        if ($formatter->group) {
            $wc->update('key.' . $formatter->group, $keys);
            $wc->update('wordindex.' . $formatter->group, $dict);
        } else {
            $wc->update('key', $keys);
            $wc->update('wordindex', $dict);
        }
        _fake_lock($lock_file, LOCK_UN);
    }
    if (isset($sel[0]) and isset($dict[$sel])) {
        $selected = array($sel);
    } else {
        $selected =& $keys;
    }
    $out = '';
    $key = -1;
    $count = 0;
    $idx = 0;
    foreach ($selected as $k) {
        $words = array_keys($dict[$k]);
        $sz = count($words);
        for ($idx = $start; $idx < $sz; $idx++) {
            $word = $words[$idx];
            $pages =& $dict[$k][$word];
            $pkey = $k;
            if ($key != $pkey) {
                $key = $pkey;
                if (!empty($sel) and !preg_match('/^' . $sel . '/i', $pkey)) {
                    continue;
                }
                if (!empty($out)) {
                    $out .= "</ul>";
                }
                $ukey = urlencode($key);
                $out .= "<a name='{$ukey}'></a><h3><a href='#top'>{$key}</a></h3>\n";
            }
            if (!empty($sel) and !preg_match('/^' . $sel . '/i', $pkey)) {
                continue;
            }
            $out .= "<h4>{$word}</h4>\n";
            $out .= "<ul>\n";
            foreach ($pages as $page) {
                $out .= '<li>' . $formatter->word_repl('"' . $page . '"') . "</li>\n";
            }
            $out .= "</ul>\n";
            $count++;
            if ($count >= $word_limit) {
                break;
            }
        }
    }
    if (isset($sel[0])) {
        $last = count($dict[$sel]);
        $offset = $idx + 1;
        $pager = array();
        if ($start > 0) {
            // get previous start offset.
            $count = 0;
            $idx -= $word_limit - 1;
            if ($idx < 0) {
                $idx = 0;
            }
            $link = $formatter->link_url($formatter->page->name, '?action=wordindex&amp;sec=' . $sel . '&amp;start=' . $idx);
            $pager[] = "<a href='{$link}'>" . _("&#171; Prev") . '</a>';
        }
        if ($offset < $last) {
            $link = $formatter->link_url($formatter->page->name, '?action=wordindex&amp;sec=' . $sel . '&amp;start=' . $offset);
            $pager[] = "<a href='{$link}'>" . _("Next &#187;") . '</a>';
        }
        if (!empty($pager)) {
            $out .= implode(' | ', $pager) . "<br />\n";
        }
    }
    $index = array();
    $tlink = '';
    if (isset($sel[0])) {
        $tlink = $formatter->link_url($formatter->page->name, '?action=wordindex&amp;sec=');
    }
    foreach ($keys as $key) {
        $name = strval($key);
        if ($key == 'Others') {
            $name = _("Others");
        }
        $ukey = urlencode($key);
        $link = !empty($tlink) ? preg_replace('/sec=/', 'sec=' . _urlencode($key), $tlink) : '';
        $index[] = "<a href='{$link}#{$ukey}'>{$name}</a>";
    }
    $str = implode(' | ', $index);
    $formatter->pagelinks = $pagelinks;
    // restore
    $formatter->sister_on = $save;
    return "<center><a name='top'></a>{$str}</center>\n{$out}";
}
Beispiel #14
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;
}
Beispiel #15
0
/**
 * _urlencode
 * urlencode 字符串或数组
 *
 * 注意:
 *   本函数其实只是用于json_encode2,如果php版本>=5.3的话,
 *   建议用闭包实现,这样就不用将此函数暴露在全局中
 *
 * @param string|array $value
 * @return string|array
 */
function _urlencode($value)
{
    if (is_array($value)) {
        foreach ($value as $k => $v) {
            $value[$k] = _urlencode($v);
        }
    } else {
        if (is_string($value)) {
            $value = urlencode(str_replace(array("\\", "\r\n", "\r", "\n", "\"", "\\/", "\t"), array('\\\\', '\\n', '\\n', '\\n', '\\"', '\\/', '\\t'), $value));
        }
    }
    return $value;
}
Beispiel #16
0
function macro_TableOfContents(&$formatter, $value = "")
{
    global $DBInfo;
    static $tocidx = 1;
    // FIXME
    $tocid = 'toc' . $tocidx;
    $head_num = 1;
    $head_dep = 0;
    $TOC = '';
    $a0 = '</a>';
    $a1 = '';
    if (!empty($DBInfo->toc_options)) {
        $value = $DBInfo->toc_options . ',' . $value;
    }
    $toctoggle = !empty($DBInfo->use_toctoggle) ? $DBInfo->use_toctoggle : '';
    $secdep = '';
    $prefix = '';
    $dot = '<span class="dot">.</span>';
    $attr = '';
    while ($value) {
        list($arg, $value) = explode(',', $value, 2);
        $key = strtok($arg, '=');
        if ($key == 'title') {
            $title = strtok('');
        } else {
            if ($key == 'align') {
                $val = strtok('');
                if (in_array($val, array('right', 'left'))) {
                    $attr = ' ' . $val;
                }
            } else {
                if ($key == 'simple') {
                    $simple = strtok('');
                    if ($simple == '') {
                        $simple = 1;
                    }
                    if ($simple) {
                        $a0 = '';
                        $a1 = '</a>';
                    }
                } else {
                    if ($key == 'toggle') {
                        $toctoggle = strtok('');
                        if ($toctoggle == '') {
                            $toctoggle = 1;
                        }
                    } else {
                        if (is_numeric($arg) and $arg > 0 and $arg < 5) {
                            $secdep = $arg;
                        } else {
                            if ($arg) {
                                $value = $value ? $arg . ',' . $value : $arg;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if ($toctoggle) {
        $js = <<<EOS
<script type="text/javascript">
/*<![CDATA[*/
 if (window.showTocToggle) { showTocToggle('{$tocid}', '<span>[+]</span>','<span>[-]</span>'); }
/*]]>*/
</script>
EOS;
    }
    $TOC0 = "\n<div class='wikiToc{$attr}' id='" . $tocid . "'>";
    if (!isset($title)) {
        $title = $formatter->macro_repl('GetText', "Contents");
    }
    if ($title) {
        $TOC0 .= "<div class='toctitle'>\n<h2 style='display:inline'>{$title}</h2>\n</div>";
    }
    $TOC0 .= "<a name='toc' ></a><dl><dd><dl>\n";
    $formatter->toc = 1;
    $baseurl = '';
    if ($value and $DBInfo->hasPage($value)) {
        $p = $DBInfo->getPage($value);
        $body = $p->get_raw_body();
        $baseurl = $formatter->link_url(_urlencode($value));
        $formatter->page =& $p;
    } else {
        $body = $formatter->text;
    }
    // remove processor blocks
    $chunk = preg_split("/({{{\n            (?:(?:[^{}]+|\n            {[^{}]+}(?!})|\n            (?<!{){{1,2}(?!{)|\n            (?<!})}{1,2}(?!})|\n            (?<=\\\\)[{}]{3}(?!}))|(?1)\n            )++}}})/x", $body, -1, PREG_SPLIT_DELIM_CAPTURE);
    $sz = count($chunk);
    $k = 1;
    $body = '';
    foreach ($chunk as $c) {
        if ($k % 2) {
            $body .= $c;
        } else {
            if (!strstr($c, "\n")) {
                $body .= $c;
            }
        }
        $k++;
    }
    $formatter->nomacro = 1;
    // disable macros in headings
    $wordrule = $formatter->wordrule .= '|' . $formatter->footrule;
    $lines = explode("\n", $body);
    foreach ($lines as $line) {
        $line = preg_replace("/\n\$/", "", $line);
        # strip \n
        preg_match("/^\\s*(?<!=)(={1,{$secdep}})\\s(#?)(.*)\\s+\\1\\s?\$/", $line, $match);
        if (!$match) {
            continue;
        }
        $dep = strlen($match[1]);
        if ($dep > 4) {
            $dep = 5;
        }
        $head = str_replace("<", "&lt;", $match[3]);
        # strip some basic wikitags
        # $formatter->baserepl,$head);
        #$head=preg_replace($formatter->baserule,"\\1",$head);
        # do not strip basic wikitags
        $head = preg_replace($formatter->baserule, $formatter->baserepl, $head);
        $head = preg_replace_callback("/(" . $wordrule . ")/", array(&$formatter, 'link_repl'), $head);
        if (!empty($simple)) {
            $head = strip_tags($head, '<b><i><img><sub><sup><del><tt><u><strong>');
        }
        if (empty($depth_top)) {
            $depth_top = $dep;
            $depth = 1;
        } else {
            $depth = $dep - $depth_top + 1;
            if ($depth <= 0) {
                $depth = 1;
            }
        }
        $num = "" . $head_num;
        $odepth = $head_dep;
        $open = "";
        $close = "";
        if (!empty($match[2])) {
            # reset TOC numberings
            $dum = explode(".", $num);
            $i = sizeof($dum);
            for ($j = 0; $j < $i; $j++) {
                $dum[$j] = 1;
            }
            $dum[$i - 1] = 0;
            $num = join($dum, ".");
            if ($prefix) {
                $prefix++;
            } else {
                $prefix = 1;
            }
        }
        if ($odepth && $depth > $odepth) {
            $open .= "<dd><dl>\n";
            $num .= ".1";
        } else {
            if ($odepth) {
                $dum = explode(".", $num);
                $i = sizeof($dum) - 1;
                while ($depth < $odepth && $i > 0) {
                    unset($dum[$i]);
                    $i--;
                    $odepth--;
                    $close .= "</dl></dd>\n";
                }
                $dum[$i]++;
                $num = join($dum, ".");
            }
        }
        $head_dep = $depth;
        # save old
        $head_num = $num;
        if ($baseurl) {
            $TOC .= $close . $open . "<dt><a href='{$baseurl}#s{$prefix}-{$num}'><span class='num'>{$num}{$dot}</span>{$a0} {$head} {$a1}</dt>\n";
        } else {
            $TOC .= $close . $open . "<dt><a id='toc{$prefix}-{$num}' href='#s{$prefix}-{$num}'><span class='num'>{$num}{$dot}</span>{$a0} {$head} {$a1}</dt>\n";
        }
    }
    $formatter->nomacro = 0;
    // restore
    $tocidx++;
    if (isset($TOC[0])) {
        $close = "";
        $depth = $head_dep;
        while ($depth > 1) {
            $depth--;
            $close .= "</dl></dd>\n";
        }
        if (isset($js)) {
            $formatter->register_javascripts("<script type=\"text/javascript\" src=\"{$DBInfo->url_prefix}/local/toctoggle.js\"></script>");
        }
        return $TOC0 . $TOC . $close . "</dl></dd></dl>\n</div>\n" . $js;
    } else {
        return "";
    }
}
Beispiel #17
0
    function send_title($msgtitle = "", $link = "", $options = "")
    {
        // Generate and output the top part of the HTML page.
        global $DBInfo;
        $self =& $this;
        if (!empty($options['action_mode']) and $options['action_mode'] == 'ajax') {
            return;
        }
        $name = $this->page->urlname;
        $action = $this->link_url($name);
        $saved_pagelinks = $this->pagelinks;
        # find upper page
        $up_separator = '/';
        if (!empty($this->use_namespace)) {
            $up_separator .= '|\\:';
        }
        $pos = 0;
        preg_match('@(' . $up_separator . ')@', $name, $sep);
        # NameSpace/SubPage or NameSpace:SubNameSpacePage
        if (isset($sep[1])) {
            $pos = strrpos($name, $sep[1]);
        }
        $mypgname = $this->page->name;
        $upper_icon = '';
        if ($pos > 0) {
            $upper = substr($name, 0, $pos);
            $upper_icon = $this->link_tag($upper, '', $this->icon['upper']) . " ";
        } else {
            if (!empty($this->group)) {
                $group = $this->group;
                $mypgname = substr($this->page->name, strlen($group));
                $upper = _urlencode($mypgname);
                $upper_icon = $this->link_tag($upper, '', $this->icon['main']) . " ";
            }
        }
        $title = '';
        if (isset($this->pi['#title'])) {
            $title = _html_escape($this->pi['#title']);
        }
        // change main title
        if (!empty($options['.title'])) {
            $title = _html_escape($options['.title']);
        }
        if (!empty($msgtitle)) {
            $msgtitle = _html_escape($msgtitle);
        } else {
            if (isset($options['msgtitle'])) {
                $msgtitle = $options['msgtitle'];
            }
        }
        if (empty($msgtitle) and !empty($options['title'])) {
            $msgtitle = $options['title'];
        }
        $groupt = '';
        if (empty($title)) {
            if (!empty($group)) {
                # for UserNameSpace
                $title = $mypgname;
                $groupt = substr($group, 0, -1) . ' &raquo;';
                // XXX
                $groupt = "<span class='wikiGroup'>{$groupt}</span>";
            } else {
                $groupt = '';
                $title = $this->page->title;
            }
            $title = _html_escape($title);
        }
        # setup title variables
        #$heading=$this->link_to("?action=fullsearch&amp;value="._urlencode($name),$title);
        // follow backlinks ?
        if (!empty($DBInfo->backlinks_follow)) {
            $attr = 'rel="follow"';
        } else {
            $attr = '';
        }
        $qext = '';
        if (!empty($DBInfo->use_backlinks)) {
            $qext = '&amp;backlinks=1';
        }
        if (isset($link[0])) {
            $title = "<a href=\"{$link}\">{$title}</a>";
        } else {
            if (empty($options['.title']) and empty($options['nolink'])) {
                $title = $this->link_to("?action=fullsearch{$qext}&amp;value=" . _urlencode($mypgname), $title, $attr);
            }
        }
        if (isset($this->pi['#notitle'])) {
            $title = '';
        } else {
            $title = $groupt . "<h1 class='wikiTitle'>{$title}</h1>";
        }
        $logo = $this->link_tag($DBInfo->logo_page, '', $DBInfo->logo_string);
        $goto_form = $DBInfo->goto_form ? $DBInfo->goto_form : goto_form($action, $DBInfo->goto_type);
        if (!empty($options['msg']) or !empty($msgtitle)) {
            $msgtype = isset($options['msgtype']) ? ' ' . $options['msgtype'] : ' warn';
            $msgs = array();
            if (!empty($options['msg'])) {
                $msgs[] = $options['msg'];
            }
            if (!empty($options['notice'])) {
                $msgs[] = $options['notice'];
            }
            $mtitle0 = implode("<br />", $msgs);
            $mtitle = !empty($msgtitle) ? "<h3>" . $msgtitle . "</h3>\n" : "";
            $msg = <<<MSG
<div class="message" id="wiki-message"><span class='{$msgtype}'>
{$mtitle}{$mtitle0}</span>
</div>
MSG;
            if (isset($DBInfo->hide_log) and $DBInfo->hide_log > 0 and preg_match('/timer/', $msgtype)) {
                $time = intval($DBInfo->hide_log * 1000);
                // sec to ms
                $msg .= <<<MSG
<script type="text/javascript">
/*<![CDATA[*/
setTimeout(function() {\$('#wiki-message').fadeOut('fast');}, {$time});
/*]]>*/
</script>
MSG;
            }
        }
        # navi bar
        $menu = array();
        if (!empty($options['quicklinks'])) {
            # get from the user setting
            $quicklinks = array_flip(explode("\t", $options['quicklinks']));
        } else {
            # get from the config.php
            $quicklinks = $this->menu;
        }
        $sister_save = $this->sister_on;
        $this->sister_on = 0;
        $titlemnu = 0;
        if (isset($quicklinks[$this->page->name])) {
            #$attr.=" class='current'";
            $titlemnu = 1;
        }
        if (!empty($DBInfo->use_userlink) and isset($quicklinks['UserPreferences']) and $options['id'] != 'Anonymous') {
            $tmpid = 'wiki:UserPreferences ' . $options['id'];
            $quicklinks[$tmpid] = $quicklinks['UserPreferences'];
            unset($quicklinks['UserPreferences']);
        }
        $this->forcelink = 1;
        foreach ($quicklinks as $item => $attr) {
            if (strpos($item, ' ') === false) {
                if (strpos($attr, '=') === false) {
                    $attr = "accesskey='{$attr}'";
                }
                # like 'MoniWiki'=>'accesskey="1"'
                $menu[$item] = $this->word_repl($item, _($item), $attr);
                #        $menu[]=$this->link_tag($item,"",_($item),$attr);
            } else {
                # like a 'http://moniwiki.sf.net MoniWiki'
                $menu[$item] = $this->link_repl($item, $attr);
            }
        }
        if (!empty($DBInfo->use_titlemenu) and $titlemnu == 0) {
            $len = $DBInfo->use_titlemenu > 15 ? $DBInfo->use_titlemenu : 15;
            #$attr="class='current'";
            $mnuname = _html_escape($this->page->name);
            if ($DBInfo->hasPage($this->page->name)) {
                if (strlen($mnuname) < $len) {
                    $menu[$this->page->name] = $this->word_repl($mypgname, $mnuname, $attr);
                } else {
                    if (function_exists('mb_strimwidth')) {
                        $my = mb_strimwidth($mypgname, 0, $len, '...', $DBInfo->charset);
                        $menu[$this->page->name] = $this->word_repl($mypgname, _html_escape($my), $attr);
                    }
                }
            }
        }
        $this->forcelink = 0;
        $this->sister_on = $sister_save;
        if (empty($this->css_friendly)) {
            $menu = $this->menu_bra . implode($this->menu_sep, $menu) . $this->menu_cat;
        } else {
            $cls = 'first';
            $mnu = '';
            foreach ($menu as $k => $v) {
                if (preg_match('/current/', $v)) {
                    $cls .= ' current';
                }
                # set current page attribute.
                $mnu .= '<li' . (!empty($cls) ? ' class="' . $cls . '"' : '') . '>' . $menu[$k] . "</li>\n";
                $cls = '';
            }
            // action menus
            $action_menu = '';
            if (!empty($DBInfo->menu_actions)) {
                $actions = array();
                foreach ($DBInfo->menu_actions as $action) {
                    if (strpos($action, ' ') !== false) {
                        list($act, $text) = explode(' ', $action, 2);
                        if ($options['page'] == $this->page->name) {
                            $actions[] = $this->link_to($act, _($text));
                        } else {
                            $actions[] = $this->link_tag($options['page'], $act, _($text));
                        }
                    } else {
                        $actions[] = $this->link_to("?action={$action}", _($action), " rel='nofollow'");
                    }
                }
                $action_menu = '<ul class="dropdown-menu"><li>' . implode("</li>\n<li>", $actions) . '</li></ul>' . "\n";
            }
            $menu = '<div id="wikiMenu"><ul>' . $mnu . "</ul></div>\n";
        }
        $this->topmenu = $menu;
        # submenu XXX
        if (!empty($this->submenu)) {
            $smenu = array();
            $mnu_pgname = (!empty($group) ? $group . '~' : '') . $this->submenu;
            if ($DBInfo->hasPage($mnu_pgname)) {
                $pg = $DBInfo->getPage($mnu_pgname);
                $mnu_raw = $pg->get_raw_body();
                $mlines = explode("\n", $mnu_raw);
                foreach ($mlines as $l) {
                    if (!empty($mk) and preg_match('/^\\s{2,}\\*\\s*(.*)$/', $l, $m)) {
                        if (isset($smenu[$mk]) and !is_array($smenu[$mk])) {
                            $smenu[$mk] = array();
                        }
                        $smenu[$mk][] = $m[1];
                        if (isset($smenu[$m[1]])) {
                            $smenu[$m[1]] = $mk;
                        }
                    } else {
                        if (preg_match('/^ \\*\\s*(.*)$/', $l, $m)) {
                            $mk = $m[1];
                        }
                    }
                }
                # make $submenu, $submain
                $cmenu = null;
                if (isset($smenu[$this->page->name])) {
                    $cmenu =& $smenu[$this->page->name];
                }
                $submain = '';
                if (isset($smenu['Main'])) {
                    $submenus = array();
                    foreach ($smenu['Main'] as $item) {
                        $submenus[] = $this->link_repl($item);
                    }
                    $submain = '<ul><li>' . implode("</li><li>", $submenus) . "</li></ul>\n";
                }
                $submenu = '';
                if ($cmenu and ($cmenu != 'Main' or !empty($DBInfo->submenu_showmain))) {
                    if (is_array($cmenu)) {
                        $smenua = $cmenu;
                    } else {
                        $smenua = $smenu[$cmenu];
                    }
                    $submenus = array();
                    foreach ($smenua as $item) {
                        $submenus[] = $this->link_repl($item);
                    }
                    #print_r($submenus);
                    $submenu = '<ul><li>' . implode("</li><li>", $submenus) . "</li></ul>\n";
                    # set current attribute.
                    $submenu = preg_replace("/(li)>(<a\\s[^>]+current[^>]+)/", "\$1 class='current'>\$2", $submenu);
                }
            }
        }
        # icons
        #if ($upper)
        #  $upper_icon=$this->link_tag($upper,'',$this->icon['upper'])." ";
        if (empty($this->icons)) {
            $this->icons = array('edit' => array('', '?action=edit', $this->icon['edit'], 'accesskey="e"'), 'diff' => array('', '?action=diff', $this->icon['diff'], 'accesskey="c"'), 'show' => array('', '', $this->icon['show']), 'backlinks' => array('', '?action=backlinks', $this->icon['backlinks']), 'random' => array('', '?action=randompage', $this->icon['random']), 'find' => array('FindPage', '', $this->icon['find']), 'info' => array('', '?action=info', $this->icon['info']));
            if (!empty($this->notify)) {
                $this->icons['subscribe'] = array('', '?action=subscribe', $this->icon['mailto']);
            }
            $this->icons['help'] = array('HelpContents', '', $this->icon['help']);
            $this->icons['pref'] = array('UserPreferences', '', $this->icon['pref']);
        }
        # UserPreferences
        if ($options['id'] != "Anonymous") {
            $user_link = $this->link_tag("UserPreferences", "", $options['id']);
            if (empty($DBInfo->no_wikihomepage) and $DBInfo->hasPage($options['id'])) {
                $home = $this->link_tag($options['id'], "", $this->icon['home']) . " ";
                unset($this->icons['pref']);
                // insert home icon
                $this->icons['home'] = array($options['id'], "", $this->icon['home']);
                $this->icons['pref'] = array("UserPreferences", "", $this->icon['pref']);
            } else {
                $this->icons['pref'] = array("UserPreferences", "", $this->icon['pref']);
            }
            if (isset($options['scrapped'])) {
                if (!empty($DBInfo->use_scrap) && $DBInfo->use_scrap != 'js' && $options['scrapped']) {
                    $this->icons['scrap'] = array('', '?action=scrap&amp;unscrap=1', $this->icon['unscrap']);
                } else {
                    $this->icons['scrap'] = array('', '?action=scrap', $this->icon['scrap']);
                }
            }
        } else {
            $user_link = $this->link_tag("UserPreferences", "", _($this->icon['user']));
        }
        if (!empty($DBInfo->check_editable)) {
            if (!$DBInfo->security->is_allowed('edit', $options)) {
                $this->icons['edit'] = array('', '?action=edit', $this->icon['locked']);
            }
        }
        if (!empty($this->icons)) {
            $icon = array();
            $myicons = array();
            if (!empty($this->icon_list)) {
                $inames = explode(',', $this->icon_list);
                foreach ($inames as $item) {
                    if (isset($this->icons[$item])) {
                        $myicons[$item] = $this->icons[$item];
                    } else {
                        if (isset($this->icon[$item])) {
                            $myicons[$item] = array("", '?action=' . $item, $this->icon[$item]);
                        }
                    }
                }
            } else {
                $myicons =& $this->icons;
            }
            foreach ($myicons as $item) {
                if (!empty($item[3])) {
                    $attr = $item[3];
                } else {
                    $attr = '';
                }
                $icon[] = $this->link_tag($item[0], $item[1], $item[2], $attr);
            }
            $icons = $this->icon_bra . implode($this->icon_sep, $icon) . $this->icon_cat;
        }
        $rss_icon = $this->link_tag("RecentChanges", "?action=rss_rc", $this->icon['rss']) . " ";
        $this->_vars['rss_icon'] =& $rss_icon;
        $this->_vars['icons'] =& $icons;
        $this->_vars['title'] = $title;
        $this->_vars['menu'] = $menu;
        $this->_vars['action_menu'] = $action_menu;
        isset($upper_icon) ? $this->_vars['upper_icon'] = $upper_icon : null;
        isset($home) ? $this->_vars['home'] = $home : null;
        if (!empty($options['header'])) {
            $this->_vars['header'] = $header = $options['header'];
        } else {
            if (isset($this->_newtheme) and $this->_newtheme == 2 and !empty($this->header_html)) {
                $this->_vars['header'] = $header = $this->header_html;
            }
        }
        if ($mtime = $this->page->mtime()) {
            $tz_offset = $this->tz_offset;
            $lastedit = gmdate("Y-m-d", $mtime + $tz_offset);
            $lasttime = gmdate("H:i:s", $mtime + $tz_offset);
            $datetime = gmdate('Y-m-d\\TH:i:s', $mtime) . '+00:00';
            $this->_vars['lastedit'] = $lastedit;
            $this->_vars['lasttime'] = $lasttime;
            $this->_vars['datetime'] = $datetime;
        }
        # print the title
        if (empty($this->_newtheme) or $this->_newtheme != 2) {
            if (isset($this->_newtheme) and $this->_newtheme != 2) {
                echo '<body' . (!empty($options['attr']) ? ' ' . $options['attr'] : '') . ">\n";
            }
            echo '<div><a id="top" name="top" accesskey="t"></a></div>' . "\n";
        }
        #
        if (file_exists($this->themedir . "/header.php")) {
            if (!empty($this->trail)) {
                $trail =& $this->trail;
            }
            if (!empty($this->origin)) {
                $origin =& $this->origin;
            }
            $subindex = !empty($this->subindex) ? $this->subindex : '';
            $themeurl = $this->themeurl;
            include $this->themedir . "/header.php";
        } else {
            #default header
            $header = "<table width='100%' border='0' cellpadding='3' cellspacing='0'>";
            $header .= "<tr>";
            if ($DBInfo->logo_string) {
                $header .= "<td rowspan='2' style='width:10%' valign='top'>";
                $header .= $logo;
                $header .= "</td>";
            }
            $header .= "<td>{$title}</td>";
            $header .= "</tr><tr><td>\n";
            $header .= $goto_form;
            $header .= "</td></tr></table>\n";
            # menu
            echo "<" . $this->tags['header'] . " id='wikiHeader'>\n";
            echo $header;
            if (!$this->css_friendly) {
                echo $menu . " " . $user_link . " " . $upper_icon . $icons . $rss_icon;
            } else {
                echo "<div id='wikiLogin'>" . $user_link . "</div>";
                echo "<div id='wikiIcon'>" . $upper_icon . $icons . $rss_icon . '</div>';
                echo $menu;
            }
            if (!empty($msg)) {
                echo $msg;
            }
            echo "</" . $this->tags['header'] . "\n";
        }
        // send header only
        if ($options['.header']) {
            return;
        }
        if (empty($this->popup) and (empty($themeurl) or empty($this->_newtheme))) {
            echo $DBInfo->hr;
            if ($options['trail']) {
                echo "<div id='wikiTrailer'><p>\n";
                echo $this->trail;
                echo "</p></div>\n";
            }
            if (!empty($this->origin)) {
                echo "<div id='wikiOrigin'><p>\n";
                echo $this->origin;
                echo "</p></div>\n";
            }
            if (!empty($this->subindex)) {
                echo $this->subindex;
            }
        }
        echo "\n<" . $this->tags['article'] . " id='wikiBody' class='entry-content'>\n";
        #if ($this->subindex and !$this->popup and (empty($themeurl) or !$this->_newtheme))
        #  echo $this->subindex;
        $this->pagelinks = $saved_pagelinks;
    }
Beispiel #18
0
function do_fastsearch($formatter, $options)
{
    global $DBInfo;
    $default_limit = isset($DBInfo->fastsearch_limit) ? $DBInfo->fastsearch_limit : 30;
    $rule = '';
    if ($options['action'] == 'titleindex' || isset($_GET['q'][0])) {
        $options['value'] = $_GET['q'];
        $options['arena'] = 'titlesearch';
        while (!empty($DBInfo->use_hangul_search)) {
            include_once "lib/unicode.php";
            $val = $_GET['q'];
            if (strtoupper($DBInfo->charset) != 'UTF-8' and function_exists('iconv')) {
                $val = iconv($DBInfo->charset, 'UTF-8', $val);
            }
            if (!$val) {
                break;
            }
            $rule = utf8_hangul_getSearchRule($val);
            $test = @preg_match("/^{$rule}/", '');
            if ($test === false) {
                $rule = $options['value'];
            }
            break;
        }
        if (!$rule) {
            $rule = trim($options['value']);
        }
    }
    $ret = $options;
    $extra = '';
    if (!empty($options['backlinks']) || $options['arena'] == 'pagelinks') {
        $title = sprintf(_("BackLinks search for \"%s\""), $options['value']);
        $extra = '&amp;arena=pagelinks';
    } else {
        if (!empty($options['titlesearch']) || $options['arena'] == 'titlesearch') {
            $title = sprintf(_("Title search for \"%s\""), $options['value']);
            if (!empty($options['titlesearch'])) {
                $ret['arena'] = 'titlesearch';
            }
            $extra = '&amp;arena=titlesearch';
        } else {
            $title = sprintf(_("Full text search for \"%s\""), $options['value']);
        }
    }
    if ($rule) {
        $out = macro_FastSearch($formatter, $rule, $ret);
    } else {
        $out = macro_FastSearch($formatter, $options['value'], $ret);
    }
    if (isset($_GET['q'][0])) {
        header("Content-Type: text/plain");
        print join("\n", $out);
        return;
    }
    $options['msg'] = !empty($ret['msg']) ? $ret['msg'] : '';
    $formatter->send_header("", $options);
    $formatter->send_title($title, $formatter->link_url("FindPage"), $options);
    if (!empty($ret['form'])) {
        print $ret['form'];
    }
    print $out;
    $context = !empty($options['context']) ? $options['context'] : 0;
    $limit = isset($options['limit'][0]) ? $options['limit'] : $default_limit;
    if ($context) {
        $extra = '&amp;context=' . $context;
    }
    if ($options['value']) {
        printf(_("Found %s matching %s out of %s total pages") . "<br />\n", $ret['hit'], $ret['hit'] == 1 ? _("page") : _("pages"), $ret['all']);
        if (!empty($limit) and $ret['hit'] > $limit) {
            $page = _urlencode($options['value']);
            echo $formatter->link_to("?action=fastsearch&amp;value={$page}&amp;limit=0" . $extra, sprintf(_("Show all %d results"), $ret['hit'])) . "<br />\n";
        }
    }
    $args['noaction'] = 1;
    $formatter->send_footer($args, $options);
}
Beispiel #19
0
function _index($formatter, $pages, $params = array())
{
    global $Config;
    if (isset($GLOBALS['.index_id'])) {
        $GLOBALS['.index_id']++;
        $index_id = $GLOBALS['.index_id'];
    } else {
        $index_id = $GLOBALS['.index_id'] = 0;
    }
    $anchor = 'index-anchor' . $index_id;
    $count = !empty($params['.count']) ? true : false;
    if ($count) {
        $cc = new Cache_Text('category');
        $bc = new Cache_Text('backlinks');
    }
    $keys = array();
    $key = '';
    $out = '';
    $redirect = '';
    $n = 0;
    foreach ($pages as $page => $info) {
        // redirect case
        if ($info == -2) {
            $urlname = _urlencode($page);
            $redirect .= '<li>' . $formatter->link_tag($urlname, '', _html_escape($page));
            $redirect .= " <span class='redirectIcon'><span>" . _("Redirect page") . "</span></span>\n";
            $redirect .= "</li>\n";
            $n++;
            continue;
        } else {
            if (is_int($info)) {
                $title = $page;
            } else {
                $title = $info;
            }
        }
        $pkey = get_key("{$title}");
        if ($key != $pkey) {
            if (isset($pkey[0])) {
                $keys[] = $pkey;
            }
            $key = $pkey;
            if (isset($out[0])) {
                $out .= "</ul></div>";
            }
            $out .= "<div><a name='{$key}'></a><h2><a href='#{$anchor}'>{$key}</a></h2>\n";
            $out .= "<ul>";
        }
        $urlname = _urlencode($page);
        $extra = '';
        // count subpages
        if ($count) {
            // get backlinks mtime
            $mtime = $bc->mtime($page);
            // get category counter info
            $cci = $cc->fetch($page, $mtime);
            if ($formatter->refresh || $cci === false) {
                // count backlinks
                $links = $bc->fetch($page);
                $c = 0;
                $p = 0;
                foreach ($links as $link) {
                    if (preg_match('@' . $Config['category_regex'] . '@', $link)) {
                        $c++;
                    } else {
                        $p++;
                    }
                }
                // update cotegory counter info
                $cci = array('C' => $c, 'P' => $p);
                $cc->update($page, $cci);
            }
            // mediawiki like category status: Category (XX C, YY P)
            $tmp = array();
            if (!empty($cci['C'])) {
                $tmp[] = $cci['C'] . ' C';
            }
            if (!empty($cci['P'])) {
                $tmp[] = $cci['P'] . ' P';
            }
            if (isset($tmp[0])) {
                $extra = ' (' . implode(', ', $tmp) . ')';
            }
        }
        $out .= '<li>' . $formatter->link_tag($urlname, '', _html_escape($title));
        $out .= $extra;
        if ($info == -2) {
            $out .= " <span class='redirectIcon'><span>" . _("Redirect page") . "</span></span>\n";
        }
        $out .= "</li>\n";
        $n++;
    }
    $out .= "</ul></div>\n";
    $keys = array_unique($keys);
    $index = array();
    foreach ($keys as $key) {
        $name = strval($key);
        $tag = '#' . $key;
        if ($name == 'Others') {
            $name = _("Others");
        }
        $index[] = "<a href='{$tag}'>{$name}</a>";
    }
    $str = implode(' | ', $index);
    if (isset($redirect[0])) {
        $redirect = '<div><h2>' . _("Redirects") . '</h2><ul>' . $redirect . '</ul></div>';
    }
    if ($n > 10) {
        $attr = " class='index-group'";
    } else {
        $attr = '';
    }
    if ($n > 0) {
        return "<div style='text-align:center'><a name='{$anchor}'></a>{$str}</div>\n<div{$attr}>{$redirect}{$out}</div>";
    } else {
        return false;
    }
}
Beispiel #20
0
function macro_ShareButtons($formatter, $value = '', $params)
{
    global $DBInfo;
    $lang = $DBInfo->lang;
    $btn = _("tweet");
    $link = $formatter->link_url($formatter->page->urlname);
    $href = qualifiedURL($link);
    $ehref = urlencode($href);
    // fix for twitter
    if (!$formatter->page->exists()) {
        return '';
    }
    if ($value == 'nojs') {
        $fb = '<li><a class="facebook" href="https://www.facebook.com/sharer/sharer.php?u=' . $href . '" target="_blank"><span>' . _("fb") . '</span></a></li>';
        $gplus = '<li><a class="gplus" href="https://plus.google.com/share?url=' . $href . '" target="_blank"><span>' . _("g+") . '</span></a></li>';
        $twitter = '<li><a class="twitter" href="https://twitter.com/share?url=' . $ehref . '" target="_blank"><span>' . $btn . '</span></a></li>';
        $oc = new Cache_text('opengraph');
        $pin = '';
        if (($val = $oc->fetch($formatter->page->name)) !== false) {
            if (!empty($val['image'])) {
                $image = $val['image'];
                $image_href = urlencode(str_replace('&amp;', '&', $image));
                // fix
                $pin = '<li><a class="pinterest" href="https://pinterest.com/pin/create/button/?url=' . $ehref . '&amp;description=' . _urlencode($val['description']) . '&amp;media=' . $image_href . '" target="_blank"><span>' . _("pin") . '</span></a></li>';
            }
        }
        return '<div class="share-buttons"><ul>' . $pin . ' ' . $fb . ' ' . $twitter . ' ' . $gplus . '</ul></div>';
    }
    $twitter_attr = '';
    $facebook_attr = 'data-layout="button_count"';
    $gplus_attr = ' data-size="medium"';
    if ($value == 'vertical' or $value == 'vert') {
        $twitter_attr = ' data-count="vertical"';
        $gplus_attr = ' data-size="tall"';
        $facebook_attr = 'data-layout="box_count"';
    } else {
        if ($value == 'icon') {
            $twitter_attr = ' data-count="none"';
            $gplus_attr = ' data-annotation="none" data-size="tall"';
            $facebook_attr = 'data-layout="button"';
        }
    }
    $twitter = <<<EOF
<a href="https://twitter.com/share" class="twitter-share-button" data-url="{$href}" data-lang="{$lang}" data-dnt="true"{$twitter_attr}>{$btn}</a>
EOF;
    $js = <<<EOF
<script type="text/javascript">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
EOF;
    $formatter->register_javascripts($js);
    $gplus = <<<EOF
<div class="g-plusone" data-href="{$href}"{$gplus_attr}></div>
EOF;
    $js = <<<EOF
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>
EOF;
    $formatter->register_javascripts($js);
    $js = <<<EOF
<script type="text/javascript">(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/ko_KR/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

EOF;
    $formatter->register_javascripts($js);
    $fb = <<<EOF
<div class="fb-like"
data-href="{$href}"
data-width="450"
data-action="recommend"
data-show-faces="false"
{$facebook_attr}
data-send="false"></div>
EOF;
    return '<div class="share-buttons">' . $fb . ' ' . $twitter . ' ' . $gplus . '</div>';
}
Beispiel #21
0
function macro_Play($formatter, $value, $params = array())
{
    global $DBInfo;
    static $autoplay = 1;
    $max_width = 600;
    $max_height = 400;
    $default_width = 320;
    $default_height = 240;
    // get the macro alias name
    $macro = 'play';
    if (!empty($params['macro_name']) and $params['macro_name'] != 'play') {
        $macro = $params['macro_name'];
    }
    // use alias macro name as [[Youtube()]], [[Vimeo()]]
    #
    $media = array();
    #
    preg_match("/^(([^,]+\\s*,?\\s*)+)\$/", $value, $match);
    if (!$match) {
        return '[[Play(error!! ' . $value . ')]]';
    }
    $align = '';
    // parse arguments height, width, align
    if (($p = strpos($match[1], ',')) !== false) {
        $my = explode(',', $match[1]);
        $my = array_map('trim', $my);
        for ($i = 0, $sz = count($my); $i < $sz; $i++) {
            if (strpos($my[$i], '=')) {
                list($key, $val) = explode('=', $my[$i], 2);
                $val = trim($val, '"\'');
                $val = trim($val);
                if ($key == 'width' and $val > 1) {
                    $width = intval($val);
                } else {
                    if ($key == 'height' and $val > 1) {
                        $height = intval($val);
                    } else {
                        if ($key == 'align') {
                            if (in_array($val, array('left', 'center', 'right'))) {
                                $align = ' obj' . ucfirst($val);
                            }
                        } else {
                            $media[] = $my[$i];
                        }
                    }
                }
            } else {
                // multiple files
                $media[] = $my[$i];
            }
        }
    } else {
        $media[] = trim($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("/^((https?|ftp|mms|rtsp):)?\\/\\//", $media[$i])) {
            if ($macro != 'play') {
                // will be parsed later
                $url[] = $media[$i];
                continue;
            }
            $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("/^((https?|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 = '';
            $custom = '';
            $object_prefered = false;
            // http://code.google.com/p/google-code-project-hosting-gadgets/source/browse/trunk/video/video.js
            if ($macro == 'youtube' && preg_match("@^([a-zA-Z0-9_-]+)(?:\\?.*)?\$@", $media[$i], $m) || preg_match("@(?:https?:)?//(?:[a-z-]+[.])?(?:youtube(?:[.][a-z-]+)+|youtu\\.be)/(?:watch[?].*v=|v/|embed/)?([a-z0-9_-]+)\$@i", $media[$i], $m)) {
                if ($object_prefered) {
                    $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";
                } else {
                    $iframe = '//www.youtube.com/embed/' . $m[1];
                    $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen';
                    if (empty($mysize)) {
                        $attr .= ' width="500px" height="281px"';
                    } else {
                        $attr .= ' ' . $mysize;
                    }
                }
                $mediainfo = 'Youtube movie';
                $objclass = ' youtube';
            } else {
                if (preg_match('@^https?://(?:videofarm|tvpot)\\.daum\\.net/(?:.*?(?:clipid=|vid=|v/))?([a-zA-Z0-9%$]+)@i', $media[$i], $m)) {
                    // like as http://tvpot.daum.net/v/GCpMeZtuBnk%24
                    if (preg_match('@[0-9]+$@', $m[1])) {
                        // clipid case
                        $aurl = $media[$i];
                        $clipid = $m[1];
                        require_once "lib/HTTPClient.php";
                        // fetch tvpot.daum.net
                        $sc = new Cache_text('daumtvpot');
                        $maxage = 60 * 60;
                        if (empty($params['refresh']) and $sc->exists($aurl) and $sc->mtime($aurl) < time() + $maxage) {
                            $info = $sc->fetch($aurl);
                        } else {
                            // no cached info found.
                            if ($formatter->_macrocache and empty($params['call'])) {
                                return $formatter->macro_cache_repl('Play', $value);
                            }
                            if (empty($params['call'])) {
                                $formatter->_dynamic_macros['@Play'] = 1;
                            }
                            // try to fetch tvpot.daum.net
                            $http = new HTTPClient();
                            $save = ini_get('max_execution_time');
                            set_time_limit(0);
                            $http->timeout = 15;
                            // support proxy
                            if (!empty($DBInfo->proxy_host)) {
                                $http->proxy_host = $DBInfo->proxy_host;
                                if (!empty($DBInfo->proxy_port)) {
                                    $http->proxy_port = $DBInfo->proxy_port;
                                }
                            }
                            $http->sendRequest($aurl, array(), 'GET');
                            set_time_limit($save);
                            if ($http->status != 200) {
                                return '[[Media(' . $aurl . ')]]';
                            }
                            if (!empty($http->resp_body)) {
                                // search Open Graph url info
                                if (preg_match('@og:url"\\s+content="http://tvpot\\.daum\\.net/v/([^"]+)"@', $http->resp_body, $match)) {
                                    $info = array('vid' => $match[1], 'clipid' => $clipid);
                                    $sc->update($aurl, $info);
                                }
                            } else {
                                return '[[Media(' . $aurl . ')]]';
                            }
                        }
                        $m[1] = $info['vid'];
                    }
                    if ($object_prefered) {
                        $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[2] . '&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";
                    } else {
                        $iframe = '//videofarm.daum.net/controller/video/viewer/Video.html?play_loc=tvpot' . '&amp;jsCallback=false&amp;wmode=transparent&amp;vid=' . $m[1] . '&amp;autoplay=false&amp;permitWideScreen=true';
                        $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen';
                        if (empty($mysize)) {
                            $attr .= ' width="500px" height="281px"';
                        } else {
                            $attr .= ' ' . $mysize;
                        }
                    }
                    $mediainfo = 'Daum movie';
                    $objclass = ' daum';
                } else {
                    if ($macro == 'vimeo' && preg_match("@^(\\d+)\$@", $media[$i], $m) || preg_match("@(?:https?:)?//(?:player\\.)?vimeo\\.com\\/(?:video/)?(.*)\$@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 = '//player.vimeo.com/video/' . $m[1] . '?portrait=0&color=333';
                            $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen';
                            if (empty($mysize)) {
                                $attr .= ' width="500px" height="281px"';
                            } else {
                                $attr .= ' ' . $mysize;
                            }
                        }
                        $mediainfo = 'Vimeo movie';
                        $objclass = ' vimeo';
                    } else {
                        if (($macro == 'niconico' || $macro == 'nicovideo') && preg_match("@((?:sm|nm)?\\d+)\$@i", $media[$i], $m) || preg_match("@(?:https?://(?:www|dic)\\.(?:nicovideo|nicozon)\\.(?:jp|net)/(?:v|watch)/)?((?:sm|nm)?\\d+)\$@i", $media[$i], $m)) {
                            $custom = '<script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/' . $m[1];
                            $size = '';
                            $qprefix = '?';
                            if ($mywidth > 0) {
                                $size .= '?w=' . intval($mywidth);
                                $qprefix = '&amp;';
                            }
                            if ($myheight > 0) {
                                $size .= $qprefix . 'h=' . intval($myheight);
                            }
                            $custom .= $size;
                            $custom .= '"></script>';
                            $attr = 'frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen';
                            $mediainfo = 'Niconico';
                            $objclass = ' niconico';
                        } 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}{$align}'><div>
<iframe class='external' 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 {
                if (isset($custom[0])) {
                    $out .= <<<OBJECT
<div class='externalObject{$objclass}'><div>
{$custom}
<div><a alt='{$myurl}' onclick='javascript:openExternal(this, "inline-block"); return false;'><span>[{$mediainfo}]</span></a></div></div></div>
OBJECT;
                } 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;
}
Beispiel #22
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>";
}
Beispiel #23
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;
}
Beispiel #24
0
function macro_Calendar($formatter, $value = "", $option = "")
{
    global $DBInfo;
    $date = !empty($_GET['date']) ? $_GET['date'] : '';
    $prev_tag = '&laquo;';
    $next_tag = '&raquo;';
    static $day_headings = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    $day_heading_length = 3;
    preg_match("/^(('|\")([^\\2]+)\\2)?,?((\\d{4})-?(\\d{2}))?,?\\s*([a-z, ]+)?\$/i", $value, $match);
    #print_r($match);
    /* GET argument has priority */
    $month = '';
    $year = '';
    if ($date) {
        preg_match("/^((\\d{4})-?(\\d{1,2}))\$/i", $date, $match2);
        $year = $match2[2];
        $month = $match2[3];
    } else {
        if (!empty($match[4])) {
            $year = $match[5];
            $month = $match[6];
        }
    }
    /* Validate date. Use system date, if date is not validated */
    if ($month < 1 || $month > 12) {
        $year = date('Y');
        $month = date('m');
    }
    $date = $year . $month;
    $month = intval($month);
    $year = intval($year);
    if (!empty($match[3])) {
        $pagename = $match[3];
    } else {
        $pagename = $formatter->page->name;
    }
    $urlpagename = _urlencode($pagename);
    $link_prefix = sprintf("%04d-%02d", $year, $month);
    $archives = array();
    $attr = '';
    $link = '';
    if (!empty($match[7])) {
        $args = explode(",", $match[7]);
        if (in_array("nolink", $args)) {
            $nolink = 1;
        }
        if (in_array("blog", $args)) {
            $mode = 'blog';
        }
        if (in_array("noweek", $args)) {
            $day_heading_length = 0;
        }
        if (in_array("center", $args)) {
            $attr = ' align="center"';
        }
        if (in_array("shortweek", $args)) {
            $day_heading_length = 1;
        }
        if (in_array("yearlink", $args)) {
            $yearlink = 1;
        }
        if (in_array("archive", $args)) {
            if (!empty($mode)) {
                // blog mode
                $archives = calendar_get_dates($formatter, $date, $pagename . '/' . $link_prefix);
            } else {
                $archives = calendar_get_dates($formatter, $date);
                $mode = 'archive';
            }
        }
    }
    $prev_month = date('Ym', mktime(0, 0, 0, $month - 1, 1, $year));
    $next_month = date('Ym', mktime(0, 0, 0, $month + 1, 1, $year));
    if (!empty($yearlink)) {
        $prev_year = date('Ym', mktime(0, 0, 0, $month, 1, $year - 1));
        $next_year = date('Ym', mktime(0, 0, 0, $month, 1, $year + 1));
        $year_prev_tag = '&laquo;';
        $year_next_tag = '&raquo;';
        $prev_tag = '&lsaquo;';
        $next_tag = '&rsaquo;';
    }
    $first_of_month = mktime(0, 0, 0, $month, 1, $year);
    #remember that mktime will automatically correct if invalid dates are entered
    # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
    # this provides a built in "rounding" feature to generate_calendar()
    # number of days in the month
    $maxdays = date('t', $first_of_month);
    # get info about the first day of the month
    $date_info = getdate($first_of_month);
    $month = $date_info['mon'];
    $year = $date_info['year'];
    $today = date("d");
    $calendar = "<table class=\"Calendar\"{$attr}>\n";
    #use the <caption> tag or just a normal table heading. Take your pick.
    #http://diveintomark.org/archives/2002/07/03.html#day_18_giving_your_calendar_a_real_caption
    #	$calendar .= "<tr><th colspan=\"7\" class=\"month\">$date_info[month], $year</th></tr>\n";
    ##	$calendar.= "<caption class=\"month\">$date_info[month], $year</caption>\n";
    $calendar .= "<caption class=\"month\">";
    /* Adding previous month and year */
    if (!empty($yearlink)) {
        $calendar .= $formatter->link_tag($link, "?date={$prev_year}", $year_prev_tag) . '&nbsp;&nbsp;';
    }
    $calendar .= $formatter->link_tag($link, "?date={$prev_month}", $prev_tag) . '&nbsp;&nbsp;';
    #$calendar.=substr($date_info[month],0,3).' '.$year;
    $calendar .= $date_info['month'] . ' ' . $year;
    /* Adding next month and year */
    $calendar .= '&nbsp;&nbsp;' . $formatter->link_tag($link, "?date={$next_month}", $next_tag);
    if (!empty($yearlink)) {
        $calendar .= '&nbsp;&nbsp;' . $formatter->link_tag($link, "?date={$next_year}", $year_next_tag);
    }
    $calendar .= "</caption>\n";
    # print the day headings "Mon", "Tue", etc.
    # if day_heading_length is 4, the full name of the day will be printed
    # otherwise, just the first n characters
    if ($day_heading_length > 0 and $day_heading_length <= 4) {
        $calendar .= '<tr>';
        foreach ($day_headings as $day_heading) {
            $calendar .= "<th abbr=\"{$day_heading}\" class=\"dayofweek\">" . ($day_heading_length != 4 ? substr($day_heading, 0, $day_heading_length) : $day_heading) . '</th>';
        }
        $calendar .= "</tr>\n";
    }
    $calendar .= '<tr>';
    $weekday = $date_info['wday'];
    #weekday (zero based) of the first day of the month
    $day = 1;
    #starting day of the month
    #take care of the first "empty" days of the month
    if ($weekday > 0) {
        $calendar .= "<td colspan=\"{$weekday}\">&nbsp;</td>";
    }
    #print the days of the month
    $action = '';
    if (!empty($mode) and $mode == 'blog') {
        $link = $urlpagename . "/{$link_prefix}";
        if (!$DBInfo->hasPage($link)) {
            $action = "?action=blog";
        }
    } else {
        if (!empty($mode)) {
            $link = $urlpagename;
        }
    }
    while ($day <= $maxdays) {
        if ($weekday == 7) {
            #start a new week
            $calendar .= "</tr>\n<tr>";
            $weekday = 0;
        }
        $daytext = $day;
        if ($day == $today and $month == date('m')) {
            $exists = 'today" bgcolor="white';
            $nonexists = 'today" bgcolor="white';
            $classes = $nonexists;
        } else {
            $exists = 'wiki';
            $nonexists = 'day" bgcolor="lightyellow';
            $classes = $nonexists;
        }
        if (empty($mode) and !isset($nolink)) {
            $link = $urlpagename . "/" . $link_prefix . "-" . sprintf("%02d", $day);
            if ($DBInfo->hasPage($link)) {
                $classes = $exists;
            }
        } else {
            if (!empty($mode)) {
                if (!empty($archives[$day])) {
                    $daytext = '<span class="blogged"><b>' . $day . '</b></span>';
                }
                if ($mode == 'archive') {
                    if (!empty($archives[$day])) {
                        if ($day < 10) {
                            $anchor = '#' . $date . '0' . $day;
                        } else {
                            $anchor = '#' . $date . $day;
                        }
                        $action = '?action=blogchanges&amp;date=' . $date . $anchor;
                        $classes = 'day';
                        $link = $urlpagename;
                    } else {
                        if ($day == $today) {
                            $link = $urlpagename;
                        } else {
                            $link = '';
                        }
                        $action = '?action=blog';
                    }
                } else {
                    if ($action[0] != '?') {
                        $action = sprintf("#%02d", $day);
                    }
                }
            }
        }
        $calendar .= '<td' . ($classes ? " class=\"{$classes}\">" : '>') . ($link ? $formatter->link_tag($link, $action, $daytext) : $daytext) . '</td>';
        $day++;
        $weekday++;
    }
    if ($weekday != 7) {
        $calendar .= '<td colspan="' . (7 - $weekday) . '">&nbsp;</td>';
    }
    return $calendar . "</tr>\n</table>\n";
}
Beispiel #25
0
function macro_FullSearch($formatter, $value = "", &$opts)
{
    global $DBInfo;
    $needle = $value;
    if ($value === true) {
        $needle = $value = $formatter->page->name;
        $options['noexpr'] = 1;
    } else {
        # for MoinMoin compatibility with [[FullSearch("blah blah")]]
        #$needle = preg_replace("/^('|\")([^\\1]*)\\1/","\\2",$value);
        $needle = $value;
    }
    // for pagination
    $offset = '';
    if (!empty($opts['offset']) and is_numeric($opts['offset'])) {
        if ($opts['offset'] > 0) {
            $offset = $opts['offset'];
        }
    }
    $url = $formatter->link_url($formatter->page->urlname);
    $fneedle = _html_escape($needle);
    $tooshort = !empty($DBInfo->fullsearch_tooshort) ? $DBInfo->fullsearch_tooshort : 2;
    $m1 = _("Display context of search results");
    $m2 = _("Search BackLinks only");
    $m3 = _("Case-sensitive searching");
    $msg = _("Go");
    $bchecked = !empty($DBInfo->use_backlinks) ? 'checked="checked"' : '';
    $form = <<<EOF
<form method='get' action='{$url}'>
   <input type='hidden' name='action' value='fullsearch' />
   <input name='value' size='30' value="{$fneedle}" />
   <span class='button'><input type='submit' class='button' value='{$msg}' /></span><br />
   <input type='checkbox' name='backlinks' value='1' {$bchecked} />{$m2}<br />
   <input type='checkbox' name='context' value='20' />{$m1}<br />
   <input type='checkbox' name='case' value='1' />{$m3}<br />
   </form>
EOF;
    if (!isset($needle[0]) or !empty($opts['form'])) {
        # or blah blah
        $opts['msg'] = _("No search text");
        return $form;
    }
    $opts['form'] = $form;
    # XXX
    $excl = array();
    $incl = array();
    if (!empty($opts['noexpr'])) {
        $tmp = preg_split("/\\s+/", $needle);
        $needle = $value = join('|', $tmp);
        $raw_needle = implode(' ', $tmp);
        $needle = preg_quote($needle);
    } else {
        if (empty($opts['backlinks'])) {
            $terms = preg_split('/((?<!\\S)[-+]?"[^"]+?"(?!\\S)|\\S+)/s', $needle, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
            $common_words = array('the', 'that', 'where', 'what', 'who', 'how', 'too', 'are');
            $common = array();
            foreach ($terms as $term) {
                if (trim($term) == '') {
                    continue;
                }
                if (preg_match('/^([-+]?)("?)([^\\2]+?)\\2$/', $term, $match)) {
                    $word = str_replace(array('\\', '.', '*'), '', $match[3]);
                    $len = strlen($word);
                    if (!$match[1] and $match[2] != '"') {
                        if ($len < $tooshort or in_array($word, $common_words)) {
                            $common[] = $word;
                            continue;
                        }
                    }
                    if ($match[1] == '-') {
                        $excl[] = $word;
                    } else {
                        $incl[] = $word;
                    }
                }
            }
            $needle = implode('|', $incl);
            $needle = _preg_search_escape($needle);
            $raw_needle = implode(' ', $incl);
            $test = validate_needle($needle);
            if ($test === false) {
                // invalid regex
                $tmp = array_map('preg_quote', $incl);
                $needle = implode('|', $tmp);
            }
            $excl_needle = implode('|', $excl);
            $test = validate_needle($excl_needle);
            if ($test2 === false) {
                // invalid regex
                $tmp = array_map('preg_quote', $excl);
                $excl_needle = implode('|', $tmp);
            }
        } else {
            $cneedle = _preg_search_escape($needle);
            $test = validate_needle($cneedle);
            if ($test === false) {
                $needle = preg_quote($needle);
            } else {
                $needle = $cneedle;
            }
        }
    }
    $test3 = trim($needle);
    if (!isset($test3[0])) {
        $opts['msg'] = _("Empty expression");
        return $form;
    }
    # set arena and sid
    if (!empty($opts['backlinks'])) {
        $arena = 'backlinks';
    } else {
        if (!empty($opts['keywords'])) {
            $arena = 'keywords';
        } else {
            $arena = 'fullsearch';
        }
    }
    if ($arena == 'fullsearch') {
        $sid = md5($value . 'v' . $offset);
    } else {
        $sid = $value;
    }
    $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0;
    # retrieve cache
    $fc = new Cache_text($arena);
    if (!$formatter->refresh and $fc->exists($sid)) {
        $data = $fc->fetch($sid);
        if (!empty($opts['backlinks'])) {
            // backlinks are not needed to check it.
            $hits = $data;
            // also fetch redirects
            $r = new Cache_Text('redirects');
            $redirects = $r->fetch($sid);
        } else {
            if (is_array($data)) {
                # check cache mtime
                $cmt = $fc->mtime($sid);
                # check update or not
                $dmt = $DBInfo->mtime();
                if ($dmt > $cmt + $delay) {
                    # XXX crude method
                    $data = array();
                } else {
                    # XXX smart but incomplete method
                    if (isset($data['hits'])) {
                        $hits =& $data['hits'];
                    } else {
                        $hits =& $data;
                    }
                    foreach ($hits as $p => $c) {
                        $mp = $DBInfo->getPage($p);
                        $mt = $mp->mtime();
                        if ($mt > $cmt + $delay) {
                            $data = array();
                            break;
                        }
                    }
                }
                if (isset($data['searched'])) {
                    extract($data);
                } else {
                    if (!empty($data)) {
                        $hits = $data;
                    }
                }
            }
        }
    }
    $pattern = '/' . $needle . '/';
    if (!empty($excl_needle)) {
        $excl_pattern = '/' . $excl_needle . '/';
    }
    if (!empty($opts['case'])) {
        $pattern .= "i";
        $excl_pattern .= "i";
    }
    if (isset($hits)) {
        if (in_array($arena, array('backlinks', 'keywords'))) {
            $test = key($hits);
            if (is_int($test) and $hits[$test] != -1) {
                // fix compatible issue for keywords, backlinks
                $hits = array_flip($hits);
                foreach ($hits as $k => $v) {
                    $hits[$k] = -1;
                }
                reset($hits);
            }
            // check invert redirect index
            if (!empty($redirects)) {
                $redirects = array_flip($redirects);
                ksort($redirects);
                foreach ($redirects as $k => $v) {
                    $hits[$k] = -2;
                }
                reset($hits);
            }
        }
        //continue;
    } else {
        $hits = array();
        set_time_limit(0);
        if (!empty($opts['backlinks']) and empty($DBInfo->use_backlink_search)) {
            $hits = array();
        } else {
            if (!empty($opts['keywords']) and empty($DBInfo->use_keyword_search)) {
                $hits = array();
            } else {
                if (!empty($opts['backlinks'])) {
                    $pages = $DBInfo->getPageLists();
                    #$opts['context']=-1; # turn off context-matching
                    $cache = new Cache_text("pagelinks");
                    foreach ($pages as $page_name) {
                        $links = $cache->fetch($page_name);
                        if (is_array($links)) {
                            if (in_array($value, $links)) {
                                $hits[$page_name] = -1;
                            }
                            // ignore count if < 0
                        }
                    }
                } else {
                    if (!empty($opts['keywords'])) {
                        $pages = $DBInfo->getPageLists();
                        $opts['context'] = -1;
                        # turn off context-matching
                        $cache = new Cache_text("keyword");
                        foreach ($pages as $page_name) {
                            $links = $cache->fetch($page_name);
                            // XXX
                            if (is_array($links)) {
                                if (stristr(implode(' ', $links), $needle)) {
                                    $hits[$page_name] = -1;
                                }
                                // ignore count if < 0
                            }
                        }
                    } else {
                        $params = array();
                        $ret = array();
                        $params['ret'] =& $ret;
                        $params['offset'] = $offset;
                        $params['search'] = 1;
                        $params['incl'] = $incl;
                        $params['excl'] = $excl;
                        $pages = $DBInfo->getPageLists($params);
                        // set time_limit
                        $mt = explode(' ', microtime());
                        $timestamp = $mt[0] + $mt[1];
                        $j = 0;
                        $time_limit = isset($DBInfo->process_time_limit) ? $DBInfo->process_time_limit : 3;
                        // default 3-seconds
                        $j = 0;
                        while (list($_, $page_name) = each($pages)) {
                            // check time_limit
                            if ($time_limit and $j % 30 == 0) {
                                $mt = explode(' ', microtime());
                                $now = $mt[0] + $mt[1];
                                if ($now - $timestamp > $time_limit) {
                                    break;
                                }
                            }
                            $j++;
                            $p = new WikiPage($page_name);
                            if (!$p->exists()) {
                                continue;
                            }
                            $body = $p->_get_raw_body();
                            #$count = count(preg_split($pattern, $body))-1;
                            $count = preg_match_all($pattern, $body, $matches);
                            if ($count) {
                                foreach ($excl as $ex) {
                                    if (stristr($body, $ex)) {
                                        continue;
                                    }
                                }
                                foreach ($incl as $in) {
                                    if (!stristr($body, $in)) {
                                        continue;
                                    }
                                }
                                $hits[$page_name] = $count;
                            }
                        }
                        $searched = $j > 0 ? $j : 0;
                        $offset = !empty($offset) ? $offset + $j : $j;
                    }
                }
            }
        }
        #krsort($hits);
        #ksort($hits);
        $name = array_keys($hits);
        array_multisort($hits, SORT_DESC, $name, SORT_ASC);
        if (in_array($arena, array('backlinks', 'keywords'))) {
            $fc->update($sid, $name);
        } else {
            $fc->update($sid, array('hits' => $hits, 'offset' => $offset, 'searched' => $searched));
        }
    }
    $opts['hits'] = $hits;
    $opts['hit'] = count($hits);
    $opts['all'] = $DBInfo->getCounter();
    if ($opts['all'] > $searched) {
        $opts['next'] = $offset;
        $opts['searched'] = $searched;
    }
    if (!empty($opts['call'])) {
        return $hits;
    }
    $out = "<!-- RESULT LIST START -->";
    // for search plugin
    $out .= "<ul class='fullsearchResult'>";
    $idx = 1;
    $checkbox = '';
    while (list($page_name, $count) = each($hits)) {
        $pgname = _html_escape($page_name);
        if (!empty($opts['checkbox'])) {
            $checkbox = "<input type='checkbox' name='pagenames[]' value=\"{$pgname}\" />";
        }
        $out .= '<!-- RESULT ITEM START -->';
        // for search plugin
        $out .= '<li>' . $checkbox . $formatter->link_tag(_rawurlencode($page_name), '?action=highlight&amp;value=' . _urlencode($value), $pgname, 'tabindex="' . $idx . '"');
        if ($count > 0) {
            $out .= ' . . . . ' . sprintf($count == 1 ? _("%d match") : _("%d matches"), $count);
        } else {
            if ($count == -2) {
                $out .= " <span class='redirectIcon'><span>" . _("Redirect page") . "</span></span>\n";
            }
        }
        if (!empty($opts['context']) and $opts['context'] > 0) {
            # search matching contexts
            $p = new WikiPage($page_name);
            if ($p->exists()) {
                $body = $p->_get_raw_body();
                $out .= find_needle($body, $needle, $excl_needle, $opts['context']);
            }
        }
        $out .= "</li>\n";
        $out .= '<!-- RESULT ITEM END -->';
        // for search plugin
        $idx++;
        #if ($idx > 50) break;
    }
    $out .= "</ul>\n";
    $out .= "<!-- RESULT LIST END -->";
    // for search plugin
    return $out;
}
Beispiel #26
0
function macro_VisualTour($formatter, $value, $options = array())
{
    global $DBInfo;
    putenv('GDFONTPATH=' . getcwd() . '/data');
    $dotcmd = "dot";
    #$dotcmd="twopi";
    #$dotcmd="neato";
    $maptype = 'imap';
    $maptype = 'cmap';
    if (!$formatter->page->exists()) {
        return "";
    }
    $args = explode(',', $value);
    $extra = '';
    foreach ($args as $arg) {
        $arg = trim($arg);
        if (($p = strpos($arg, '=')) === false) {
            if ($arg == 'show') {
                $extra .= '&t=show';
            } else {
                if (is_int($arg)) {
                    $w = $arg;
                } else {
                    if ($DBInfo->hasPage($arg)) {
                        $pgname = $arg;
                    }
                }
            }
        } else {
            $k = strtok($arg, '=');
            $v = strtok('');
            if ($k == 'width' or $k == 'w') {
                $w = (int) $v;
            } else {
                if ($k == 'depth' or $k == 'd') {
                    $d = (int) $v;
                } else {
                    if ($k == 'arena' or $k == 'a') {
                        $extra .= '&arena=' . $v;
                    }
                }
            }
        }
    }
    if (!empty($options['w']) and $options['w'] < 6) {
        $w = $options['w'];
    } else {
        $w = !empty($w) ? $w : 2;
    }
    if (!empty($options['d']) and $options['d'] < 6) {
        $d = $options['d'];
    } else {
        $d = !empty($d) ? $d : 3;
    }
    if (!empty($options['f'])) {
        $extra .= "&f=" . $options['f'];
    }
    if (!empty($options['arena'])) {
        $extra .= "&arena=" . $options['arena'];
    }
    if (isset($pgname[0])) {
        $urlname = _urlencode($pgname);
    } else {
        $urlname = $formatter->page->urlname;
        $pgname = $formatter->page->name;
    }
    $dot = $formatter->macro_repl('dot', $pgname, $options);
    if (!empty($DBInfo->cache_public_dir)) {
        $fc = new Cache_text('visualtour', array('dir' => $DBInfo->cache_public_dir));
        $fname = $fc->getKey($dot);
        $basename = $DBInfo->cache_public_dir . '/' . $fname;
        $dotfile = $basename . '.dot';
        $pngfile = $basename . '.png';
        $mapfile = $basename . '.map';
        $urlbase = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $fname : $DBInfo->url_prefix . '/' . $basename;
        $png_url = $urlbase . '.png';
        $map_url = $urlbase . '.map';
    } else {
        $md5sum = md5($dot);
        $cache_dir = $DBInfo->upload_dir . "/VisualTour";
        $cache_url = $DBInfo->upload_url ? $DBInfo->upload_url . '/VisualTour' : $DBInfo->url_prefix . '/' . $cache_dir;
        $basename = $cache_dir . '/' . $md5sum;
        $pngfile = $basename . '.png';
        $mapfile = $basename . '.map';
        $dotfile = $basename . '.dot';
        $urlbase = $cache_url . '/' . $md5sum;
        $png_url = $urlbase . '.png';
        $map_url = $urlbase . '.map';
    }
    if (!is_dir(dirname($pngfile))) {
        $om = umask(00);
        _mkdir_p(dirname($pngfile), 0777);
        umask($om);
    }
    $err = '';
    if ($formatter->refresh or !file_exists($dotfile)) {
        $fp = fopen($dotfile, "w");
        fwrite($fp, $dot);
        fclose($fp);
        $cmd = "{$dotcmd} -Tpng {$dotfile} -o {$pngfile}";
        $formatter->errlog('Dot');
        $fp = popen($cmd . $formatter->LOG, 'r');
        pclose($fp);
        $err = $formatter->get_errlog();
        $cmd = "{$dotcmd} -T{$maptype} {$dotfile} -o {$mapfile}";
        $formatter->errlog('Dot');
        $fp = popen($cmd . $formatter->LOG, 'r');
        pclose($fp);
        $err .= $formatter->get_errlog();
        if ($err) {
            $err = "<pre class='errlog'>{$err}</pre>\n";
        }
    }
    if ($maptype == 'imap') {
        $attr = ' ismap="ismap"';
        return $err . "<span class='VisualTour'><a href='{$map_url}'><img src='{$png_url}' alt='VisualTour'{$attr}></a></span>\n";
    } else {
        $attr = ' usemap="#mainmap"';
        $fp = fopen($mapfile, 'r');
        $map = '';
        if (is_resource($fp)) {
            while (!feof($fp)) {
                $map .= fgets($fp, 1024);
            }
            fclose($fp);
            $map = '<map name="mainmap">' . $map . '</map>';
        }
        return $err . "<span class='VisualTour'><img src='{$png_url}' alt='VisualTour'{$attr}>{$map}</span>\n";
    }
}
Beispiel #27
0
 function get_summary($blogs, $options)
 {
     global $DBInfo;
     if (!$blogs) {
         return array();
     }
     $date = !empty($options['date']) ? $options['date'] : '';
     if ($date) {
         // make a date pattern to grep blog entries
         $check = strlen($date);
         if ($check < 4 or !preg_match('/^\\d+/', $date)) {
             $date = date('Y\\-m');
         } else {
             if ($check == 6) {
                 $date = substr($date, 0, 4) . '\\-' . substr($date, 4);
             } else {
                 if ($check == 8) {
                     $date = substr($date, 0, 4) . '\\-' . substr($date, 4, 2) . '\\-' . substr($date, 6);
                 } else {
                     if ($check != 4) {
                         $date = date('Y\\-m');
                     }
                 }
             }
         }
         #print $date;
     } else {
         $date = '\\d{4}-\\d{2}-\\d{2}T';
     }
     $entries = array();
     $logs = array();
     foreach ($blogs as $blog) {
         $pagename = $DBInfo->keyToPagename($blog);
         $pageurl = _urlencode($pagename);
         $page = $DBInfo->getPage($pagename);
         $raw = $page->get_raw_body();
         $temp = explode("\n", $raw);
         $summary = '';
         foreach ($temp as $line) {
             if (empty($state)) {
                 if (preg_match("/^({{{)?#!blog\\s(.*)\\s({$date}" . "[^ ]+)\\s?(.*)?\$/", $line, $match)) {
                     $entry = array($pageurl, $match[2], $match[3], $match[4]);
                     if ($match[1]) {
                         $endtag = '}}}';
                     }
                     $state = 1;
                     $commentcount = 0;
                 }
                 continue;
             }
             if (preg_match("/^{$endtag}\$/", $line)) {
                 $state = 0;
                 $comments = '';
                 if (preg_match("/----\n/", $summary)) {
                     list($content, $comments) = explode("----\n", $summary, 2);
                 } else {
                     $content = $summary;
                 }
                 $entry[] = $content;
                 $commentcount = 0;
                 if ($comments and empty($options['noaction'])) {
                     $commentcount = sizeof(explode("----\n", $comments));
                 }
                 $entry[] = $commentcount;
                 $entries[] = $entry;
                 $summary = '';
                 continue;
             }
             $summary .= $line . "\n";
         }
     }
     return $entries;
 }
Beispiel #28
0
function macro_FastSearch($formatter, $value = "", &$opts)
{
    global $DBInfo;
    $default_limit = isset($DBInfo->fastsearch_limit) ? $DBInfo->fastsearch_limit : 30;
    if ($value === true) {
        $needle = $value = $formatter->page->name;
    } else {
        # for MoinMoin compatibility with [[FullSearch("blah blah")]]
        $needle = $value = preg_replace("/^('|\")([^\\1]*)\\1/", "\\2", $value);
    }
    $needle = _preg_search_escape($needle);
    $pattern = '/' . $needle . '/i';
    $fneedle = str_replace('"', "&#34;", $needle);
    # XXX
    $url = $formatter->link_url($formatter->page->urlname);
    $arena = 'fullsearch';
    $check1 = 'checked="checked"';
    $check2 = $check3 = '';
    if (in_array($opts['arena'], array('titlesearch', 'fullsearch', 'pagelinks'))) {
        $check1 = '';
        $arena = $opts['arena'];
        if ($arena == 'fullsearch') {
            $check1 = 'checked="checked"';
        } else {
            if ($arena == 'titlesearch') {
                $check2 = 'checked="checked"';
            } else {
                $check3 = 'checked="checked"';
            }
        }
    }
    if (!empty($opts['backlinks'])) {
        $arena = 'pagelinks';
        $check1 = '';
        $check3 = 'checked="checked"';
    }
    $msg = _("Fast search");
    $msg2 = _("Display context of search results");
    $msg3 = _("Full text search");
    $msg4 = _("Title search");
    $msg5 = _("Link search");
    $form = <<<EOF
<form method='get' action='{$url}'>
   <input type='hidden' name='action' value='fastsearch' />
   <input name='value' size='30' value='{$fneedle}' />
   <span class='button'><input type='submit' class='button' value='{$msg}' /></span><br />
   <input type='checkbox' name='context' value='20' />{$msg2}<br />
   <input type='radio' name='arena' value='fullsearch' {$check1} />{$msg3}
   <input type='radio' name='arena' value='titlesearch' {$check2} />{$msg4}
   <input type='radio' name='arena' value='pagelinks' {$check3} />{$msg5}<br />
   </form>
EOF;
    if (!isset($needle[0]) or !empty($opts['form'])) {
        # or blah blah
        $opts['msg'] = _("No search text");
        return $form;
    } else {
        if (validate_needle($needle) === false) {
            $opts['msg'] = sprintf(_("Invalid search expression \"%s\""), $needle);
            return $form;
        }
    }
    $DB = new Indexer_dba($arena, "r", $DBInfo->dba_type);
    if ($DB->db == null) {
        $opts['msg'] = _("Couldn't open search database, sorry.");
        $opts['hits'] = array();
        $opts['hit'] = 0;
        $opts['all'] = 0;
        return '';
    }
    $opts['form'] = $form;
    $sc = new Cache_text("searchkey");
    if ($arena == "pagelinks") {
        $words = array($value);
    } else {
        $words = getTokens($value);
    }
    // $words=explode(' ', strtolower($value));
    $idx = array();
    $new_words = array();
    foreach ($words as $word) {
        if ($sc->exists($word)) {
            $searchkeys = $sc->fetch($word);
        } else {
            $searchkeys = $DB->_search($word);
            $sc->update($word, $searchkeys);
        }
        $new_words = array_merge($new_words, $searchkeys);
        $new_words = array_merge($idx, $DB->_search($word));
    }
    $words = array_merge($words, $new_words);
    //
    $word = array_shift($words);
    $idx = $DB->_fetchValues($word);
    foreach ($words as $word) {
        $ids = $DB->_fetchValues($word);
        // FIXME
        foreach ($ids as $id) {
            $idx[] = $id;
        }
    }
    $init_hits = array_count_values($idx);
    // initial hits
    $idx = array_keys($init_hits);
    //arsort($idx);
    $all_count = $DBInfo->getCounter();
    $pages = array();
    $hits = array();
    foreach ($idx as $id) {
        $key = $DB->_fetch($id);
        $pages[$id] = $key;
        $hits['_' . $key] = $init_hits[$id];
        // HACK. prefix '_' to numerical named pages
    }
    $DB->close();
    if (!empty($_GET['q']) and isset($_GET['q'][0])) {
        return $pages;
    }
    $context = !empty($opts['context']) ? $opts['context'] : 0;
    $limit = isset($opts['limit'][0]) ? $opts['limit'] : $default_limit;
    $contexts = array();
    if ($arena == 'fullsearch' || $arena == 'pagelinks') {
        $idx = 1;
        foreach ($pages as $page_name) {
            if (!empty($limit) and $idx > $limit) {
                break;
            }
            $p = new WikiPage($page_name);
            if (!$p->exists()) {
                continue;
            }
            $body = $p->_get_raw_body();
            $count = preg_match_all($pattern, $body, $matches);
            // more precisely count matches
            if ($context) {
                # search matching contexts
                $contexts[$page_name] = find_needle($body, $needle, '', $context);
            }
            $hits['_' . $page_name] = $count;
            // XXX hack for numerical named pages
            $idx++;
        }
    }
    //uasort($hits, 'strcasecmp');
    //$order = 0;
    //uasort($hits, create_function('$a, $b', 'return ' . ($order ? '' : '-') . '(strcasecmp($a, $b));'));
    $name = array_keys($hits);
    array_multisort($hits, SORT_DESC, $name, SORT_ASC);
    $opts['hits'] = $hits;
    $opts['hit'] = count($hits);
    $opts['all'] = $all_count;
    if (!empty($opts['call'])) {
        return $hits;
    }
    $out = "<!-- RESULT LIST START -->";
    // for search plugin
    $out .= "<ul>";
    $idx = 1;
    while (list($page_name, $count) = each($hits)) {
        $page_name = substr($page_name, 1);
        $out .= '<!-- RESULT ITEM START -->';
        // for search plugin
        $out .= '<li>' . $formatter->link_tag(_rawurlencode($page_name), "?action=highlight&amp;value=" . _urlencode($needle), $page_name, "tabindex='{$idx}'");
        if ($count > 1) {
            $out .= ' . . . . ' . sprintf($count == 1 ? _("%d match") : _("%d matches"), $count);
            if (!empty($contexts[$page_name])) {
                $out .= $contexts[$page_name];
            }
        }
        $out .= "</li>\n";
        $out .= '<!-- RESULT ITEM END -->';
        // for search plugin
        $idx++;
        if (!empty($limit) and $idx > $limit) {
            break;
        }
    }
    $out .= "</ul>\n";
    $out .= "<!-- RESULT LIST END -->";
    // for search plugin
    return $out;
}
Beispiel #29
0
function generate_item($formatter, $log)
{
    global $DBInfo;
    list($page, $user, $date, $title, $summary) = $log;
    if (!$title) {
        return "";
    }
    $url = qualifiedUrl($formatter->link_url(_urlencode($page)));
    /* perma link */
    $tag = md5($user . ' ' . $date . ' ' . $title);
    /* RFC 822 date format for RSS 2.0 */
    $date[10] = ' ';
    $pubDate = gmdate('D, j M Y H:i:s T', strtotime(substr($date, 0, 19) . ' GMT'));
    /* description */
    if ($summary) {
        $p = new WikiPage($page);
        $f = new Formatter($p);
        $summary = str_replace('\\}}}', '}}}', $summary);
        ob_start();
        $f->send_page($summary, array('fixpath' => 1, 'nojavascript' => 1));
        $description = '<description><![CDATA[' . ob_get_contents() . ']]></description>';
        ob_end_clean();
    }
    /* convert special characters into HTML entities */
    $title = htmlspecialchars($title);
    return <<<ITEM
<item>
  <title>{$title}</title>
  <link>{$url}#{$tag}</link>
  <guid isPermaLink="true">{$url}#{$tag}</guid>
  {$description}
  <pubDate>{$pubDate}</pubDate>
  <author>{$user}</author>
  <category domain="{$url}">{$page}</category>
  <comments><![CDATA[{$url}?action=blog&value={$tag}#BlogComment]]></comments>
</item>

ITEM;
}
Beispiel #30
0
function macro_SlideShow($formatter, $value = '', $options = array())
{
    global $DBInfo;
    $depth = 2;
    // default depth
    if (!empty($options['d'])) {
        $depth = intval($options['d']);
    }
    $args = explode(',', $value);
    $sz = sizeof($args);
    for ($i = 0, $sz = sizeof($args); $i < $sz; $i++) {
        if (($p = strpos($args[$i], '=')) !== false) {
            $k = substr($args[$i], 0, $p);
            $v = substr($args[$i], $p + 1);
            if ($k == 'depth' or $k == 'dep') {
                $depth = intval($v);
            }
        } else {
            $pgname = $args[$i];
        }
    }
    if ($pgname) {
        if (!$DBInfo->hasPage($pgname)) {
            return '[[SlideShow(' . _("No page found") . ')]]';
        }
        $pg = $DBInfo->getPage($pgname);
        $sections = _get_sections($pg->get_raw_body(), $depth);
        $urlname = _urlencode($pgname);
    } else {
        $sections = _get_sections($formatter->page->get_raw_body(), $depth);
        $urlname = $formatter->page->urlname;
    }
    if (!empty($options['p'])) {
        list($sect, $dum) = explode('/', $options['p']);
        $sect = abs(intval($sect));
        $sect = $sect ? $sect : 1;
    } else {
        $sect = 1;
    }
    $act = !empty($options['action']) ? $options['action'] : 'SlideShow';
    $iconset = 'bluecurve';
    $icon_dir = $formatter->imgs_dir . '/plugin/SlideShow/' . $iconset . '/';
    // get head title section
    if ($depth == 2) {
        list($secthead, $dumm) = explode("\n", $sections[0]);
        preg_match('/^\\s*=\\s*([^=].*[^=])\\s*=\\s?$/', $secthead, $match);
        $secthead = rtrim($sections[0]);
        if (isset($match[1])) {
            $title = $match[1];
        }
    } else {
        $dep = '&amp;d=' . $depth;
    }
    $sz = sizeof($sections);
    // $sections[0]
    $sz--;
    //if (trim($sections[$sz-1])=='') $sz--;
    //print $sections[0];
    //print_r($sections);
    if ($sect > $sz) {
        $sect = $sz;
    }
    // get prev,next subtitle
    if ($sz > $sect) {
        list($n_title, $dumm) = explode("\n", $sections[$sect + 1]);
        preg_match("/^\\s*={" . $depth . '}\\s*(.*)\\s*={' . $depth . '}\\s?$/', $n_title, $match);
        if (isset($match[1])) {
            $n_title = $match[1];
        } else {
            $n_title = '';
        }
        list($e_title, $dumm) = explode("\n", $sections[$sz]);
        preg_match("/^[ ]*={" . $depth . "}\\s+(.*)\\s+={" . $depth . "}\\s?/", $e_title, $match);
        if (isset($match[1])) {
            $e_title = $match[1];
        } else {
            $e_title = '';
        }
    }
    $s_title = '';
    if (!empty($sections[1]) and (empty($options['action']) or $sect > 1)) {
        list($s_title, $dumm) = explode("\n", $sections[1]);
        preg_match("/^\\s*={" . $depth . "}\\s*(.*)\\s*={" . $depth . "}\\s?\$/", $s_title, $match);
        if (isset($match[1])) {
            $s_title = $match[1];
        }
    }
    if ($sect >= 1) {
        list($p_title, $dumm) = explode("\n", $sections[$sect - 1]);
        preg_match('/^\\s*={' . $depth . '}\\s*(.*)\\s*={' . $depth . '}\\s?$/', $p_title, $match);
        if (isset($match[1])) {
            $p_title = $match[1];
        } else {
            $p_title = '';
        }
    }
    // make link icons
    if (!empty($s_title) or empty($options['action'])) {
        $slink = $formatter->link_url($urlname, '?action=' . $act . $dep . '&amp;p=1');
        $icon = !empty($options['action']) ? 'start' : 'next';
        $start = '<a href="' . $slink . '" title="' . _("Start:") . ' ' . $s_title . '">' . '<img src="' . $icon_dir . $icon . '.png' . '" style="border:0" alt="&lt;|" /></a>';
    } else {
        $start = '<img src="' . $icon_dir . 'start_off.png' . '" style="border:0" alt="&lt;|" /></a>';
    }
    if (!empty($e_title) and !empty($options['action'])) {
        $elink = $formatter->link_url($urlname, '?action=' . $act . $dep . '&amp;p=' . $sz);
        $end = '<a href="' . $elink . '" title="' . _("End:") . ' ' . $e_title . '">' . '<img src="' . $icon_dir . 'end.png' . '" style="border:0" alt="|>" /></a>';
    } else {
        $end = '<img src="' . $icon_dir . 'end_off.png' . '" style="border:0" alt="|>" /></a>';
    }
    $np = '';
    if (!empty($n_title) and !empty($options['action'])) {
        $np = $sect + 1;
        $nlink = $formatter->link_url($urlname, '?action=' . $act . $dep . '&amp;p=' . ($sect + 1));
        $next = '<a href="' . $nlink . '" title="' . _("Next:") . ' ' . $n_title . '">' . '<img src="' . $icon_dir . 'next.png' . '" style="border:0" alt=">" /></a>';
    } else {
        $next = '<img src="' . $icon_dir . 'next_off.png' . '" style="border:0" alt=">" /></a>';
    }
    $pp = '';
    if (!empty($p_title)) {
        $pp = $sect - 1;
        $plink = $formatter->link_url($urlname, '?action=' . $act . $dep . '&amp;p=' . ($sect - 1));
        $prev = '<a href="' . $plink . '" title="' . _("Prev:") . ' ' . $p_title . '">' . '<img src="' . $icon_dir . 'prev.png' . '" style="border:0" alt="<" /></a>';
    } else {
        $prev = '<img src="' . $icon_dir . 'prev_off.png' . '" style="border:0" alt="<" /></a>';
    }
    $rlink = $formatter->link_url($urlname, '?action=show');
    $return = '<a href="' . $rlink . '" title="' . _("Return") . ' ' . $pgname . '">' . '<img src="' . $icon_dir . 'up.png' . '" style="border:0" alt="^" /></a>';
    if (!empty($options['action'])) {
        $form0 = '<form method="post" onsubmit="return false" action="' . $rlink . '">';
        $form0 .= '<input type="hidden" name="d" value="' . $depth . '" />';
        $form0 .= '<input type="hidden" name="action" value="slideshow" />';
        $form = '<span class="slideShow" style="vertical-align:bottom;">' . '<input style="text-align:center" type="text" name="p" value="' . $sect . '/' . $sz . '" onkeypress="slideshowhandler(event,this,' . "'{$rlink}','{$pp}','{$np}')" . '" /></span>';
        $form1 = "</form>\n";
        return array($sections, "{$form0}{$return}{$start}{$prev}{$form}{$next}{$end}{$form1}\n");
    }
    return "{$return}{$start}";
}