示例#1
0
function macro_Clip($formatter, $value)
{
    global $DBInfo;
    $keyname = $DBInfo->_getPageKey($formatter->page->name);
    $_dir = str_replace("./", '', $DBInfo->upload_dir . '/' . $keyname);
    // support hashed upload dir
    if (!is_dir($_dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $prefix = get_hashed_prefix($keyname);
        $_dir = str_replace('./', '', $DBInfo->upload_dir . '/' . $prefix . $keyname);
    }
    $name = _rawurlencode($value);
    $enable_edit = 0;
    umask(00);
    if (!file_exists($_dir)) {
        _mkdir_p($_dir, 0777);
    }
    $pngname = $name . '.png';
    $now = time();
    $url = $formatter->link_url($formatter->page->name, "?action=clip&value={$name}&now={$now}");
    if (!file_exists($_dir . "/{$pngname}")) {
        return "<a href='{$url}'>" . _("Paste a new picture") . "</a>";
    }
    $edit = '';
    $end_tag = '';
    if ($enable_edit) {
        $edit = "<a href='{$url}'>";
        $end_tag = '</a>';
    }
    return "{$edit}<img src='{$DBInfo->url_prefix}/{$_dir}/{$pngname}' border='0' alt='image' />{$end_tag}\n";
}
示例#2
0
function _mkdir_p($target, $mode = 0777)
{
    // from php.net/mkdir user contributed notes
    if (file_exists($target)) {
        if (!is_dir($target)) {
            return false;
        } else {
            return true;
        }
    }
    // recursivly create dirs.
    return _mkdir_p(dirname($target), $mode) and mkdir($target, $mode);
}
示例#3
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' />";
}
示例#4
0
 function TitleIndexer_Text($name = 'titleindexer')
 {
     global $Config;
     $this->text_dir = $Config['text_dir'];
     $this->cache_dir = $Config['cache_dir'] . '/' . $name;
     if (!is_dir($this->cache_dir)) {
         $om = umask(00);
         _mkdir_p($this->cache_dir, 0777);
         umask($om);
     }
     $this->pagelst = $this->cache_dir . '/' . $name . '.lst';
     $this->pagecnt = $this->cache_dir . '/' . $name . '.cnt';
     $this->pagelck = $this->cache_dir . '/' . $name . '.lock';
 }
示例#5
0
 function TitleIndexer_Text($name = 'titleindexer')
 {
     global $Config;
     if (strtolower($Config['charset']) != 'utf-8') {
         $this->_match_flags = 'im';
     }
     $this->text_dir = $Config['text_dir'];
     $this->cache_dir = $Config['cache_dir'] . '/' . $name;
     if (!is_dir($this->cache_dir)) {
         $om = umask(00);
         _mkdir_p($this->cache_dir, 0777);
         umask($om);
     }
     $this->pagelst = $this->cache_dir . '/' . $name . '.lst';
     $this->pagecnt = $this->cache_dir . '/' . $name . '.cnt';
     $this->pagelck = $this->cache_dir . '/' . $name . '.lock';
 }
示例#6
0
 function BBS_text($name, $conf)
 {
     # $conf['data_dir'] from DBInfo.
     $this->bbsname = $name;
     # XXX
     $this->text_dir = $conf['data_dir'] . '/text/' . $name . '.d';
     # XXX
     $this->data_dir = $conf['data_dir'] . '/bbs/' . $name;
     $this->cache_dir = $this->data_dir . '/cache';
     $this->dba_type = $conf['dba_type'];
     $this->use_attach = $conf['use_attach'];
     # XXX
     $this->index = $this->data_dir . '/.index';
     $this->current = $this->data_dir . '/.current';
     $this->count = $this->data_dir . '/.count';
     # XXX
     if ($conf['use_counter']) {
         $this->counter = new Counter_dba($this);
     }
     if (!$this->counter->counter) {
         $this->counter = new Counter();
     }
     if (!file_exists($this->index)) {
         umask(00);
         _mkdir_p($this->data_dir, 0777);
         // XXX
         @mkdir($this->text_dir, 0777);
         // XXX
         @mkdir($this->text_dir, 0777);
         // XXX
         umask(022);
         touch($this->index);
         touch($this->count);
         # XXX global lock.
         touch($this->text_dir . '/.lock');
         $fp = fopen($this->current, 'w');
         if ($fp) {
             fwrite($fp, '1');
             fclose($fp);
         }
     }
 }
示例#7
0
 function PageIndex($name = 'pageindex')
 {
     global $Config;
     if (strtolower($Config['charset']) != 'utf-8') {
         $this->_match_flags = 'im';
     }
     $this->text_dir = $Config['text_dir'];
     $this->cache_dir = $Config['cache_dir'] . '/' . $name;
     if (!empty($Config['pageindex_chunksize'])) {
         $this->chunksize = $Config['pageindex_chunksize'];
     }
     if (!is_dir($this->cache_dir)) {
         $om = umask(00);
         _mkdir_p($this->cache_dir, 0777);
         umask($om);
     }
     $this->pagelst = $this->cache_dir . '/' . $name . '.lst';
     $this->pageidx = $this->cache_dir . '/' . $name . '.idx';
     $this->pagecnt = $this->cache_dir . '/' . $name . '.cnt';
     $this->pagelck = $this->cache_dir . '/' . $name . '.lock';
 }
示例#8
0
 function _ci($key, $log)
 {
     $dir = dirname($key);
     if (!is_dir($dir . '/RCS')) {
         $om = umask(00);
         _mkdir_p($dir . '/RCS', 2777);
         umask($om);
     }
     $mlog = '';
     $plog = '';
     if (getenv('OS') == 'Windows_NT' and isset($log[0])) {
         // win32 cmd.exe arguments do not accept UTF-8 charset correctly.
         // just use the stdin commit msg method instead of using -m"log" argument.
         $logfile = tempnam($this->DB->vartmp_dir, 'COMMIT_LOG');
         $fp = fopen($logfile, 'w');
         if (is_resource($fp)) {
             fwrite($fp, $log);
             fclose($fp);
             $plog = ' < ' . $logfile;
         }
     }
     if (empty($plog)) {
         // $log = escapeshellarg($log); // win32 does not work correctly
         $log = '"' . preg_replace('/([\\\\"])/', "\\\\\\1", $log) . '"';
         $mlog = ' -m' . $log;
     }
     if (!empty($this->DB->rcs_always_unlock)) {
         $fp = popen("rcs -l -M {$key}", 'r');
         if (is_resource($fp)) {
             pclose($fp);
         }
     }
     $fp = @popen("ci -l -x,v/ -q -t-\"" . $key . "\" " . $mlog . " " . $key . $plog . $this->NULL, "r");
     if (is_resource($fp)) {
         pclose($fp);
     }
     if (isset($plog[0])) {
         unlink($logfile);
     }
 }
示例#9
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>';
    }
}
示例#10
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;
}
示例#11
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;
}
示例#12
0
function do_SWFUpload($formatter, $options = array())
{
    global $DBInfo;
    $swfupload_dir = $DBInfo->upload_dir . '/.swfupload';
    $mysubdir = '';
    if (!is_dir($swfupload_dir)) {
        $om = umask(00);
        mkdir($swfupload_dir, 0777);
        umask($om);
        $fp = fopen($swfupload_dir . '/.htaccess', 'w');
        if ($fp) {
            $htaccess = <<<EOF
Options -Indexes
Order deny,allow

EOF;
            fwrite($fp, $htaccess);
            fclose($fp);
        }
    }
    // check subdir
    if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
        $depth = $DBInfo->swfupload_depth;
    } else {
        $depth = 2;
    }
    $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI');
    // FIXME
    if (session_id() != '') {
        // ip based
        if (0 and $_SESSION['_swfupload']) {
            // XXX flash bug?
            $myid = $_SESSION['_swfupload'];
        } else {
            if (!empty($options['value']) and ($p = strpos($options['value'], '/')) !== false) {
                $tmp = explode('/', $options['value']);
                #list($dum,$myid,$dum2)=explode('/',$options['value'],3);
                $myid = $tmp[1];
            }
        }
    }
    $prefix = substr($myid, 0, $depth);
    $mysubdir = $prefix . '/' . $myid . '/';
    // debug
    //$options['_mysubdir']=$mysubdir;
    //$fp=fopen($swfupload_dir.'/swflog.txt','a+');
    //foreach ($options as $k=>$v) {
    //    if (is_string($v))
    //         fwrite($fp,sprintf("%s=>%s\n",$k,$v));
    //}
    //foreach ($_SESSION as $k=>$v) {
    //    if (is_string($v))
    //         fwrite($fp,sprintf("%s=>%s\n",$k,$v));
    //}
    //fwrite($fp,"------------------------\n");
    //fclose($fp);
    // set the personal subdir
    if (!empty($options['value']) and preg_match('/^[a-z0-9\\/]+$/i', $options['value'])) {
        //if ($mysubdir == $options['value']) // XXX check subdir
        //    $mysubdir = $options['value'];
        list($dum, $myval, $dum2) = explode('/', $options['value'], 3);
        // XXX
        if (!is_dir($swfupload_dir . '/' . $mysubdir)) {
            $om = umask(00);
            _mkdir_p($swfupload_dir . '/' . $mysubdir, 0777);
            umask($om);
        }
    }
    //move the uploaded file
    if (isset($_FILES['Filedata']['tmp_name'])) {
        move_uploaded_file($_FILES['Filedata']['tmp_name'], $swfupload_dir . '/' . $mysubdir . $_FILES['Filedata']['name']);
        echo "Success";
        return;
    } else {
        if (isset($options['MYFILES']) and is_array($options['MYFILES'])) {
            include_once 'plugin/UploadFile.php';
            $options['_pds_subdir'] = $mysubdir;
            // a temporary pds dir
            $options['_pds_remove'] = 1;
            // remove all files in pds dir
            do_UploadFile($formatter, $options);
        } else {
            $formatter->send_header("", $options);
            $formatter->send_title("", "", $options);
            $out = macro_SWFUpload($formatter, '');
            print $formatter->get_javascripts();
            print $out;
            if (!in_array('UploadedFiles', $formatter->actions)) {
                $formatter->actions[] = 'UploadedFiles';
            }
            $formatter->send_footer("", $options);
        }
    }
}
示例#13
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;
}
示例#14
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";
    }
}
示例#15
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>';
}
示例#16
0
                             $txt = $dom[$i]['value'] . $txt;
                         }
                     }
                     $num = key($this->toc);
                     $dep = count(explode('.', $num));
                     $this->Bookmark($num . ' ' . $this->toc[$num], $dep, $this->y);
                     next($this->toc);
             }
             parent::closeHTMLTagHandler($dom, $key, $cell);
         }
     }
 }
 // define the share directory to create img
 define('X_PATH_SHARE_IMG', $DBInfo->cache_public_dir . '/html2pdf/');
 if (!file_exists(X_PATH_SHARE_IMG)) {
     _mkdir_p(X_PATH_SHARE_IMG, 0777);
 }
 // XXX
 $formatter->nonexists = 'always';
 $formatter->section_edit = 0;
 $formatter->perma_icon = '';
 ob_start();
 $formatter->send_header();
 $formatter->send_page('', array('fixpath' => 1));
 print '</body></html>';
 $html = ob_get_contents();
 ob_end_clean();
 # begin
 $pdf = new XTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, $DBInfo->charset);
 include_once 'function/toc.php';
 $toc = function_toc($formatter);
示例#17
0
function do_SWFUpload($formatter, $options = array())
{
    global $DBInfo;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$DBInfo->security->writable($options)) {
        $options['title'] = _("Page is not writable");
        return do_invalid($formatter, $options);
    }
    // check allowed file extensions
    $allowed_re = '.*';
    if (!empty($DBInfo->pds_allowed)) {
        $allowed_re = $DBInfo->pds_allowed;
    }
    $swfupload_dir = $DBInfo->upload_dir . '/.swfupload';
    $mysubdir = '';
    if (!is_dir($swfupload_dir)) {
        $om = umask(00);
        mkdir($swfupload_dir, 0777);
        umask($om);
        $fp = fopen($swfupload_dir . '/.htaccess', 'w');
        if ($fp) {
            $htaccess = <<<EOF
# FCGI or CGI user can use .user.ini
Options -Indexes
AddType text/plain .php5 .php4 .php3 .phtml .php .html .map .mm
<Files ~ "\\.php">
#ForceType text/plain
SetHandler text/plain
</Files>
Order deny,allow
deny from all

EOF;
            fwrite($fp, $htaccess);
            fclose($fp);
        }
    }
    // check subdir
    if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
        $depth = $DBInfo->swfupload_depth;
    } else {
        $depth = 2;
    }
    $seed = $_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI';
    if ($DBInfo->seed) {
        $seed .= $DBInfo->seed;
    }
    $myid = md5($seed);
    // FIXME
    if (session_id() != '') {
        // ip based
        if (0 and $_SESSION['_swfupload']) {
            // XXX flash bug?
            $myid = $_SESSION['_swfupload'];
        } else {
            if (!empty($options['value']) and ($p = strpos($options['value'], '/')) !== false) {
                $tmp = explode('/', $options['value']);
                #list($dum,$myid,$dum2)=explode('/',$options['value'],3);
                $myid = $tmp[1];
            }
        }
    }
    $prefix = substr($myid, 0, $depth);
    $mysubdir = $prefix . '/' . $myid . '/';
    // debug
    //$options['_mysubdir']=$mysubdir;
    //$fp=fopen($swfupload_dir.'/swflog.txt','a+');
    //foreach ($options as $k=>$v) {
    //    if (is_string($v))
    //         fwrite($fp,sprintf("%s=>%s\n",$k,$v));
    //}
    //foreach ($_SESSION as $k=>$v) {
    //    if (is_string($v))
    //         fwrite($fp,sprintf("%s=>%s\n",$k,$v));
    //}
    //fwrite($fp,"------------------------\n");
    //fclose($fp);
    // set the personal subdir
    if (!empty($options['value']) and preg_match('/^[a-z0-9\\/]+$/i', $options['value'])) {
        //if ($mysubdir == $options['value']) // XXX check subdir
        //    $mysubdir = $options['value'];
        list($dum, $myval, $dum2) = explode('/', $options['value'], 3);
        // XXX
        if (!is_dir($swfupload_dir . '/' . $mysubdir)) {
            $om = umask(00);
            _mkdir_p($swfupload_dir . '/' . $mysubdir, 0777);
            umask($om);
        }
    }
    //move the uploaded file
    if (isset($_FILES['Filedata']['tmp_name'])) {
        if (preg_match('/\\.(' . $allowed_re . ')$/i', $_FILES['Filedata']['name'])) {
            move_uploaded_file($_FILES['Filedata']['tmp_name'], $swfupload_dir . '/' . $mysubdir . $_FILES['Filedata']['name']);
        }
        echo "Success";
        return;
    } else {
        if (isset($options['MYFILES']) and is_array($options['MYFILES'])) {
            include_once 'plugin/UploadFile.php';
            $options['_pds_subdir'] = $mysubdir;
            // a temporary pds dir
            $options['_pds_remove'] = 1;
            // remove all files in pds dir
            do_UploadFile($formatter, $options);
        } else {
            $formatter->send_header("", $options);
            $formatter->send_title("", "", $options);
            $out = macro_SWFUpload($formatter, '');
            print $formatter->get_javascripts();
            print $out;
            if (!in_array('UploadedFiles', $formatter->actions)) {
                $formatter->actions[] = 'UploadedFiles';
            }
            $formatter->send_footer("", $options);
        }
    }
}
示例#18
0
 /**
  * Function - Create wikifarm directory if available
  *
  * @param String data directory
  * @param Boolean copy wikiseed or not
  * @param String wikiseed src directory
  * @return Boolean or String
  */
 static function create_dirs($farm_dir, $conf = array())
 {
     // Nothing to do
     if (is_dir($farm_dir)) {
         return true;
     }
     $ret = true;
     if (!is_dir($farm_dir)) {
         $ret = _mkdir_p($farm_dir);
     }
     if ($ret === false) {
         return sprintf("Fail to mkdir(%s)", $farm_dir);
     }
     // set text_dir
     $text_dir = $farm_dir . '/text';
     // create dirs
     $ret = true;
     $dirs = array('text', 'text/RCS', 'cache');
     foreach ($dirs as $d) {
         $dir = $farm_dir . '/' . $d;
         if (!is_dir($dir)) {
             $ret = mkdir($dir);
             if ($ret === false) {
                 return sprintf("Fail to mkdir(%s)", $dir);
             }
         }
     }
     // touch editlog
     $ret = touch(self::get_editlog($farm_dir));
     if ($ret === false) {
         return "Fail to touch editlog";
     }
     // check wikiseed directory
     if (!empty($conf['wikifarm_seed_dir'])) {
         $seeddir = $conf['wikifarm_seed_dir'];
     } else {
         $seeddir = 'wikiseed';
     }
     if (!is_dir($seeddir)) {
         return true;
     }
     if (!empty($conf['wikifarm_autoseed'])) {
         $wikiseed = $conf['wikifarm_autoseed'];
     } else {
         $wikiseed = false;
     }
     // skip to sow wikiseed
     if (!$wikiseed) {
         // base pages
         $files = array('FrontPage', 'RecentChanges', 'FindPage', 'TitleIndex', 'UserPreferences');
     } else {
         // copy wikiseed
         $handle = opendir($seeddir);
         $files = array();
         while ($file = readdir($handle)) {
             // We don't copy directories
             if (is_dir($seeddir . '/' . $file)) {
                 continue;
             }
             $files[] = $file;
         }
         closedir($handle);
     }
     foreach ($files as $file) {
         // FIXME: Handle errors
         copy($seeddir . '/' . $file, $text_dir . '/' . $file);
         // preserve seed mtime
         $mtime = filemtime($seeddir . '/' . $file);
         touch($text_dir . '/' . $file, $mtime);
     }
     return true;
 }
示例#19
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' />";
}
示例#20
0
function macro_MsgTrans($formatter, $value, $param = array())
{
    global $DBInfo;
    $user =& $DBInfo->user;
    if (empty($param['init']) and (!is_array($DBInfo->owners) or !in_array($user->id, $DBInfo->owners))) {
        return sprintf(_("You are not allowed to \"%s\" !"), "msgtrans");
    }
    if (!$pagename) {
        $pagename = $DBInfo->default_translation ? $DBInfo->default_translation : 'LocalTranslationKo';
    }
    $page = $DBInfo->getPage($pagename);
    $strs = array();
    $charset = strtoupper($DBInfo->charset);
    $lang = !empty($value) ? $value : ($DBInfo->lang ? $DBInfo->lang : 'en_US.' . $charset);
    if ($page->exists()) {
        $raw = $page->get_raw_body();
        $raw = rtrim($raw);
        $lines = explode("\n", $raw);
        foreach ($lines as $l) {
            $l = trim($l);
            if ($l[0] == '#') {
                if (preg_match('/^#lang(?' . '>uage)? (ko_KR|en_US|fr_FR)$/', $l, $m)) {
                    $lang = $m[1];
                    if ($DBInfo->charset) {
                        $lang .= '.' . $charset;
                    }
                }
                continue;
            }
            if ($l[0] == '"') {
                if (preg_match('/^(("(([^"]|\\\\")*?)"\\s*)+)\\s*(.*)$/', $l, $m)) {
                    $smap = array('/"\\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/');
                    $rmap = array('', "\n", "\r", "\t", '"');
                    $w = preg_replace($smap, $rmap, $m[3]);
                    $t = preg_replace($smap, $rmap, $m[5]);
                }
            } else {
                list($w, $t) = explode(" ", $l, 2);
            }
            $strs[$w] = $t;
        }
    }
    if (getenv("OS") == "Windows_NT") {
        $lang = substr($lang, 0, 2);
    }
    //print_r($strs);
    if (!empty($strs) or !empty($param['init'])) {
        $myMO = null;
        $ldir = 'locale/' . $lang . '/LC_MESSAGES';
        $mofile = $ldir . '/moniwiki.mo';
        if (!file_exists($mofile)) {
            # load *.po file
            $e = false;
            $mylang = substr($lang, 0, 2);
            $pofile = 'locale/po/' . $mylang . '.po';
            if (!file_exists($pofile)) {
                $pofile = dirname(__FILE__) . '/../locale/po/' . $mylang . '.po';
            }
            if (file_exists($pofile)) {
                include_once 'lib/Gettext/PO.php';
                $myPO = new File_Gettext_PO();
                if (($e = $myPO->load($pofile)) == true) {
                    $myMO = $myPO->toMO();
                    preg_match('/charset=(.*)$/', $myMO->meta['Content-Type'], $cs);
                    if (strtoupper($cs[1]) != $charset) {
                        if (function_exists("iconv")) {
                            $myMO->meta['Content-Type'] = 'text/plain; charset=' . $charset;
                            foreach ($myMO->strings as $k => $v) {
                                $nv = iconv($cs[1], $charset, $v);
                                if (isset($nv)) {
                                    $myMO->strings[$k] = $nv;
                                }
                            }
                        } else {
                            $e = false;
                        }
                    }
                }
            }
        } else {
            # load *.mo file
            include_once 'lib/Gettext/MO.php';
            $myMO = new File_Gettext_MO();
            $e = $myMO->load($mofile);
        }
        if (!is_object($myMO)) {
            return;
        }
        if ($e == true) {
            $myMO->strings = array_merge($myMO->strings, $strs);
            #$myMO->meta['PO-Revision-Date']= date('Y-m-d H:iO');
            ksort($myMO->strings);
            // important!
            #print_r($myMO->strings);
        } else {
            $meta = array('Content-Type' => 'text/plain; charset=' . $charset, 'Last-Translator' => 'MoniWiki Translator', 'PO-Revision-Date' => date('Y-m-d H:iO'), 'MIME-Version' => '1.0', 'Language-Team' => 'MoniWiki Translator');
            if (true !== ($e = $myMO->fromArray(array('meta' => $meta, 'strings' => $strs)))) {
                return "Fail to make a mo file.\n";
            }
        }
        $vartmp_dir = $DBInfo->vartmp_dir;
        $tmp = tempnam($vartmp_dir, "GETTEXT");
        #$tmp=$vartmp_dir."/GETTEXT.mo";
        if (true !== ($e = $myMO->save($tmp))) {
            return "Fail to save mo file.\n";
        }
        if (!function_exists('bindtextdomain')) {
            // FIXME use cache class
            $tmp2 = tempnam($vartmp_dir, "GETTEXT");
            $fp = fopen($tmp2, 'w');
            if (is_resource($fp)) {
                fwrite($fp, _msgs_to_php($myMO->strings));
                fclose($fp);
                $ldir2 = $DBInfo->cache_dir . '/' . $ldir;
                if (!rename($tmp2, $ldir2 . '/moniwiki.php')) {
                    unlink($tmp2);
                    // fail to copy ?
                }
            }
        }
        # gettext cache workaround
        # http://kr2.php.net/manual/en/function.gettext.php#58310
        # use md5sum instead
        $md5 = md5_file($tmp);
        $md5file = $DBInfo->cache_dir . '/' . $ldir . '/md5sum';
        $ldir = $DBInfo->cache_dir . '/' . $ldir;
        _mkdir_p($ldir, 0777);
        $f = fopen($md5file, 'w');
        if (is_resource($f)) {
            fwrite($f, $md5);
            fclose($f);
        }
        if (!rename($tmp, $ldir . '/moniwiki-' . $md5 . '.mo')) {
            unlink($md5file);
            // fail to copy ?
            return "Fail to save mo file.\n";
        }
        return _("Local translation files are successfully translated !\n");
    }
    return "Empty !\n";
}
示例#21
0
} else {
    $src_dir = $topdir . '/' . $DBInfo->upload_dir;
}
if (isset($argv[4])) {
    if (is_dir($argv[4])) {
        echo 'Dest dir already exists!', "\n";
        exit;
    }
    $dest_dir = $argv[4];
} else {
    $dest_dir = $src_dir . '.new';
}
//
set_time_limit(0);
if (!file_exists($dest_dir)) {
    _mkdir_p($dest_dir);
}
echo "\t* src dir  = ", $src_dir, "\n";
echo "\t* dest dir = ", $dest_dir, "\n";
$ans = ask('Are you sure ? [y/N]', 'n');
if ($ans == 'n') {
    exit;
}
require_once $topdir . "/lib/pagekey.{$fromenc}.php";
require_once $topdir . "/lib/pagekey.{$toenc}.php";
$from_class = 'PageKey_' . $fromenc;
$to_class = 'PageKey_' . $toenc;
$from = new $from_class($DBInfo);
$to = new $to_class($DBInfo);
function get_sub_dir($dir)
{
示例#22
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;
}
示例#23
0
function do_post_Draw($formatter, $options = array())
{
    global $DBInfo;
    $enable_replace = 1;
    $keyname = $DBInfo->_getPageKey($options['page']);
    $_dir = str_replace("./", '', $DBInfo->upload_dir . '/' . $keyname);
    $pagename = $options['page'];
    // support hashed upload dir
    if (!is_dir($_dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $prefix = get_hashed_prefix($keyname);
        $_dir = str_replace('./', '', $DBInfo->upload_dir . '/' . $prefix . $keyname);
    }
    umask(00);
    if (!file_exists($_dir)) {
        _mkdir_p($_dir, 0777);
    }
    $name = $options['value'];
    if (!empty($_FILES['filepath'])) {
        $upfile = $_FILES['filepath']['tmp_name'];
        $temp = explode("/", $_FILES['filepath']['name']);
        $upfilename = $temp[count($temp) - 1];
        preg_match("/(.*)\\.([a-z0-9]{1,4})\$/i", $upfilename, $fname);
        # do not change the extention of the file.
        $file_path = $newfile_path = $_dir . "/" . $upfilename;
        # is file already exists ?
        $dummy = 0;
        while (file_exists($newfile_path)) {
            $dummy = $dummy + 1;
            $ufname = $fname[1] . "_" . $dummy;
            // rename file
            $upfilename = $ufname . ".{$fname['2']}";
            $newfile_path = $_dir . "/" . $upfilename;
        }
        if ($enable_replace) {
            if ($file_path != $newfile_path) {
                $test = @copy($file_path, $newfile_path);
            }
            $test = @copy($upfile, $file_path);
        } else {
            $test = @copy($upfile, $newfile_path);
        }
        if (!$test) {
            $title = sprintf(_("Fail to copy \"%s\" to \"%s\""), $upfilename, $file_path);
            $formatter->send_header("Status: 406 Not Acceptable", $options);
            $formatter->send_title($title, "", $options);
            return;
        }
        if ($fname[2] == 'map') {
            # fix map file.
            $map = file($newfile_path);
            $map = implode('', $map);
            # remove useless areas
            $map = preg_replace('/HREF="%TWIKIDRAW%"/', 'nohref', $map);
            $fp = fopen($newfile_path, 'w');
            if ($fp) {
                fwrite($fp, $map);
                fclose($fp);
            }
        }
        chmod($newfile_path, 0644);
        if ($fname[2] == 'draw') {
            $comment = sprintf("Drawing '%s' uploaded", $upfilename);
            $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
            $DBInfo->addLogEntry($keyname, $REMOTE_ADDR, $comment, "ATTDRW");
        }
        return;
    }
    if (!$name) {
        $title = _("Fatal error !");
        $formatter->send_header("Status: 406 Not Acceptable", $options);
        $formatter->send_title($title, "", $options);
        print "<h2>" . _("No filename given") . "</h2>";
        $formatter->send_footer("", $options);
        return;
    }
    $gifname = _rawurlencode($name);
    if (empty($_GET['mode']) or $_GET['mode'] != 'attach') {
        $gifname = 'Draw_' . $gifname;
    }
    $imgpath = "{$_dir}/{$gifname}";
    $ufname = $gifname;
    $dummy = 0;
    while (file_exists($imgpath)) {
        $dummy = $dummy + 1;
        $ufname = $gifname . "_" . $dummy;
        // rename file
        $imgpath = "{$_dir}/{$ufname}";
    }
    $draw_url = "{$DBInfo->upload_dir_url}/{$keyname}/{$ufname}.draw";
    $gif_url = "{$DBInfo->upload_dir_url}/{$keyname}/{$ufname}.gif";
    $formatter->send_header("", $options);
    $formatter->send_title(_("Edit drawing"), "", $options);
    $prefix = $formatter->prefix;
    $now = time();
    $url_exit = $formatter->link_url($options['page'], "?ts={$now}");
    $url_save = $formatter->link_url($options['page'], "?action=draw");
    $url_help = $formatter->link_url("HotDraw");
    $pubpath = $DBInfo->url_prefix . "/applets/TWikiDrawPlugin";
    print "<h2>" . _("Edit new drawing") . "</h2>\n";
    print <<<APPLET
<applet code="CH.ifa.draw.twiki.TWikiDraw.class"
 archive="twikidraw.jar" codebase="{$pubpath}"
 width='500' height='40' align="center">
        <param name="drawpath" value="{$draw_url}">
        <param name="gifpath"  value="{$gif_url}">
        <param name="savepath" value="{$url_save}">
        <param name="viewpath" value="{$url_exit}">
        <param name="helppath" value="{$url_help}">
<b>NOTE:</b> You need a Java enabled browser to edit the drawing example.
</applet><br />
APPLET;
    $formatter->send_footer("", $options);
    return;
}
示例#24
0
        _mkdir_p($argv[4] . '/text/RCS');
    } else {
        if (!file_exists($argv[4] . '/text') && !file_exists($argv[4] . '/text/RCS')) {
            _mkdir_p($argv[4] . '/text/RCS');
        } else {
            if (!is_dir($argv[4] . '/text') or !is_dir($argv[4] . '/text/RCS')) {
                usage();
                exit;
            }
        }
    }
    $dest_dir = $argv[4] . '/text';
} else {
    $dest_dir = $topdir . '/data.new';
    if (!file_exists($dest_dir)) {
        _mkdir_p($dest_dir . '/RCS');
    }
}
echo "\t* src dir  = ", $text_dir, "\n";
echo "\t* dest dir = ", $dest_dir, "\n";
$ans = ask('Are you sure ? [y/N]', 'n');
if ($ans == 'n') {
    exit;
}
require_once $topdir . "/lib/pagekey.{$fromenc}.php";
require_once $topdir . "/lib/pagekey.{$toenc}.php";
$from_class = 'PageKey_' . $fromenc;
$to_class = 'PageKey_' . $toenc;
$from = new $from_class($DBInfo);
$to = new $to_class($DBInfo);
set_time_limit(0);
示例#25
0
function do_uploadfile($formatter, $options)
{
    global $DBInfo;
    $files = array();
    $title = '';
    if (isset($options['data'])) {
        if (substr($options['data'], 0, 5) == 'data:') {
            $data = substr($options['data'], 5);
        } else {
            $data = $options['data'];
        }
        $err = _("Fail to parse data string");
        while (preg_match('@^(image/(gif|jpe?g|png));base64,(.*)$@', $data, $match)) {
            $ret = base64_decode($match[3]);
            if ($ret === false) {
                $err = _("Fail to decode base64 data string.");
                break;
            } else {
                $name = isset($options['name'][0]) ? $options['name'] : 'unnamed';
                $name .= '.' . $match[2];
                $tmpfile = tempnam($DBInfo->vartmp_dir, 'DATA');
                $fp = fopen($tmpfile, 'wb');
                if (!is_resource($fp)) {
                    $err = _("Fail to open file.\n");
                    break;
                }
                fwrite($fp, $ret);
                fclose($fp);
                $count = 1;
                $files['upfile']['name'][] = $name;
                $files['upfile']['tmp_name'][] = $tmpfile;
                $files['upfile']['error'][] = '';
                $files['upfile']['type'][] = $match[1];
                $err = '';
                break;
            }
        }
    }
    if (!empty($err)) {
        echo $err;
        return;
    }
    if (isset($_FILES['upfile']) and is_array($_FILES)) {
        if (!empty($options['multiform']) and $options['multiform'] > 1 or is_array($_FILES['upfile']['name'])) {
            $options['multiform'] = !empty($options['multiform']) ? $options['multiform'] : sizeof($_FILES['upfile']['name']);
            $count = $options['multiform'];
            $files =& $_FILES;
            if (!isset($options['rename'])) {
                $options['rename'] = array();
            }
        } else {
            $count = 1;
            $files['upfile']['name'][] =& $_FILES['upfile']['name'];
            $files['upfile']['tmp_name'][] =& $_FILES['upfile']['tmp_name'];
            $files['upfile']['error'][] =& $_FILES['upfile']['error'];
            $files['upfile']['type'][] =& $_FILES['upfile']['type'];
            $options['rename'] = array($options['rename']);
            $options['replace'] = array($options['replace']);
        }
    } else {
        if (isset($options['MYFILES']) and is_array($options['MYFILES'])) {
            // for SWFUpload action
            $count = sizeof($options['MYFILES']);
            $MYFILES =& $options['MYFILES'];
            $mysubdir = $options['mysubdir'];
            for ($i = 0; $i < $count; $i++) {
                $myname = $MYFILES[$i];
                $files['upfile']['name'][] = $myname;
                $files['upfile']['tmp_name'][] = $DBInfo->upload_dir . '/.swfupload/' . $mysubdir . $myname;
                // XXX
                $files['rename'][] = '';
                $files['replace'][] = '';
            }
        }
    }
    // Set upload err msg func.
    if (!empty($DBInfo->upload_err_func) and function_exists($DBInfo->upload_err_func)) {
        $upload_err_func = $DBInfo->upload_err_func;
    } else {
        $upload_err_func = '_upload_err_msg';
    }
    $msg = array();
    $err_msg = array();
    $upload_ok = array();
    $js = '';
    $uploadid = !empty($options['uploadid']) ? $options['uploadid'] : '';
    if (!empty($uploadid) or !empty($options['MYFILES'])) {
        $js = <<<EOF
<script type="text/javascript">
/*<![CDATA[*/
function delAllForm(id) {
  if (!opener) return;
  if (id == '') return;
  var fform = opener.document.getElementById(id);

  if (fform && fform.rows && fform.rows.length) { // for UploadForm
    for (var i=fform.rows.length;i>0;i--) {
      fform.deleteRow(i-1);
    }
  } else { // for SWFUpload
    var listing = opener.document.getElementById('mmUploadFileListing');
    if (listing) {
      var elem = listing.getElementsByTagName("li");
      listing.innerHTML='';
    } else if (fform) {
      fform.reset();
    }
  }
}

delAllForm('{$uploadid}');
/*]]>*/
</script>

EOF;
    }
    $ok = 0;
    if ($files) {
        foreach ($files['upfile']['name'] as $f) {
            if ($f) {
                $ok = 1;
                break;
            }
        }
    }
    if (!$ok) {
        if (isset($options['retval'])) {
            return false;
        }
        // ignore
        #$title="No file selected";
        $formatter->send_header("", $options);
        $formatter->send_title($title, "", $options);
        print macro_UploadFile($formatter, '', $options);
        if (!in_array('UploadedFiles', $formatter->actions)) {
            $formatter->actions[] = 'UploadedFiles';
        }
        $formatter->send_footer("", $options);
        return false;
    }
    $key = $DBInfo->pageToKeyname($formatter->page->name);
    if ($key != 'UploadFile') {
        $dir = $DBInfo->upload_dir . '/' . $key;
        // support hashed upload_dir
        if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
            $prefix = get_hashed_prefix($key);
            $dir = $DBInfo->upload_dir . '/' . $prefix . $key;
        }
    } else {
        $dir = $DBInfo->upload_dir;
    }
    if (!file_exists($dir)) {
        umask(00);
        _mkdir_p($dir, 0777);
        umask(02);
    }
    $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
    $comment = "File ";
    $uploaded = '';
    $log_entry = '';
    $protected_exts = !empty($DBInfo->pds_protected) ? $DBInfo->pds_protected : "pl|cgi|php";
    $safe_exts = !empty($DBInfo->pds_safe) ? $DBInfo->pds_safe : "txt|gif|png|jpg|jpeg";
    $protected = explode('|', $protected_exts);
    $safe = explode('|', $safe_exts);
    # upload file protection
    if (!empty($DBInfo->pds_allowed)) {
        $pds_exts = $DBInfo->pds_allowed;
    } else {
        $pds_exts = "png|jpg|jpeg|gif|mp3|zip|tgz|gz|txt|css|exe|pdf|hwp";
    }
    $allowed = 0;
    if (isset($DBInfo->upload_masters) and in_array($options['id'], $DBInfo->upload_masters)) {
        // XXX WARN!!
        $pds_exts = '.*';
        $allowed = 1;
    }
    $safe_types = array('text' => '', 'media' => '', 'image' => '', 'audio' => '', 'application' => 'bin');
    for ($j = 0; $j < $count; $j++) {
        # replace space and ':' strtr()
        $upfilename = str_replace(" ", "_", $files['upfile']['name'][$j]);
        $upfilename = str_replace(":", "_", $upfilename);
        preg_match("/^(.*)\\.([a-z0-9]{1,5})\$/i", $upfilename, $fname);
        if (!$upfilename) {
            continue;
        } else {
            if ($upfilename) {
                $uploaded++;
            }
        }
        $no_ext = 0;
        if (empty($fname[2])) {
            $fname[1] = $upfilename;
            $fname[2] = '';
            $no_ext = 1;
        }
        if (!$allowed) {
            if (!empty($DBInfo->use_filetype)) {
                $type = '';
                $type = $files['upfile']['type'][$j] ? $files['upfile']['type'][$j] : 'text/plain';
                list($mtype, $xtype) = explode('/', $type);
                if (!empty($mtype) and array_key_exists($mtype, $safe_types)) {
                    $allowed = 1;
                    $fname[2] = $fname[2] ? $fname[2] : $safe_types[$mtype];
                } else {
                    if ($no_ext) {
                        $err_msg[] = sprintf(_("The %s type of %s is not allowed to upload"), $type, $upfilename);
                        continue;
                    }
                }
            } else {
                $fname[2] = $fname[2] ? $fname[2] : 'txt';
                $no_ext = 0;
            }
        }
        $upfilename = preg_replace('/\\.$/', '', implode('.', array($fname[1], $fname[2])));
        if (!$allowed) {
            if (!$no_ext and !preg_match("/(" . $pds_exts . ")\$/i", $fname[2])) {
                if ($DBInfo->use_filetype and !empty($type)) {
                    $err_msg[] = sprintf(_("The %s type of %s is not allowed to upload"), $type, $upfilename);
                } else {
                    $err_msg[] = sprintf(_("%s is not allowed to upload"), $upfilename);
                }
                continue;
            } else {
                if ($fname[2] and in_array(strtolower($fname[2]), $safe)) {
                    $upfilename = $fname[1] . '.' . $fname[2];
                } else {
                    # check extra extentions for the mod_mime
                    $exts = explode('.', $fname[1]);
                    $ok = 0;
                    for ($i = sizeof($exts); $i > 0; $i--) {
                        if (in_array(strtolower($exts[$i - 1]), $safe)) {
                            $ok = 1;
                            break;
                        } else {
                            if (in_array(strtolower($exts[$i - 1]), $protected)) {
                                $exts[$i] .= '.txt';
                                # extra check for mod_mime: append 'txt' extension: my.pl.hwp => my.pl.txt.hwp
                                $ok = 1;
                                break;
                            }
                        }
                    }
                    if ($ok) {
                        $fname[1] = implode('.', $exts);
                        $upfilename = $fname[1] . '.' . $fname[2];
                    }
                }
            }
        }
        $file_path = $newfile_path = $dir . "/" . $upfilename;
        $filename = $upfilename;
        if (!empty($options['rename'][$j])) {
            # XXX
            $temp = explode("/", _stripslashes($options['rename'][$j]));
            $upfilename = $temp[count($temp) - 1];
            preg_match("/^(.*)\\.([a-z0-9]{1,5})\$/i", $upfilename, $tname);
            $exts = explode('.', $tname[1]);
            $ok = 0;
            for ($i = sizeof($exts); $i > 0; $i--) {
                if (in_array(strtolower($exts[$i - 1]), $protected)) {
                    $exts[$i] .= '.txt';
                    $ok = 1;
                    break;
                }
            }
            if ($ok) {
                $tname[1] = implode('.', $exts);
                $upfilename = $tname[1] . '.' . $fname[2];
            }
            # check the extention of the new file name.
            $fname[1] = $tname[1];
            $newfile_path = $dir . "/" . $tname[1] . ".{$fname['2']}";
            if ($tname[2] != $fname[2]) {
                if (strtolower($tname[2]) == strtolower($fname[2])) {
                    # change the case of the file ext. is allowed
                    $newfile_path = $dir . "/" . $tname[1] . ".{$tname['2']}";
                } else {
                    $err_msg[] = sprintf(_("It is not allowed to change file ext. \"%s\" to \"%s\"."), $fname[2], $tname[2]);
                }
            }
        }
        # is file already exists ?
        $dummy = 0;
        $myext = $fname[2] ? '.' . $fname[2] : '';
        while (@file_exists($newfile_path)) {
            $dummy = $dummy + 1;
            $ufname = $fname[1] . "_" . $dummy;
            // rename file
            $upfilename = $ufname . $myext;
            $newfile_path = $dir . "/" . $upfilename;
        }
        $upfile = $files['upfile']['tmp_name'][$j];
        if (!empty($files['upfile']['error'][$j]) and $files['upfile']['error'][$j] != UPLOAD_ERR_OK) {
            $err_msg[] = _("ERROR:") . ' <tt>' . $upload_err_func($files['upfile']['error'][$j]) . ' : ' . $upfilename . '</tt>';
            if ($files['upfile']['error'][$j] == UPLOAD_ERR_INI_SIZE) {
                $err_msg[] = "<tt>upload_max_filesize=" . ini_get('upload_max_filesize') . '</tt>';
            }
            continue;
        }
        $_l_path = _l_filename($file_path);
        $new_l_path = _l_filename($newfile_path);
        if (!empty($options['replace'][$j])) {
            // backup
            if ($newfile_path != $file_path) {
                $test = @copy($_l_path, $new_l_path);
            }
            // replace
            $test = @copy($upfile, $_l_path);
            $upfilename = $filename;
        } else {
            $test = @copy($upfile, $new_l_path);
        }
        @unlink($upfile);
        if (!$test) {
            $err_msg[] = sprintf(_("Fail to copy \"%s\" to \"%s\""), $upfilename, $file_path);
            if ($files['upfile']['error'][$j] == UPLOAD_ERR_INI_SIZE) {
                $err_msg[] = "<tt>upload_max_filesize=" . ini_get('upload_max_filesize') . '</tt>';
            }
            continue;
        }
        chmod($new_l_path, 0644);
        $comment .= "'{$upfilename}' ";
        $title .= (!empty($title) ? "\\n" : '') . sprintf(_("File \"%s\" is uploaded successfully"), $upfilename);
        $fullname = $formatter->page->name . "/{$upfilename}";
        $upname = $upfilename;
        if (strpos($fullname, ' ') !== false) {
            $fullname = '"' . $fullname . '"';
        }
        if (strpos($upname, ' ') !== false) {
            $upname = '"' . $upname . '"';
        }
        if ($key == 'UploadFile') {
            $msg[] = "<ins>attachment:/{$upname}</ins>";
            $upload_ok[] = '/' . $upname;
            $log_entry .= " * attachment:/{$upname}?action=deletefile . . . @USERNAME@ @DATE@\n";
        } else {
            $msg[] = "<ins>attachment:{$upname}</ins> or";
            $msg[] = "<ins>attachment:{$fullname}</ins>";
            $upload_ok[] = $upname;
            $log_entry .= " * attachment:{$fullname}?action=deletefile . . . @USERNAME@ @DATE@\n";
        }
    }
    // multiple upload
    $comment .= "uploaded";
    if (!empty($DBInfo->upload_changes)) {
        $p = $DBInfo->getPage($DBInfo->upload_changes);
        $raw_body = $p->_get_raw_body();
        if ($raw_body and $raw_body[strlen($raw_body) - 1] != "\n") {
            $raw_body .= "\n";
        }
        $raw_body .= $log_entry;
        $p->write($raw_body);
        $DBInfo->savePage($p, $comment, $options);
    } else {
        $DBInfo->addLogEntry($key, $REMOTE_ADDR, $comment, "UPLOAD");
    }
    if (!empty($options['action_mode']) and $options['action_mode'] == 'ajax') {
        $err = implode("\\n", $err_msg);
        $err = strip_tags($err);
        if ($err) {
            $err .= "\\n";
        }
        $formatter->header('Content-type: text/html; charset=' . $DBInfo->charset);
        $scr = '';
        if (!empty($options['domain']) and preg_match('/^[a-z][a-z0-9]+(\\.[a-z][a-z0-9]+)*$/i', $options['domain'])) {
            $scr = '<script type="text/javascript">document.domain="' . $options['domain'] . '";</script>';
        }
        echo $scr . '
    {"title": "' . str_replace(array('"', '<'), array("'", '&lt;'), $title) . '",
     "msg": ["' . $err . strip_tags(implode("\\n", $msg)) . '"],
     "uploaded":' . $uploaded . ',
     "files": ["' . implode("\"\n,\"", $upload_ok) . '"]
    }';
        return true;
    }
    $msgs = implode("<br />\n", $err_msg);
    $msgs .= implode("<br />\n", $msg);
    if (isset($options['retval'])) {
        $retval = array('title' => $title, 'msg' => $msgs, 'uploaded' => $uploaded, 'files' => $upload_ok);
        $ret =& $options['retval'];
        $ret = $retval;
        return true;
    }
    $formatter->send_header("", $options);
    if ($uploaded < 2) {
        $formatter->send_title($title, "", $options);
        print $msgs;
    } else {
        $msg = $title . '<br />' . $msg;
        $title = sprintf(_("Files are uploaded successfully"), $upfilename);
        $formatter->send_title($title, "", $options);
        print $msgs;
    }
    print $js;
    $formatter->send_footer('', $options);
    if (isset($options['MYFILES']) and is_array($options['MYFILES']) and session_id() != '') {
        session_destroy();
    }
    return true;
}
示例#26
0
 function _ci($key, $log, $force = false)
 {
     $dir = dirname($key);
     if (!is_dir($dir . '/RCS')) {
         $om = umask(00);
         _mkdir_p($dir . '/RCS', 2777);
         umask($om);
     }
     $mlog = '';
     $plog = '';
     if (getenv('OS') == 'Windows_NT' and isset($log[0])) {
         // win32 cmd.exe arguments do not accept UTF-8 charset correctly.
         // just use the stdin commit msg method instead of using -m"log" argument.
         $logfile = tempnam($this->DB->vartmp_dir, 'COMMIT_LOG');
         $fp = fopen($logfile, 'w');
         if (is_resource($fp)) {
             fwrite($fp, $log);
             fclose($fp);
             $plog = ' < ' . $logfile;
         }
     }
     if (empty($plog)) {
         $log = escapeshellarg($log);
         $mlog = ' -m' . $log;
     }
     // setup lockfile
     $lockfile = $key . '.##';
     touch($lockfile);
     $fl = fopen($key . '.##', 'w');
     $counter = 0;
     $locked = true;
     // lock timeout
     $timeout = isset($this->DB->savepage_timeout) && $this->DB->savepage_timeout > 5 ? $this->DB->savepage_timeout : 5;
     while (!flock($fl, LOCK_EX | LOCK_NB)) {
         if ($counter++ < $timeout) {
             sleep(1);
         } else {
             $locked = false;
             break;
         }
     }
     if ($locked) {
         if (!empty($this->DB->rcs_always_unlock)) {
             $fp = popen("rcs -l -M {$key}", 'r');
             if (is_resource($fp)) {
                 pclose($fp);
             }
         }
         // force option
         $f = '';
         if ($force) {
             $f = '-f ';
         }
         $fp = @popen("ci " . $f . "-l -x,v/ -q -t-\"" . $key . "\" " . $mlog . " " . $key . $plog . $this->NULL, "r");
         if (is_resource($fp)) {
             pclose($fp);
         }
         if (isset($plog[0])) {
             unlink($logfile);
         }
         flock($fl, LOCK_UN);
         fclose($fl);
         // remove lockfile
         unlink($lockfile);
         return 0;
     }
     // fail to get flock
     return -1;
 }
示例#27
0
文件: wiki.php 项目: sedrion/moniwiki
 function _savePage($pagename, $body, $options = array())
 {
     $keyname = $this->_getPageKey($pagename);
     $filename = $this->text_dir . '/' . $keyname;
     $dir = dirname($filename);
     if (!is_dir($dir)) {
         $om = umask(~$this->umask);
         _mkdir_p($dir, 0777);
         umask($om);
     }
     $is_new = false;
     if (!file_exists($filename)) {
         $is_new = true;
     }
     $fp = @fopen($filename, "a+b");
     if (!is_resource($fp)) {
         return -1;
     }
     flock($fp, LOCK_EX);
     // XXX
     ftruncate($fp, 0);
     fwrite($fp, $body);
     flock($fp, LOCK_UN);
     fclose($fp);
     $ret = 0;
     if (!empty($this->version_class)) {
         $om = umask(~$this->umask);
         $ver = $this->lazyLoad('version', $this);
         // get diff
         if (!$is_new) {
             $diff = $ver->diff($pagename);
             // count diff lines, chars
             $changes = diffcount_lines($diff, $this->charset);
             // set return values
             $retval =& $options['retval'];
             $retval['add'] = $changes[0];
             $retval['del'] = $changes[1];
             $retval['add_chars'] = $changes[2];
             $retval['del_chars'] = $changes[3];
         } else {
             // new file.
             // set return values
             $retval =& $options['retval'];
             $retval['add'] = get_file_lines($filename);
             $retval['del'] = 0;
             $retval['add_chars'] = mb_strlen($body, $this->charset);
             $retval['del_chars'] = 0;
         }
         $force = $is_new || $options['.force'];
         // FIXME fix for revert+create cases for clear
         if ($is_new && preg_match('@;;{REVERT}@', $options['log'])) {
             $tmp = preg_replace('@;;{REVERT}:@', ';;{CREATE}{REVERT}:', $options['log']);
             if ($tmp !== null) {
                 $options['log'] = $tmp;
             }
         }
         $ret = $ver->_ci($filename, $options['log'], $force);
         if ($ret == -1) {
             $options['retval']['msg'] = _("Fail to save version information");
         }
         chmod($filename, 0666 & $this->umask);
         umask($om);
     }
     return $ret;
 }