Ejemplo n.º 1
0
function processor_pic($formatter, $value = "")
{
    global $DBInfo;
    $GROFF = "groff -e -p -ms -Tps ";
    $CONVERT = "convert -transparent white -density 120x120 -crop 0x0 -trim ";
    $vartmp_dir =& $DBInfo->vartmp_dir;
    if (getenv("OS") == "Windows_NT") {
        $NULL = 'NUL';
        $vartmp_dir = getenv('TEMP');
        #$convert="wconvert";
    }
    $cache_dir = $DBInfo->upload_dir . "/PIC";
    $cache_url = !empty($DBInfo->upload_url) ? $DBInfo->upload_url . '/PIC' : $DBInfo->url_prefix . '/' . $cache_dir;
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    $pic_script = $value;
    # print "<pre>$pic_script</pre>";
    $uniq = md5($pic_script);
    if ($DBInfo->cache_public_dir) {
        $fc = new Cache_text('pic', array('ext' => 'png', 'dir' => $DBInfo->cache_public_dir));
        $pngname = $fc->getKey($uniq, false);
        $outpath_png = $DBInfo->cache_public_dir . '/' . $pngname;
        $png_url = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $outpath_png;
    } else {
        $outpath_png = $cache_dir . '/' . $uniq . '.png';
        $png_url = $cache_url . '/' . $uniq . '.png';
    }
    $outpath_pic = "{$vartmp_dir}/{$uniq}.pic";
    $outpath_ps = "{$vartmp_dir}/{$uniq}.ps";
    if (!file_exists(dirname($outpath_png))) {
        umask(00);
        _mkdir_p(dirname($outpath_png), 0777);
        umask(022);
    }
    if ($formatter->refresh || !file_exists($outpath_png)) {
        # write to pic script file
        $ifp = fopen("{$outpath_pic}", "w");
        fwrite($ifp, $pic_script);
        fclose($ifp);
        # convert processing
        $fp = popen("{$GROFF} {$outpath_pic} >{$outpath_ps}" . $formatter->NULL, 'r');
        pclose($fp);
        $fp = popen("{$CONVERT} {$outpath_ps} {$outpath_png}" . $formatter->NULL, 'r');
        pclose($fp);
        # delete temporary files
        unlink($outpath_ps);
        unlink($outpath_pic);
    }
    return "<img class='tex' src='{$png_url}' alt='pic' />";
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
0
function processor_gnuplot($formatter = "", $value = "")
{
    global $DBInfo;
    $convert = "convert";
    if (getenv("OS") == "Windows_NT") {
        $gnuplot = "wgnuplot";
    } else {
        $gnuplot = "gnuplot";
    }
    $vartmp_dir =& $DBInfo->vartmp_dir;
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    if (strpos($line, ' ') !== false) {
        list($dum, $szarg) = explode(' ', $line);
        $args = explode('x', $szarg, 2);
        if (count($args) > 2) {
            $xsize = max(intval($args[0]), 50);
            $ysize = max(intval($args[1]), 50);
        }
        $value = '#' . $line . "\n" . $value;
    }
    #$term='dumb'; // for w3m,lynx
    $term = 'png';
    if ($term == 'png') {
        $ext = 'png';
    } else {
        if ($term == 'dumb') {
            $ext = 'txt';
        }
    }
    $default_size = "set size 0.5,0.6";
    $body = $plt = $value;
    while ($body and $body[0] == '#') {
        # extract first line
        list($line, $body) = explode("\n", $body, 2);
        # skip comments (lines with two hash marks)
        if ($line[1] == '#') {
            continue;
        }
        # parse the PI
        list($verb, $arg) = explode(' ', $line, 2);
        $verb = strtolower($verb);
        $arg = rtrim($arg);
        if (in_array($verb, array('#size'))) {
            $args = explode('x', $arg, 2);
            $xsize = intval($args[0]);
            $ysize = intval($args[1]);
        }
    }
    if (!empty($xsize)) {
        if ($xsize > 640 or $xsize < 100) {
            $xscale = 0.5;
        }
        if ($xscale and ($ysize > 480 or $ysize < 100)) {
            $yscale = 0.6;
        }
        $xscale = $xsize / 640.0;
        if (empty($yscale)) {
            $yscale = $xscale / 0.5 * 0.6;
        }
        $size = 'set size ' . $xscale . ',' . $yscale;
    } else {
        $size = $default_size;
    }
    # a sample for testing
    #  $plt='
    #set term gif
    #!  ls
    #plot sin(x)
    #';
    # normalize plt
    $plt = str_replace("\r\n", "\n", $plt);
    $plt = "\n" . $plt . "\n";
    $plt = preg_replace("/\n\\s*![^\n]+\n/", "\n", $plt);
    # strip shell commands
    $plt = preg_replace("/[ ]+/", " ", $plt);
    preg_match("/\nset?\\s+(t|te|ter|term)\\s(.*)\n/", $plt, $tmatch);
    $plt = preg_replace("/\nset?\\s+(t|o|si).*\n/", "\n", $plt);
    $plt = preg_replace("/system/", "", $plt);
    # strip system() function
    #
    $plt = preg_replace("/('|\")<(\\s*)/", "\\1\\2", $plt);
    # strip all redirection mark
    #print "<pre>$plt</pre>";
    if ($tmatch) {
        if (preg_match('/^postscript\\s*(enhanced|color)?/', $tmatch[2])) {
            // XXX
            $term = $tmatch[2];
            $ext = 'ps';
            $size = '#set term ' . $term;
        } else {
            if (preg_match('/^svg/', $tmatch[2])) {
                $term = $tmatch[2];
                $ext = 'svg';
                $size = "set size 1.0,1.0\n#set term " . $term;
            }
        }
    }
    if ($term != 'dumb') {
        $plt = "\n" . $size . "\n" . $plt;
    }
    $uniq = md5($plt);
    if ($DBInfo->cache_public_dir) {
        $fc = new Cache_text('gnuplot', array('ext' => $ext, 'dir' => $DBInfo->cache_public_dir));
        $pngname = $fc->getKey($uniq, false);
        $png = $DBInfo->cache_public_dir . '/' . $pngname;
        $png_url = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $png;
        $cache_dir = $DBInfo->cache_public_dir;
    } else {
        $cache_dir = $DBInfo->upload_dir . "/GnuPlot";
        $cache_url = $DBInfo->upload_url ? $DBInfo->upload_url . '/GnuPlot' : $DBInfo->url_prefix . '/' . $cache_dir;
        $png = $cache_dir . '/' . $uniq . ".{$ext}";
        $png_url = $cache_url . '/' . $uniq . ".{$ext}";
    }
    $outpath =& $png;
    $src = "\nset term {$term}\nset out '{$outpath}'\n{$plt}\n";
    if (!is_dir(dirname($png))) {
        $om = umask(00);
        _mkdir_p(dirname($png), 0777);
        umask($om);
    }
    $log = '';
    if ($formatter->refresh || !file_exists($outpath)) {
        $flog = tempnam($vartmp_dir, "GNUPLOT");
        #
        # for Win32 wgnuplot.exe
        #
        if (getenv("OS") == "Windows_NT") {
            $finp = tempnam($vartmp_dir, "GNUPLOT");
            $ifp = fopen($finp, "w");
            fwrite($ifp, $src);
            fclose($ifp);
            $cmd = "{$gnuplot} \"{$finp}\" > {$flog}";
            $fp = system($cmd);
            $log = join(file($flog), "");
            if (file_exists($outpath)) {
                unlink($flog);
                unlink($finp);
            } else {
                print "<font color='red'>ERROR:</font> Gnuplot does not work correctly";
            }
        } else {
            #
            # Unix
            #
            $cmd = $gnuplot;
            $formatter->errlog('GnuPlot');
            $fp = popen($cmd . $formatter->LOG, "w");
            if (is_resource($fp)) {
                fwrite($fp, $src);
                pclose($fp);
            }
            $log = $formatter->get_errlog();
            if (filesize($outpath) == 0) {
                $log .= "\n<font color='red'>ERROR:</font> Gnuplot does not work correctly";
                unlink($outpath);
            }
        }
        if ($log) {
            $log = "<pre class='errlog'>{$log}</pre>\n";
        }
    }
    $rext = $ext;
    $rpng_url = $png_url;
    if ($ext == 'ps' and file_exists($outpath)) {
        $routpath = preg_replace('/\\.' . $ext . '$/', '.png', $outpath);
        if ($formatter->refresh || !file_exists($routpath)) {
            $cmd = "{$convert} -rotate 90 {$outpath} {$routpath}";
            $fp = popen($cmd . $formatter->NULL, 'r');
            pclose($fp);
        }
        $rpng_url = preg_replace('/\\.' . $ext . '$/', '.png', $png_url);
        $rext = 'png';
    } else {
        if ($ext == 'svg') {
            $fp = fopen($outpath, 'r');
            if ($fp) {
                $svg = fread($fp, filesize($outpath));
                fclose($fp);
                $svg = preg_replace('/<svg [^>]+>/', '<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">', $svg);
                $fp = fopen($outpath, 'w');
                if ($fp) {
                    fwrite($fp, $svg);
                    fclose($fp);
                }
            }
        }
    }
    $bra = '';
    $ket = '';
    if ($ext == 'ps') {
        $bra = '<a href="' . $png_url . '" />';
        $ket = '</a>';
    }
    if (!file_exists($outpath)) {
        return $log;
    }
    if ($rext == 'png') {
        return $log . $bra . "<img src='{$rpng_url}' alt='gnuplot' style='border:0' />" . $ket;
    }
    if ($rext == 'svg') {
        return $log . $bra . "<embed src='{$rpng_url}' alt='gnuplot' width='640' height='480' />" . $ket;
    }
    if ($rext == 'txt') {
        return $log . '<pre class="gnuplot">' . implode('', file("{$cache_dir}/{$pngname}")) . '</pre>';
    }
}
Ejemplo n.º 5
0
function processor_latex(&$formatter, $value = "", $options = array())
{
    global $DBInfo;
    if (empty($formatter->latex_uniq)) {
        $formatter->latex_all = '';
        $formatter->latex_uniq = array();
    }
    $latex_convert_options = !empty($DBInfo->latex_convert_options) ? $DBInfo->latex_convert_options : "-trim -crop 0x0 -density 120x120";
    $raw_mode = isset($options['retval']) ? 1 : 0;
    # site spesific variables
    $latex = "latex";
    $dvicmd = "dvipng";
    $dviopt = '-D 120 -gamma 1.3';
    $convert = "convert";
    $mogrify = "mogrify";
    $vartmp_dir =& $DBInfo->vartmp_dir;
    $cache_dir = $DBInfo->upload_dir . "/LaTeX";
    $cache_url = !empty($DBInfo->upload_url) ? $DBInfo->upload_url . '/LaTeX' : $DBInfo->url_prefix . '/' . $cache_dir;
    $option = '-interaction=batchmode ';
    $mask = '';
    $options['dpi'] = intval($options['dpi']);
    if (preg_match('/ps$/', $dvicmd)) {
        $tmpext = 'ps';
        $dviopt = '-D 300';
        if (!empty($options['dpi'])) {
            $latex_convert_options .= ' -density ' . $options['dpi'] . 'x' . $options['dpi'];
        }
    } else {
        $tmpext = 'png';
        $mask = '-%d';
        if (!empty($options['dpi'])) {
            $dviopt = preg_replace('/-D 120/', '', $dviopt);
            $dviopt .= ' -D ' . $options['dpi'];
        }
    }
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    if (!$value) {
        if (empty($DBInfo->latex_allinone)) {
            return '';
        }
    }
    $tex = $value;
    if (!empty($DBInfo->latex_renumbering)) {
        $GLOBALS['_latex_eq_num'] = !empty($formatter->latex_num) ? $formatter->latex_num : 0;
        // renumbering
        //  just remove numbers and use \\tag{num}
        $ntex = preg_replace_callback('/\\\\begin\\{\\s*(equation)\\s*\\}((.|\\n)+)\\\\end\\{\\s*\\1\\s*\\}/', '_latex_renumber', $tex);
        #print '<pre>'.$ntex.'</pre>';
        if ($tex != $ntex) {
            $tex = $ntex;
        }
        $formatter->latex_num = $GLOBALS['_latex_eq_num'];
        // save
    } else {
        if (!$raw_mode and !empty($DBInfo->latex_allinone)) {
            $chunks = preg_split('/(\\\\begin\\{\\s*(?:equation)\\s*\\}(?:(?:.|\\n)+)\\\\end\\{\\s*\\1\\s*\\})/', $tex, -1, PREG_SPLIT_DELIM_CAPTURE);
            if (($sz = count($chunks)) > 0) {
                $ntex = '';
                for ($i = 1; $i < $sz; $i += 2) {
                    $ntex .= $chunks[$i - 1];
                    preg_match('/\\\\begin\\{\\s*(equation)\\s*\\}((.|\\n)+)\\\\end\\{\\s*\\1\\s*\\}/', $chunks[$i], $m);
                    $ntex .= _latex_renumber(array('', $m[1], $m[2]), "\n%%");
                }
                $tex = $ntex;
            }
            #print '<pre>'.$ntex.'</pre>';
        }
    }
    if (!empty($DBInfo->latex_template) and file_exists($DBInfo->data_dir . '/' . $DBInfo->latex_template)) {
        $templ = implode('', file($DBInfo->data_dir . '/' . $DBInfo->latex_template));
    } else {
        $head = !empty($DBInfo->latex_header) ? $DBInfo->latex_header : '';
        $templ = "\\documentclass[10pt,notitlepage]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{amsfonts}{$head}\n%%\\usepackage[all]{xy}\n\\pagestyle{empty}\n\\begin{document}\n@TEX@\n\\end{document}\n%%{$dviopt}\n%%{$latex_convert_options}\n";
    }
    $src = str_replace('@TEX@', $tex, $templ);
    $uniq = $tex ? md5($src) : $formatter->latex_uniq[sizeof($formatter->latex_uniq) - 1];
    // check image file exists
    if (empty($raw_mode) and !empty($DBInfo->latex_allinone) and $tex) {
        $formatter->latex_uniq[] = $uniq;
        $formatter->latex_all .= $tex . "\n\\pagebreak\n\n";
        #print '<pre>'.$tex.'</pre>';
    }
    if (!empty($DBInfo->cache_public_dir)) {
        $fc = new Cache_text('latex', array('ext' => 'png', 'dir' => $DBInfo->cache_public_dir));
        $pngname = $fc->getKey($uniq, false);
        $png = $DBInfo->cache_public_dir . '/' . $pngname;
        $png_url = !empty($DBInfo->cache_public_url) ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $png;
    } else {
        $png = $cache_dir . '/' . $uniq . '.png';
        $png_url = $cache_url . '/' . $uniq . '.png';
    }
    if (!is_dir(dirname($png))) {
        $om = umask(00);
        _mkdir_p(dirname($png), 0777);
        umask($om);
    }
    $NULL = '/dev/null';
    if (getenv("OS") == "Windows_NT") {
        $NULL = 'NUL';
        $vartmp_dir = getenv('TEMP');
        #$convert="wconvert";
    }
    $bra = '';
    $ket = '';
    if (!empty($formatter->preview) and empty($DBInfo->latex_allinone)) {
        $bra = '<span class="previewTex"><input type="checkbox" class="previewTex" name="_tex_' . $uniq . '" />';
        $ket = '</span>';
    }
    $img_exists = file_exists($png);
    $log = '';
    while (!empty($formatter->preview) || !empty($formatter->refresh) || !$img_exists) {
        //if ($options['_tex_'.$uniq] || $formatter->refresh || !file_exists($png)) {
        if (empty($raw_mode) and !empty($DBInfo->latex_allinone)) {
            if (empty($value)) {
                #$js= '<script type="text/javascript" src="'.$DBInfo->url_prefix.'/local/latex.js"></script>';
                if ($formatter->register_javascripts('latex.js')) {
                }
                $src = str_replace('@TEX@', $formatter->latex_all, $templ);
                #print '<pre>'.$src.'</pre>';
                $uniq = md5($src);
            } else {
                $formatter->postamble['latex'] = 'processor:latex:';
                break;
            }
        }
        $fp = fopen($vartmp_dir . "/{$uniq}.tex", "w");
        fwrite($fp, $src);
        fclose($fp);
        $outpath =& $png;
        # Unix specific FIXME
        $cwd = getcwd();
        chdir($vartmp_dir);
        $formatter->errlog('Dum', $uniq . '.log');
        $cmd = "{$latex} {$option} {$uniq}.tex >{$NULL}";
        $fp = popen($cmd . $formatter->NULL, 'r');
        pclose($fp);
        $log = $formatter->get_errlog(1, 1);
        if ($log) {
            #list($dum,$log,$dum2)=preg_split('/\n!/',$log,3);
            if (($p = strpos($log, "\n!")) !== FALSE) {
                $log = substr($log, $p);
                $log = "<pre class='errlog'>" . $log . "</pre>\n";
            } else {
                $log = '';
            }
        }
        if (!file_exists($uniq . ".dvi")) {
            if (!$image_mode) {
                $log .= "<pre class='errlog'><font color='red'>ERROR:</font> LaTeX does not work properly.</pre>";
                trigger_error($log, E_USER_WARNING);
            }
            chdir($cwd);
            return '';
        }
        #$formatter->errlog('DVIPS');
        $cmd = "{$dvicmd} {$dviopt} {$uniq}.dvi -o {$uniq}{$mask}.{$tmpext}";
        $formatter->errlog('DVI', $uniq . '.log');
        $fp = popen($cmd . $formatter->NULL, 'r');
        pclose($fp);
        $log2 = $formatter->get_errlog();
        if ($log2 and !$raw_mode) {
            trigger_error($log2, E_USER_NOTICE);
        }
        chdir($cwd);
        chdir(dirname($outpath));
        # XXX :(
        if ($tmpext == 'ps') {
            $cmd = "{$convert} -transparent white {$latex_convert_options} {$vartmp_dir}/{$uniq}.{$tmpext} " . basename($outpath);
        } else {
            if (!$raw_mode and !empty($DBInfo->latex_allinone)) {
                $outpath = "{$vartmp_dir}/{$uniq}.{$tmpext}";
            }
            $cmd = "{$mogrify} -transparent white {$latex_convert_options} {$vartmp_dir}/{$uniq}*.{$tmpext}";
        }
        # ImageMagick of the RedHat AS 4.x do not support -trim option correctly
        # http://kldp.net/forum/message.php?msg_id=12024
        #$cmd= "$convert -transparent white -trim -crop 0x0 -density 120x120 $vartmp_dir/$uniq.ps $outpath";
        $formatter->errlog('CNV', $uniq . '.log');
        $fp = popen($cmd . $formatter->LOG, 'r');
        pclose($fp);
        $log2 = $formatter->get_errlog(1, 1);
        if (!$raw_mode and $log2) {
            trigger_error($log2, E_USER_WARNING);
        }
        chdir($cwd);
        if ($raw_mode or $tmpext == 'png' and empty($DBInfo->latex_allinone)) {
            rename("{$vartmp_dir}/{$uniq}-1.{$tmpext}", $outpath);
        } else {
            if ($DBInfo->latex_allinone) {
                $sz = sizeof($formatter->latex_uniq);
                if ($tmpext == 'png') {
                    $soutpath = preg_replace('/\\.png/', '', $outpath);
                    if (file_exists($outpath . '.0')) {
                        # old convert behavior
                        $soutpath = "{$soutpath}.png.%d";
                    } else {
                        $soutpath = "{$soutpath}-%d.png";
                    }
                    # new behavior :(
                }
                for ($i = 0; $i < $sz; $i++) {
                    $id = $formatter->latex_uniq[$i];
                    if ($DBInfo->cache_public_dir) {
                        $pngname = $fc->getKey($id, false);
                        $img = $DBInfo->cache_public_dir . '/' . $pngname;
                    } else {
                        $img = $cache_dir . '/' . $id . '.png';
                    }
                    if ($tmpext == 'ps' and $sz == 1) {
                        rename($outpath, $img);
                    } else {
                        $ii = $i;
                        if ($tmpext == 'png') {
                            $ii++;
                        }
                        rename(sprintf($soutpath, $ii), $img);
                    }
                }
                $formatter->latex_all = '';
                $formatter->latex_uniq = array();
                $formatter->postamble['latex'] = '';
            }
        }
        @unlink($vartmp_dir . "/{$uniq}.log");
        @unlink($vartmp_dir . "/{$uniq}.aux");
        @unlink($vartmp_dir . "/{$uniq}.tex");
        @unlink($vartmp_dir . "/{$uniq}.dvi");
        @unlink($vartmp_dir . "/{$uniq}.bib");
        @unlink($vartmp_dir . "/{$uniq}.ps");
        $img_exists = true;
        break;
    }
    if (!$raw_mode and !$value) {
        return $js;
    }
    $alt = str_replace("'", "&#39;", $value);
    $title = $alt;
    if (!$raw_mode and !$img_exists) {
        $title = $png_url;
        if ($DBInfo->latex_allinone == 1 && empty($formatter->wikimarkup)) {
            $png_url = $DBInfo->imgs_dir . '/loading.gif';
        }
    }
    if (!$raw_mode) {
        return $log . $bra . "<img class='tex' src='{$png_url}' rel='{$uniq}' alt='{$alt}' " . "title='{$title}' />" . $ket;
    }
    $retval =& $options['retval'];
    $retval = $png;
    return $png_url;
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
function processor_metapost($formatter, $value = "")
{
    global $DBInfo;
    # site spesific variables
    $mpost = "mpost";
    $dvips = "dvips";
    $convert = "convert -transparent white -crop 0x0 -density 120x120";
    $vartmp_dir =& $DBInfo->vartmp_dir;
    $cache_dir = $DBInfo->upload_dir . "/MetaPost";
    $option = '-T -interaction=batchmode ';
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    if (!$value) {
        return;
    }
    if (preg_match('/beginfig\\(/', $value)) {
        $out = '<font color=red>Don\'t use beginfig()!</font>';
        $out .= "<pre>\n";
        $out .= $value;
        $out .= "</pre>\n";
        return $out;
    }
    $mp = $value;
    $uniq = md5($mp);
    if (!empty($DBInfo->cache_public_dir)) {
        $fc = new Cache_text('metapost', array('dir' => $DBInfo->cache_public_dir));
        $basename = $fc->getKey($mp);
        $png = $DBInfo->cache_public_dir . '/' . $basename . '.png';
        $ps = $DBInfo->cache_public_dir . '/' . $basename . '.ps';
        $png_url = $DBInfo->cache_public_url . '/' . $basename . '.png';
        $ps_url = $DBInfo->cache_public_url . '/' . $basename . '.ps';
    } else {
        $png = $cache_dir . '/' . $uniq . '.png';
        $ps = $cache_dir . '/' . $uniq . '.png';
        $png_url = $DBInfo->url_prefix . '/' . $png;
        $ps_url = $DBInfo->url_prefix . '/' . $ps;
        if (!file_exists($cache_dir)) {
            umask(00);
            mkdir($cache_dir, 0777);
            umask(022);
        }
    }
    $vartmp_basename = $vartmp_dir . '/' . $uniq;
    $src = "beginfig(1);\n{$mp}\nendfig;\n";
    if ($formatter->refresh || !file_exists($png)) {
        $fp = fopen($vartmp_dir . "/{$uniq}.mp", "w");
        fwrite($fp, $src);
        fclose($fp);
        $outpath = $png;
        # Unix specific FIXME
        $dir = getcwd();
        chdir($vartmp_dir);
        $cmd = "{$mpost} {$option} {$uniq} >/dev/null";
        $fp = popen($cmd . $formatter->NULL, 'r');
        pclose($fp);
        chdir($dir);
        $cmd = "{$convert} {$vartmp_basename}.1 {$outpath}";
        $fp = popen($cmd . $formatter->NULL, 'r');
        pclose($fp);
        @copy("{$vartmp_basename}.1", $ps);
        unlink("{$vartmp_basename}.1");
        unlink("{$vartmp_basename}.mp");
        unlink("{$vartmp_basename}.log");
    }
    return "<a href='{$ps_url}'><img class='tex' border='0' src='{$png_url}' alt='mp'" . "title=\"{$mp}\" /></a>";
}
Ejemplo n.º 8
0
function processor_geshi($formatter, $value, $options)
{
    global $DBInfo;
    if (!defined('GESHI_VERSION')) {
        return $formatter->processor_repl('vim', $value, $options);
    }
    $syntax = array('actionscript', 'ada', 'apache', 'asm', 'asp', 'bash', 'c', 'c_mac', 'caddcl', 'cadlisp', 'cpp', 'csharp', 'css-gen', 'css', 'delphi', 'html4strict', 'java', 'javascript', 'lisp', 'lua', 'nsis', 'objc', 'oobas', 'oracle8', 'pascal', 'perl', 'php-brief', 'php', 'python', 'qbasic', 'smarty', 'sql', 'vb', 'vbnet', 'visualfoxpro', 'xml');
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    # get parameters
    if ($line) {
        $line = substr($line, 2);
        $tag = strtok($line, ' ');
        $type = strtok(' ');
        $extra = strtok('');
        if ($tag != 'vim') {
            $extra = $type;
            $type = $tag;
        }
    }
    $src = rtrim($value);
    // XXX
    if (!$type) {
        $type = 'nosyntax';
    }
    $uniq = md5($extra . $value);
    if ($DBInfo->cache_public_dir) {
        $fc = new Cache_text('geshi', array('ext' => 'html', 'dir' => $DBInfo->cache_public_dir));
        $htmlname = $fc->getKey($uniq, false);
        $html = $DBInfo->cache_public_dir . '/' . $htmlname;
    } else {
        $cache_dir = $DBInfo->upload_dir . "/GeshiProcessor";
        $html = $cache_dir . '/' . $uniq . '.html';
    }
    if (!is_dir(dirname($html))) {
        $om = umask(00);
        _mkdir_p(dirname($html), 0777);
        umask($om);
    }
    if (file_exists($html) && !$formatter->refresh) {
        $out = "";
        $fp = fopen($html, "r");
        while (!feof($fp)) {
            $out .= fread($fp, 1024);
        }
        return $out;
    }
    # comment out the following two lines to freely use any syntaxes.
    if (!in_array($type, $syntax)) {
        return "<pre class='code'>\n{$line}\n" . htmlspecialchars($src) . "\n</pre>\n";
    }
    $geshi = new GeSHi($src, $type, dirname(__FILE__) . "/../../lib/geshi/geshi");
    if ($extra == "number") {
        $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
    }
    if ($extra == "fancy") {
        $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
    } else {
        $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS);
    }
    $out = '';
    $geshi->set_comments_style(1, 'font-style: normal;');
    $geshi->set_header_type(GESHI_HEADER_DIV);
    #$geshi->set_header_type(GESHI_HEADER_PRE);
    #$out = '<style type="text/css"><!--'.$geshi->get_stylesheet().'--></style>';
    #$geshi->enable_classes();
    $out .= $geshi->parse_code();
    $fp = fopen($html, "w");
    fwrite($fp, $out);
    fclose($fp);
    return $out;
}
Ejemplo n.º 9
0
 function get_javascripts()
 {
     global $Config;
     if (!empty($Config['use_jspacker']) and !empty($Config['cache_public_dir'])) {
         include_once 'lib/fckpacker.php';
         # good but not work with prototype.
         define('JS_PACKER', 'FCK_Packer/MoniWiki');
         $constProc = new FCKConstantProcessor();
         #$constProc->RemoveDeclaration = false ;
         #include_once('lib/jspacker.php'); # bad!
         #$packer = new JavaScriptPacker('', 0);
         #$packer->pack(); // init compressor
         #include_once('lib/jsmin.php'); # not work.
         $out = '';
         $packed = '';
         $pjs = array();
         $keys = array();
         foreach ($this->java_scripts as $k => $js) {
             if (!empty($js)) {
                 $keys[] = $k;
             }
         }
         if (empty($keys)) {
             return '';
         }
         $uniq = md5(implode(';', $keys));
         $cache = new Cache_text('js', array('ext' => 'html'));
         if ($cache->exists($uniq)) {
             foreach ($keys as $k) {
                 $this->java_scripts[$k] = '';
             }
             return $cache->fetch($uniq);
         }
         foreach ($this->java_scripts as $k => $js) {
             if ($js) {
                 if ($js[0] != '<') {
                     $async = '';
                     if (strpos($js, ',') !== false && substr($js, 0, 5) == 'async') {
                         $async = ' async';
                         $js = substr($js, 6);
                     }
                     if (preg_match('@^(http://|/)@', $js)) {
                         $out .= "<script{$async} type='text/javascript' src='{$js}'></script>\n";
                     } else {
                         if (file_exists('local/' . $js)) {
                             $fp = fopen('local/' . $js, 'r');
                             if (is_resource($fp)) {
                                 $_js = fread($fp, filesize('local/' . $js));
                                 fclose($fp);
                                 $packed .= '/* ' . $js . ' */' . "\n";
                                 #$packed.= JSMin::minify($_js);
                                 $packed .= FCKJavaScriptCompressor::Compress($_js, $constProc) . "\n";
                                 #$packed.= $packer->_pack($_js)."\n";
                                 $pjs[] = $k;
                             }
                         } else {
                             // is it exist ?
                             $js = $this->url_prefix . '/local/' . $js;
                             $out .= "<script{$async} type='text/javascript' src='{$js}'></script>\n";
                         }
                     }
                 } else {
                     //
                     $out .= $js;
                     if (0 and preg_match('/<script[^>]+(src=("|\')([^\\2]+)\\2)?[^>]*>(.*)<\\/script>\\s*$/s', $js, $m)) {
                         if (!empty($m[3])) {
                             $out .= $js;
                             #$out.="<script type='text/javascript' src='$js'></script>\n";
                         } else {
                             if (!empty($m[4])) {
                                 $packed .= '/* embeded ' . $k . '*/' . "\n";
                                 #$packed.= $packer->_pack($js)."\n";
                                 $packed .= FCKJavaScriptCompressor::Compress($m[4], $constProc) . "\n";
                                 #$packed.= JSMin::minify($js);
                                 $pjs[] = $k;
                             }
                         }
                     }
                 }
                 $this->java_scripts[$k] = '';
             }
         }
         $suniq = md5(implode(';', $pjs));
         $fc = new Cache_text('js', array('ext' => 'js', 'dir' => $Config['cache_public_dir']));
         $jsname = $fc->getKey($suniq, 0);
         $out .= '<script type="text/javascript" src="' . $Config['cache_public_url'] . '/' . $jsname . '"></script>' . "\n";
         $cache->update($uniq, $out);
         $ver = FCKJavaScriptCompressor::Revision();
         $header = '/* ' . JS_PACKER . ' ' . $ver . ' ' . md5($packed) . ' ' . date('Y-m-d H:i:s') . ' */' . "\n";
         # save real compressed js file.
         $fc->_save($jsname, $header . $packed);
         return $out;
     }
     $out = '';
     foreach ($this->java_scripts as $k => $js) {
         if ($js) {
             if ($js[0] != '<') {
                 $async = '';
                 if (strpos($js, ',') !== false && substr($js, 0, 5) == 'async') {
                     $async = ' async';
                     $js = substr($js, 6);
                 }
                 if (!preg_match('@^(http://|/)@', $js)) {
                     $js = $this->url_prefix . '/local/' . $js;
                 }
                 $out .= "<script{$async} type='text/javascript' src='{$js}'></script>\n";
             } else {
                 $out .= $js;
             }
             $this->java_scripts[$k] = '';
         }
     }
     return $out;
 }
Ejemplo n.º 10
0
function processor_sfd($formatter, $value = "")
{
    global $DBInfo;
    $width = 1000;
    $height = 1000;
    $EM = 1000;
    $op = array('l' => 1, 'c' => 0, 'm' => 1);
    $CONVERT = "convert -transparent white -density 24x24 ";
    $vartmp_dir =& $DBInfo->vartmp_dir;
    if (getenv("OS") == "Windows_NT") {
        $NULL = 'NUL';
        $vartmp_dir = getenv('TEMP');
        #$convert="wconvert";
    }
    $cache_dir = $DBInfo->upload_dir . "/SFD";
    $cache_url = !empty($DBInfo->upload_url) ? $DBInfo->upload_url . '/SFD' : $DBInfo->url_prefix . '/' . $cache_dir;
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    $sfd_source = $value;
    # print "<pre>$sfd_source</pre>";
    $uniq = md5($sfd_source);
    $lines = explode("\n", $sfd_source);
    $f = 0;
    $stat = 0;
    $eps = '';
    $oop = '';
    foreach ($lines as $l) {
        if ($stat == 0 and preg_match('/^StartChar:\\s+(.*)$/', $l)) {
            $stat = 1;
        } else {
            if ($stat == 1 and preg_match('/^Fore/', $l)) {
                $stat = 2;
            } else {
                if ($stat == 1 and preg_match('/^Width:\\s+(\\d+)$/', $l, $m)) {
                    $width = $height = $m[1];
                    $emscale = $EM / $width;
                    $width = intval($emscale * $width);
                    $height = intval($emscale * $height);
                    # XXX
                    $ascent = intval($height * 0.8);
                    $decent = intval($height * 0.2);
                    $date = date("Y-m-d H:i:s", time());
                    $eps .= <<<HEAD
%!PS-Adobe-3.0 EPSF-3.0
%%Creator: Adobe Illustrator by MoniWiki
%%Title:
%%CreationDate: {$date}
%%BoundingBox: 0 0 {$width} {$height}
%%DocumentData: Clean7Bit
%%EndComments
%%BeginProlog
/bd { bind def } bind def
/incompound false def
/m { moveto } bd
/l { lineto } bd
/c { curveto } bd
/F { incompound not {fill} if } bd
/f { closepath F } bd
/S { stroke } bd
/*u { /incompound true def } bd
/*U { /incompound false def f} bd
/k { setcmykcolor } bd
/K { k } bd
%%EndProlog
%%BeginSetup
%%EndSetup
0.000000 0.000000 0.000000 1.000000 k
*u

HEAD;
                } else {
                    if ($stat == 2) {
                        if (preg_match('/^\\s*([\\d+\\s\\.\\-\\+]+)\\s+([clm])\\s+\\d+$/', $l, $m)) {
                            $c = $m[1];
                            $op = $m[2];
                            $p = preg_split('/\\s+/', $m[1]);
                            if ($op == 'm' and $oop == 'l') {
                                $eps .= "f\n";
                            }
                            $n = 1;
                            foreach ($p as $val) {
                                if ($n % 2 == 0) {
                                    $eps .= intval($emscale * ($val + $decent)) . " ";
                                } else {
                                    $eps .= intval($emscale * $val) . " ";
                                }
                                $n++;
                            }
                            $eps .= "{$op}\n";
                            $oop = $op;
                            #print "$op ",$op{$op},"\n";
                        } else {
                            if (preg_match('/^EndChar$/', $l)) {
                                $stat = 0;
                                $eps .= "f\n*U\n";
                                $eps .= <<<INFO
0 0 1 setrgbcolor
5 setlinewidth
0 {$decent} m
{$width} {$decent} l
stroke
0 0 0 setrgbcolor
0 0 m
{$width} 0 l
{$width} {$height} l
0 {$height} l
0 0 l
stroke
*U

INFO;
                                $eps .= "%%Trailer\n%%EOF\n";
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if ($DBInfo->cache_public_dir) {
        $fc = new Cache_text('sfd', array('ext' => 'png', 'dir' => $DBInfo->cache_public_dir));
        $pngname = $fc->getKey($uniq, false);
        $outpath_png = $DBInfo->cache_public_dir . '/' . $pngname;
        $png_url = $DBInfo->cache_public_url ? $DBInfo->cache_public_url . '/' . $pngname : $DBInfo->url_prefix . '/' . $outpath_png;
    } else {
        $outpath_png = $cache_dir . '/' . $uniq . '.png';
        $png_url = $cache_url . '/' . $uniq . '.png';
    }
    $outpath_eps = "{$vartmp_dir}/{$uniq}.eps";
    if (!file_exists(dirname($outpath_png))) {
        umask(00);
        _mkdir_p(dirname($outpath_png), 0777);
        umask(022);
    }
    if ($formatter->refresh || !file_exists($outpath_png)) {
        # write to eps file
        $ifp = fopen("{$outpath_eps}", "w");
        fwrite($ifp, $eps);
        fclose($ifp);
        # convert
        $fp = popen("{$CONVERT} {$outpath_eps} {$outpath_png}" . $formatter->NULL, 'r');
        pclose($fp);
        # delete temporary files
        #unlink($outpath_eps);
    }
    return "<img class='tex' src='{$png_url}' alt='sfd' />";
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
0
function processor_vim($formatter, $value, $options)
{
    global $DBInfo;
    $vim_default = '-T xterm';
    static $jsloaded = 0;
    $vartmp_dir =& $DBInfo->vartmp_dir;
    $syntax = array("php", "c", "python", "jsp", "sh", "cpp", "java", "ruby", "forth", "fortran", "perl", "haskell", "lisp", "st", "objc", "tcl", "lua", "asm", "masm", "tasm", "make", "mysql", "awk", "docbk", "diff", "html", "tex", "vim", "xml", "dtd", "sql", "conf", "config", "nosyntax", "apache");
    #$opts=array("number");
    $line = '';
    if ($value[0] == '#' and $value[1] == '!') {
        list($line, $value) = explode("\n", $value, 2);
    }
    # get parameters
    if ($line) {
        $line = substr($line, 2);
        $tag = strtok($line, ' ');
        $type = strtok(' ');
        $extra = strtok('');
        if ($tag != 'vim') {
            $extra = $type;
            $type = $tag;
        }
    }
    $src = $value;
    if (!preg_match('/^\\w+$/', $type)) {
        $type = 'nosyntax';
    }
    $option = '';
    if ($extra == "number") {
        $option = '+"set number" ';
    }
    if ($DBInfo->vim_options) {
        $option .= $DBInfo->vim_options . ' ';
    }
    $uniq = md5($option . $extra . $type . $src);
    if ($DBInfo->cache_public_dir) {
        $fc = new Cache_text('vim', array('ext' => 'html', 'dir' => $DBInfo->cache_public_dir));
        $htmlname = $fc->getKey($uniq, false);
        $html = $DBInfo->cache_public_dir . '/' . $htmlname;
    } else {
        $cache_dir = $DBInfo->upload_dir . "/VimProcessor";
        $html = $cache_dir . '/' . $uniq . '.html';
    }
    $script = '';
    if (!empty($DBInfo->use_numbering) and empty($formatter->no_js)) {
        $formatter->register_javascripts('numbering.js');
        $script = "<script type=\"text/javascript\">\n/*<![CDATA[*/\naddtogglebutton('PRE-{$uniq}');\n/*]]>*/\n</script>";
    }
    if (!is_dir(dirname($html))) {
        $om = umask(00);
        _mkdir_p(dirname($html), 0777);
        umask($om);
    }
    if (file_exists($html) && empty($formatter->refresh) && empty($formatter->preview)) {
        $out = "";
        $fp = fopen($html, "r");
        while (!feof($fp)) {
            $out .= fread($fp, 1024);
        }
        @fclose($fp);
        return '<div>' . $out . $script . '</div>';
    }
    if (!empty($DBInfo->vim_nocheck) and !in_array($type, $syntax)) {
        $lines = explode("\n", $line . "\n" . str_replace('<', '&lt;', $src));
        if ($lines[sizeof($lines) - 1] == "") {
            array_pop($lines);
        }
        $src = "<span class=\"line\">" . implode("</span>\n<span class=\"line\">", $lines) . "</span>";
        return '<div>' . $script . "<pre class='wiki' id='PRE-{$uniq}'>\n{$src}</pre></div>\n";
    }
    $tohtml = !empty($DBInfo->vim_2html) ? $DBInfo->vim_2html : ($tohtml = '$VIMRUNTIME/syntax/2html.vim');
    #$tohtml= realpath($DBInfo->data_dir).'/2html.vim';
    if (getenv("OS") == "Windows_NT") {
        $vim = "gvim";
        # Win32
        $fout = tempnam($vartmp_dir, "OUT");
    } else {
        $tohtml = '\\' . $tohtml;
        $vim = "vim";
        $fout = "/dev/stdout";
    }
    $tmpf = tempnam($vartmp_dir, "FOO");
    $fp = fopen($tmpf, "w");
    fwrite($fp, $src);
    fclose($fp);
    $cmd = "{$vim} {$vim_default} -e -s {$tmpf} " . ' +"syntax on " +"set syntax=' . $type . '" ' . $option . ' +"so ' . $tohtml . '" +"wq! ' . $fout . '" +qall';
    $log = '';
    $out = '';
    if (getenv("OS") == "Windows_NT") {
        system($cmd);
        $out = join(file($fout), "");
        unlink($fout);
    } else {
        $formatter->errlog();
        $fp = popen($cmd . $formatter->LOG, "r");
        if (is_resource($fp)) {
            while ($s = fgets($fp, 1024)) {
                $out .= $s;
            }
            pclose($fp);
        }
        $log = $formatter->get_errlog();
        if ($log) {
            $log = '<pre class="errlog">' . $log . '</pre>';
        }
    }
    unlink($tmpf);
    #$out=preg_replace("/<title.*title>|<\/?head>|<\/?html>|<meta.*>|<\/?body.*>/","", $out);
    $out = str_replace("\r\n", "\n", $out);
    # for Win32
    #$out=preg_replace("/(^(\s|\S)*<pre>\n|\n<\/pre>(\s|\S)*$)/","",$out); # XXX segfault sometime
    preg_match("/<body\\s+bgcolor=(\"|')([^\\1]+)\\1\\s+text=\\1([^\\1]+)\\1/U", $out, $match);
    $bgcolor = '#000000';
    $fgcolor = '#c0c0c0';
    if ($match) {
        $bgcolor = $match[2];
        $fgcolor = $match[3];
    }
    $myspan = 'pre';
    $fpos = strpos($out, '<pre>');
    if ($fpos === false) {
        $myspan = 'div';
        $fpos = strpos($out, '<body');
        $tpos = strpos($out, '</body>');
        $out = substr($out, $fpos + 7, $tpos - $fpos - 7);
        $out = preg_replace('/^[^>]+>/', '', $out);
        $out = preg_replace(array("@^<font face[^>]*>\n@", "@\n?</font>\n?\$@"), array('', ''), $out);
        // vim7.x
    } else {
        $tpos = strpos($out, '</pre>');
        $out = substr($out, $fpos + 6, $tpos - $fpos - 7);
    }
    $stag = "<{$myspan} class='wikiSyntax' id='PRE-{$uniq}' style='font-family:FixedSys,monospace;color:{$fgcolor};background-color:{$bgcolor}'>\n";
    $etag = "</{$myspan}>\n";
    $lines = explode("\n", $out);
    $out = '';
    if (0) {
        // list style
        $col = array(' alt', '');
        $sz = count($lines);
        for ($i = 0; $i < $sz; $i++) {
            $cls = $col[$i % 2];
            $out .= "<li class=\"line{$cls}\">" . $lines[$i] . "</li>\n";
        }
        $out = '<ul style="margin:0;padding:0;list-style:none;">' . $out . '</ul>';
    } else {
        $out = "<span class=\"line\">" . implode("</span>\n<span class=\"line\">", $lines) . "</span>\n";
    }
    $fp = fopen($html, "w");
    fwrite($fp, $stag . $out . $etag);
    fclose($fp);
    return $log . '<div>' . $stag . $out . $etag . $script . '</div>';
}
Ejemplo n.º 13
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";
    }
}
Ejemplo n.º 14
0
function do_sitemap($formatter, $options)
{
    global $DBInfo, $Config;
    $tc = new Cache_text('persist', array('depth' => 0));
    $extra = '';
    if (!empty($formater->group)) {
        $extra = '.' . $formatter->group;
    }
    if (!empty($formatter->prefix)) {
        $extra .= qualifiedUrl($formatter->prefix);
    }
    // all pages
    $mtime = $DBInfo->mtime();
    $lastmod = gmdate('D, d M Y H:i:s \\G\\M\\T', $mtime);
    $etag = md5($mtime . $DBInfo->etag_seed . $extra);
    $options['etag'] = $etag;
    $options['mtime'] = $mtime;
    // set the s-maxage for proxy
    $date = gmdate('Y-m-d-H-i-s', $mtime);
    $proxy_maxage = !empty($Config['proxy_maxage']) ? ', s-maxage=' . $Config['proxy_maxage'] : '';
    // only xml format supported
    $format = 'text/xml';
    if (isset($options['format']) and in_array($options['format'], array('text/xml'))) {
        $format = $options['format'];
    }
    $header[] = 'Content-Type: ' . $format;
    $header[] = 'Cache-Control: public' . $proxy_maxage . ', max-age=0, must-revalidate';
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        $header[] = 'HTTP/1.0 304 Not Modified';
    } else {
        $header[] = 'Content-Disposition: attachment; filename="sitemap-' . $date . '.xml"';
    }
    $formatter->send_header($header, $options);
    if (!$need) {
        @ob_end_clean();
        return;
    }
    if (!$formatter->refresh && ($ret = $tc->fetch('sitemap' . $extra . '.mtime')) !== false) {
        if (($ret = $tc->fetch('sitemap' . $extra, 0, array('print' => 1))) !== false) {
            return;
        }
    }
    // set sitemap public cache
    $ext = $format == 'text/xml' ? 'xml' : 'txt';
    $sc = new Cache_text('sitemap', array('dir' => $DBInfo->cache_public_dir, 'ext' => $ext, 'depth' => 0));
    # get page list
    set_time_limit(0);
    if ($formater->group) {
        $group_pages = $DBInfo->getLikePages($formater->group);
        foreach ($group_pages as $page) {
            $all_pages[] = str_replace($formatter->group, '', $page);
        }
        usort($all_pages, 'strcasecmp');
    } else {
        if (!empty($Config['sitemap_sortby'])) {
            // call PageSort macro.
            $opts = array();
            $opts['sortby'] = $Config['sitemap_sortby'];
            // date or size
            $opts['.call'] = 1;
            $ret = $formatter->macro_repl('PageSort', '', $opts);
            $all_pages = array();
            if (!empty($ret['count'])) {
                $tc->fetch('pagedate.raw');
                $rawfile = $tc->cache_path . '/' . $tc->getKey('pagedate.raw');
                $fp = fopen($rawfile, 'r');
                if (is_resource($fp)) {
                    while (($line = fgets($fp, 1024)) != false) {
                        $tmp = explode("\t", $line);
                        $all_pages[] = $tmp[0];
                    }
                    fclose($fp);
                }
            }
        } else {
            $args = array('all' => 1);
            $all_pages = $DBInfo->getPageLists($args);
            usort($all_pages, 'strcasecmp');
        }
    }
    $count = sizeof($all_pages);
    $map = '';
    $zone = '+00:00';
    $ttl = !empty($DBInfo->sitemap_ttl) ? $DBInfo->sitemap_ttl : 60 * 60 * 24 * 7;
    if ($count > 50000) {
        $map = <<<HEAD
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

HEAD;
        $date = gmdate("Y-m-d\\TH:i:s", time()) . $zone;
        // W3C datetime format
        $total = intval($count / 50000) + ($count % 50000 > 0 ? 1 : 0);
        for ($i = 0; $i < $total; $i++) {
            $mapname = $sc->getKey(sprintf('sitemap' . $extra . '%03d', $i));
            $map .= "<sitemap>\n<loc>\n" . qualifiedUrl($DBInfo->cache_public_url . '/' . $mapname) . '</loc>' . "\n";
            $map .= '<lastmod>' . $date . "</lastmod>\n</sitemap>\n";
        }
        $map .= "</sitemapindex>\n";
        $tc->update('sitemap' . $extra, $map);
        $tc->update('sitemap' . $extra . '.mtime', array('dummy' => 1), $ttl);
    }
    # charset
    if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
        $charset = $options['oe'];
    } else {
        $charset = $DBInfo->charset;
    }
    $head = <<<HEAD
<?xml version="1.0" encoding="{$charset}"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9"
         url="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
         xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

HEAD;
    $foot = <<<FOOT
</urlset>
FOOT;
    # process page list
    $i = 0;
    $ii = 0;
    $items = array();
    foreach ($all_pages as $page) {
        $ii++;
        $url = qualifiedUrl($formatter->link_url(_rawurlencode($page)));
        $p = new WikiPage($page);
        $t = $p->mtime();
        $date = gmdate("Y-m-d\\TH:i:s", $t) . $zone;
        // W3C datetime format
        $item = "<url>\n";
        $item .= "  <loc>" . $url . "</loc>\n";
        $item .= "  <lastmod>" . $date . "</lastmod>\n";
        $item .= "</url>";
        $items[] = $item;
        if ($ii >= 50000) {
            $ii = 0;
            // process output
            $out = implode("\n", $items);
            if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
                $charset = $options['oe'];
                if (function_exists('iconv')) {
                    $new = iconv($DBInfo->charset, $charset, $items);
                    if (!$new) {
                        $charset = $DBInfo->charset;
                    }
                    if ($new) {
                        $out = $new;
                    }
                }
            }
            $sc->update(sprintf('sitemap' . $extra . '%03d', $i), $head . $out . $foot);
            $i++;
            $items = array();
        }
    }
    $sc->update('sitemap' . $extra . '.mtime', array('dummy' => 1), $ttl);
    // process output
    if ($count > 50000) {
        if (count($items)) {
            $out = implode("\n", $items);
            if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
                $charset = $options['oe'];
                if (function_exists('iconv')) {
                    $new = iconv($DBInfo->charset, $charset, $items);
                    if (!$new) {
                        $charset = $DBInfo->charset;
                    }
                    if ($new) {
                        $out = $new;
                    }
                }
            }
            $sc->update(sprintf('sitemap' . $extra . '%03d', $i), $head . $out . $foot);
        }
    } else {
        $out = implode("\n", $items);
        if ($options['oe'] and strtolower($options['oe']) != $DBInfo->charset) {
            $charset = $options['oe'];
            if (function_exists('iconv')) {
                $new = iconv($DBInfo->charset, $charset, $items);
                if (!$new) {
                    $charset = $DBInfo->charset;
                }
                if ($new) {
                    $out = $new;
                }
            }
        }
        $map = $head . $out . $foot;
        $tc->update('sitemap' . $extra, $map);
        $tc->update('sitemap' . $extra, array('dummy' => 1), $ttl);
    }
    echo $map;
}