Exemplo n.º 1
0
function do_Clip($formatter, $options)
{
    global $DBInfo;
    $enable_replace = 1;
    $keyname = $DBInfo->_getPageKey($options['page']);
    $_dir = str_replace("./", '', $DBInfo->upload_dir . '/' . $keyname);
    // support hashed upload dir
    if (!is_dir($_dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $prefix = get_hashed_prefix($keyname);
        $_dir = str_replace('./', '', $DBInfo->upload_dir . '/' . $prefix . $keyname);
    }
    $pagename = _urlencode($options['page']);
    $name = $options['value'];
    if (!$name) {
        $title = _("Fatal error !");
        $formatter->send_header("Status: 406 Not Acceptable", $options);
        $formatter->send_title($title, "", $options);
        print "<h2>" . _("No filename given") . "</h2>";
        $formatter->send_footer("", $options);
        return;
    }
    $pngname = _rawurlencode($name);
    //$imgpath="$_dir/$pngname";
    $imgpath = "{$pngname}";
    $imgparam = '';
    if (file_exists($_dir . '/' . $imgpath . '.png')) {
        $url = qualifiedUrl($DBInfo->url_prefix . '/' . $_dir . '/' . $imgpath . '.png');
        $imgparam = "<param name='image' value='{$url}' />";
    }
    $png_url = "{$imgpath}.png";
    $formatter->send_header("", $options);
    $formatter->send_title(_("Clipboard"), "", $options);
    $prefix = $formatter->prefix;
    $now = time();
    $url_exit = $formatter->link_url($pagename, "?ts={$now}");
    $url_save = $formatter->link_url($pagename, "?action=draw");
    $url_help = $formatter->link_url("ClipMacro");
    $pubpath = $DBInfo->url_prefix . "/applets/ClipPlugin";
    print "<h2>" . _("Cut & Paste a Clipboard Image") . "</h2>\n";
    print <<<APPLET
<applet code="clip"
 archive="clip.jar" codebase="{$pubpath}"
 width='200' height='200' align="center">
        <param name="pngpath"  value="{$png_url}" />
        <param name="savepath" value="{$url_save}" />
        <param name="viewpath" value="{$url_exit}" />
        <param name="compress" value="5" />
{$imgparam}
<b>NOTE:</b> You need a Java enabled browser to edit the drawing example.
</applet><br />
APPLET;
    $formatter->send_footer("", $options);
    return;
}
Exemplo n.º 2
0
function macro_MultiUpload($formatter, $value = '')
{
    global $Config;
    $GLOBALS['_id_multiupload_'] = empty($GLOBALS['_id_multiupload_']) ? 1 : ++$GLOBALS['_id_multiupload_'];
    $id = $GLOBALS['_id_multiupload_'];
    $formatter->register_javascripts('wikibits.js');
    $formatter->register_javascripts('uploader.js');
    $msg = _("Choose File");
    $msg2 = _("Upload files");
    $url = $formatter->link_url($formatter->page->urlname);
    $form = <<<EOS
  <form target='_blank' id="form-upload{$id}" method="post" action="{$url}" enctype="multipart/form-data">
  <div class='uploadForm' id="upload{$id}">
  <input type='hidden' name='action' value='UploadFile' />
  <input type='hidden' name='uploadid' value='form-upload{$id}' />
  <span style="position: relative;"><button onclick="return false;" class="add-file"><span>{$msg}</span></button>
  <input type="file" id="file-upload{$id}" name="upfile[]" size="50" multiple="multiple" style="position:absolute;left:-5;width:80px" class="form-file" /></span>
EOS;
    $multiform = <<<EOF
  <ul>
  </ul>
  <div>
  <button type="submit" class='upload-file' id='button-upload{$id}' name="upload"><span>{$msg2}</span></button>
  </div>
  </div>
  </form>
{$js}
EOF;
    if (!in_array('UploadedFiles', $formatter->actions)) {
        $formatter->actions[] = 'UploadedFiles';
    }
    while (!empty($formatter->preview) and !in_array('UploadFile', $formatter->actions)) {
        if (!empty($Config['use_preview_uploads'])) {
            global $DBInfo;
            $key = $DBInfo->pageToKeyname($formatter->page->name);
            $dir = $Config['upload_dir'] . '/' . $key;
            if (!is_dir($dir) and !empty($Config['use_hashed_upload_dir'])) {
                // support hashed upload_dir
                $prefix = get_hashed_prefix($key);
                $dir = $DBInfo->upload_dir . '/' . $prefix . $key;
            }
            if (!is_dir($dir)) {
                break;
            }
            $form = $formatter->macro_repl('UploadedFiles(tag=1)') . $form;
        }
        break;
    }
    return $script . $form . $multiform;
}
Exemplo n.º 3
0
function macro_UploadedFiles($formatter, $value = "", $options = "")
{
    global $DBInfo;
    $use_preview = $DBInfo->use_preview_uploads ? $DBInfo->use_preview_uploads : 0;
    $preview_width = 64;
    #$use_preview=0;
    $use_admin = 1;
    $use_fileinfo = 1;
    $js_tag = 0;
    $js_script = '';
    $uploader = '';
    // get user id
    if (empty($formatter->preview) && empty($options)) {
        $options = array();
        $options['id'] = $DBInfo->user->id;
    }
    if (isset($DBInfo->members) and !in_array($options['id'], $DBInfo->members)) {
        $use_admin = 0;
    }
    $iconset = 'gnome';
    $icon_dir = $DBInfo->imgs_dir . '/plugin/UploadedFiles/' . $iconset;
    $args = !empty($DBInfo->uploadedfiles_options) ? explode(',', $DBInfo->uploadedfiles_options) : array();
    $nargs = explode(',', $value);
    if (!empty($nargs)) {
        $args = array_merge($args, $nargs);
    }
    $value = '';
    $default_column = 8;
    $col = (!empty($options['col']) and $options['col'] > 0) ? (int) $options['col'] : $default_column;
    if (!empty($formatter->preview)) {
        $js_tag = 1;
        $use_preview = 1;
        $uploader = 'UploadForm';
        $use_admin = 0;
        $use_fileinfo = 0;
        $col = 10000;
    } else {
        if (!empty($options['preview'])) {
            $use_preview = 1;
            $use_admin = 0;
            $use_fileinfo = 0;
        }
    }
    if (!empty($options['tag'])) {
        # javascript tag mode
        $js_tag = 1;
        $use_preview = 1;
        $use_admin = 0;
        $use_fileinfo = 0;
        $col = 10000;
    }
    if ($use_fileinfo) {
        $col = 1;
    }
    $href_attr = '';
    $attr = '';
    if (!empty($DBInfo->use_lightbox) and !$js_tag) {
        $href_attr = ' rel="lightbox[upload]" ';
    }
    $nodir = 0;
    foreach ($args as $arg) {
        $arg = trim($arg);
        if (($p = strpos($arg, '=')) !== false) {
            $k = substr($arg, 0, $p);
            $v = substr($arg, $p + 1);
            if ($k == 'preview') {
                $use_preview = $v;
            } else {
                if ($k == 'nodir') {
                    $nodir = $v;
                } else {
                    if ($k == 'tag') {
                        $js_tag = 1;
                        $use_preview = 1;
                    }
                }
            }
        } else {
            $value = $arg;
        }
    }
    if (!isset($options['nodir'])) {
        $options['nodir'] = $nodir;
    }
    if (!empty($options['page'])) {
        $value = $options['page'];
    }
    // avoid to set the pagename of the "page,name" as "name"
    if ($js_tag) {
        $form = 'editform';
        $js_script = <<<EOS
      <script language="javascript" type="text/javascript">
/*<![CDATA[*/
// based on wikibits.js in the MediaWiki
// small fix to use opener in the dokuwiki.

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

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

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

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

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

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

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

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

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

\t\tif (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any
\t\t\tsubst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
\t\t} else {
\t\t\tsubst = tagOpen + myText + tagClose;
\t\t}
\t\ttxtarea.value = txtarea.value.substring(0, startPos) + subst +
\t\t\ttxtarea.value.substring(endPos, txtarea.value.length);
\t\ttxtarea.focus();
\t\t//set new selection
\t\tif (replaced) {
\t\t\tvar cPos = startPos+(tagOpen.length+myText.length+tagClose.length);
\t\t\ttxtarea.selectionStart = cPos;
\t\t\ttxtarea.selectionEnd = cPos;
\t\t} else {
\t\t\ttxtarea.selectionStart = startPos+tagOpen.length;   
\t\t\ttxtarea.selectionEnd = startPos+tagOpen.length+myText.length;
\t\t}\t
\t\ttxtarea.scrollTop = scrollTop;
  } else { // All others
    txtarea.value += tagOpen + myText + tagClose + " ";
    txtarea.focus();
  }
}
/*]]>*/
</script>
EOS;
    }
    if (!empty($DBInfo->download_action)) {
        $mydownload = $DBInfo->download_action;
    } else {
        $mydownload = 'download';
    }
    $checkbox = 'checkbox';
    $needle = "//";
    if (!empty($options['download']) || !empty($DBInfo->force_download)) {
        $force_download = 1;
        if (!empty($options['download'])) {
            $mydownload = $options['download'];
        }
    }
    if (!empty($options['needle'])) {
        $needle = '@' . $options['needle'] . '@i';
    }
    if (!empty($options['checkbox'])) {
        $checkbox = $options['checkbox'];
    }
    if (!in_array('UploadFile', $formatter->actions)) {
        $formatter->actions[] = 'UploadFile';
    }
    if ($value and $value != 'UploadFile') {
        $key = $DBInfo->pageToKeyname($value);
        //if ($force_download or $key != $value)
        $down_prefix = $formatter->link_url(_rawurlencode($value), "?action={$mydownload}&amp;value=");
        $dir = $DBInfo->upload_dir . "/{$key}";
    } else {
        $value = $formatter->page->urlname;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        //if ($force_download or $key != $formatter->page->name)
        $down_prefix = $formatter->link_url($formatter->page->urlname, "?action={$mydownload}&amp;value=");
        $dir = $DBInfo->upload_dir . "/{$key}";
    }
    // support hashed upload_dir
    if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
        $dir = $DBInfo->upload_dir . '/' . get_hashed_prefix($key) . $key;
    }
    if (!empty($force_download) or $key != $value) {
        $prefix = $down_prefix;
    }
    if (!empty($formatter->preview) and $formatter->page->name == $value) {
        $opener = '';
    } else {
        $opener = $value . ':';
    }
    if ($value != 'UploadFile' and file_exists($dir)) {
        $handle = opendir($dir);
    } else {
        $key = '';
        $value = 'UploadFile';
        if (!$force_download) {
            $prefix .= $prefix ? '/' : '';
        }
        $dir = $DBInfo->upload_dir;
        $handle = opendir($dir);
        $opener = '/';
    }
    $upfiles = array();
    $dirs = array();
    $per = !empty($DBInfo->uploadedfiles_per_page) ? $DBInfo->uploadedfiles_per_page : 100;
    // set nodir option to show only files
    if (!empty($options['needle']) && !isset($options['nodir'])) {
        $options['nodir'] = true;
    } else {
        if (!isset($options['nodir'])) {
            $options['nodir'] = false;
        }
    }
    // count files/dirs
    $count_files = 0;
    $count_dirs = 0;
    $uf = new Cache_text('settings');
    if (($info = $uf->fetch('uploadedfiles')) !== false) {
        $count_files = $info['files'];
        $count_dirs = $info['dirs'];
    } else {
        while (($file = readdir($handle)) !== false) {
            if ($file[0] == '.') {
                continue;
            }
            if (is_dir($dir . "/" . $file)) {
                $count_dirs++;
            } else {
                $count_files++;
            }
        }
        rewinddir($handle);
        // TTL = 1 day
        $uf->update('uploadedfiles', array('files' => $count_files, 'dirs' => $count_dirs), 60 * 60 * 24);
    }
    // XXX
    $plink = '';
    if (!empty($options['p'])) {
        $p = $options['p'] ? (int) $options['p'] : 1;
    } else {
        $p = 1;
    }
    $pfrom = ($p - 1) * $per;
    $pto = $pfrom + $per;
    $count = 0;
    while (($file = readdir($handle)) !== false) {
        if ($file[0] == '.') {
            continue;
        }
        if ($count >= $pfrom) {
            if (is_dir($dir . "/" . $file)) {
                if ($options['nodir']) {
                    continue;
                }
                if ($value == 'UploadFile') {
                    $dirs[] = $DBInfo->keyToPagename($file);
                }
            } else {
                if (preg_match($needle, $file) and $count >= $pfrom) {
                    if ($count < $pto) {
                        $upfiles[] = _p_filename($file);
                    }
                }
            }
        }
        $count++;
        if ($count >= $pto) {
            $plink = 1;
            break;
        }
    }
    closedir($handle);
    if (!$upfiles and !$dirs) {
        return "<h3>" . _("No files found") . "</h3>";
    }
    sort($upfiles);
    sort($dirs);
    $link = $formatter->link_url($formatter->page->urlname);
    $out = "<form method='post' action='{$link}'>";
    $out .= "<p><input type='hidden' name='action' value='DeleteFile' />\n";
    if ($key) {
        $out .= "<input type='hidden' name='value' value=\"{$value}\" />\n";
    }
    $out .= "</p><table style='border:0px' cellpadding='2' class='info'>\n";
    // set colspan to show file informations
    $c = 1;
    if ($use_admin) {
        $c = 2;
    }
    if ($c) {
        $colspan = ' colspan="' . $c . '"';
    }
    if ($use_fileinfo) {
        $mname = _("File name");
        $msize = _("Size");
        $mdate = _("Date");
        $out .= "<tr><th{$colspan}>{$mname}</th><th>{$msize}</th><th>{$mdate}</th></tr>\n";
        $c += 2;
    }
    // set colspan again
    if ($c > 1) {
        $colspan = ' colspan="' . $c . '"';
    }
    $idx = 1;
    if ($js_tag) {
        #$attr=' target="_blank"';
        $extra = '&amp;popup=1&amp;tag=1';
    } else {
        $attr = '';
        $extra = '';
    }
    // support hashed upload_dir
    if (!empty($DBInfo->use_hashed_upload_dir)) {
        $ndirs = array();
        foreach ($dirs as $d0) {
            if (strlen($d0) != 1) {
                $ndirs[] = $d0;
                continue;
            }
            $handle = opendir($DBInfo->upload_dir . '/' . $d0);
            if (!is_resource($handle)) {
                continue;
            }
            $pre = $DBInfo->upload_dir . '/' . $d0;
            while (($d = readdir($handle)) !== false) {
                if (!is_dir($pre . '/' . $d)) {
                    $ndirs[] = $d0;
                    break;
                }
                if ($d[0] == $d0[0]) {
                    $hd = opendir($pre . '/' . $d);
                    if (!is_resource($hd)) {
                        continue;
                    }
                    $pre1 = $pre . '/' . $d;
                    while (($d1 = readdir($hd)) !== false) {
                        if ($d1[0] == '.') {
                            continue;
                        }
                        if (is_dir($pre1 . '/' . $d1)) {
                            $ndirs[] = $d1;
                        }
                    }
                    closedir($hd);
                }
            }
            closedir($handle);
        }
        $dirs = $ndirs;
        sort($dirs);
    }
    // count dirs
    $didx = 0;
    if (count($dirs)) {
        $out .= "<tr>";
        $didx++;
    }
    foreach ($dirs as $file) {
        $link = $formatter->link_url($file, "?action=uploadedfiles{$extra}", $file, $attr);
        $key = $DBInfo->pageToKeyname($file);
        // support hashed upload_dir
        $pre = '';
        if (!empty($DBInfo->use_hashed_upload_dir)) {
            $pre = get_hashed_prefix($key);
            if (!is_dir($dir . '/' . $pre . $key)) {
                $pre = '';
            }
        }
        $dirname = $dir . '/' . $pre . $key;
        $date = date("Y-m-d", filemtime($dirname));
        $file = _html_escape($file);
        if ($use_admin) {
            $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>";
        }
        $out .= "<td class='wiki'><a href='{$link}'>{$file}/</a></td>";
        if ($use_fileinfo) {
            $out .= "<td align='right' class='wiki'>&nbsp;</td><td class='wiki'>{$date}</td>";
        }
        if ($didx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        $idx++;
        $didx++;
    }
    if (isset($value[0]) and $value != 'UploadFile') {
        if ($js_tag) {
            #$attr=' target="_blank"';
            $extra = '&amp;popup=1&amp;tag=1';
        }
        if (!empty($options['needle'])) {
            $extra .= '&amp;q=' . $options['needle'];
        }
        $link = $formatter->link_tag('UploadFile', "?action=uploadedfiles&amp;value=top{$extra}", "<img src='" . $icon_dir . "/32/up.png' style='border:0' class='upper' alt='..' />", $attr);
        $out .= "<tr>";
        if ($use_admin) {
            $out .= "<td class='wiki'>&nbsp;</td>";
        }
        $out .= "<td class='wiki'>{$link}</td>";
        if ($use_fileinfo) {
            $date = date("Y-m-d", filemtime($dir . "/.."));
            $out .= "<td align='right' class='wiki'>&nbsp;</td><td class='wiki'>{$date}</td>";
        }
        if ($didx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        $didx++;
    }
    if (!empty($options['needle'])) {
        $extra .= '&amp;q=' . $options['needle'];
    }
    if (isset($options['nodir'])) {
        $extra .= '&amp;nodir=' . $options['nodir'];
    }
    if ($plink) {
        $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}&amp;p=" . ($p + 1), _("Next page &raquo;"), $attr);
    } else {
        if ($p > 1) {
            $plink = $formatter->link_tag('', "?action=uploadedfiles{$extra}", _("&laquo; First page"), $attr);
        }
    }
    if (empty($prefix)) {
        $prefix = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir) . '/';
    }
    $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
    $down_mode = strpos($prefix, ';value=') !== false;
    $mywidth = $preview_width;
    if (empty($didx)) {
        // no dirs found.
        $out .= '<tr>';
    }
    $iidx = $didx;
    // file index
    foreach ($upfiles as $file) {
        $_l_file = _l_filename($file);
        // force download with some extensions. XXX
        if ($down_mode or preg_match('/\\.(pl|cgi|py|php.?)$/', $file)) {
            $link = str_replace(";value=", ";value=" . rawurlencode($file), $down_prefix);
        } else {
            $link = $prefix . rawurlencode($file);
        }
        // XXX
        $previewlink = $link;
        $size = filesize($dir . '/' . $_l_file);
        if (!empty($use_preview)) {
            preg_match("/\\.(.{1,4})\$/", $file, $m);
            $ext = isset($m[1]) ? strtolower($m[1]) : '';
            if ($use_preview > 1 and $ext and stristr('gif,png,jpeg,jpg', $ext)) {
                list($w, $h) = getimagesize($dir . '/' . $file);
                if ($w <= $preview_width) {
                    $mywidth = $w;
                } else {
                    $mywidth = $preview_width;
                }
                if (file_exists($dir . "/thumbnails/" . $_l_file)) {
                    if ($down_mode) {
                        $previewlink = str_replace('value=', 'value=thumbnails/', $previewlink);
                    } else {
                        $previewlink = $prefix . 'thumbnails/' . rawurlencode($file);
                    }
                }
            }
        }
        if (!empty($use_fileinfo)) {
            $i = 0;
            for (; $i < 4; $i++) {
                if ($size <= 1024) {
                    #$size= round($size,2).' '.$unit[$i];
                    break;
                }
                $size = $size / 1024;
            }
            $size = round($size, 2) . ' ' . $unit[$i];
        }
        $date = date('Y-m-d', filemtime($dir . '/' . $_l_file));
        $fname = $file;
        if ($use_preview or $js_tag) {
            $tag_open = 'attachment:';
            $tag_close = '';
            if ($opener != $value) {
                $tag_open .= $opener;
            }
            $alt = "alt='{$tag_open}{$file}{$tag_close}' title='{$file}'";
            if ($ext and stristr('gif,png,jpeg,jpg', $ext)) {
                $fname = "<img src='{$previewlink}' class='icon' width='{$mywidth}' {$alt} />";
                $attr .= $href_attr;
            } else {
                if (preg_match('/^(wmv|avi|mpeg|mpg|swf|wav|mp3|ogg|midi|mid|mov)$/', $ext)) {
                    $tag_open = '[[Media(';
                    $tag_close = ')]]';
                    $alt = "{$tag_open}{$file}{$tag_close}";
                } else {
                    if (!preg_match('/^(bmp|c|h|java|py|bak|diff|doc|css|php|xml|html|mod|' . 'rpm|deb|pdf|ppt|xls|tgz|gz|bz2|zip)$/', $ext)) {
                        $ext = 'unknown';
                    }
                }
                $fname = "<img src='{$icon_dir}/{$ext}.png' class='icon' {$alt} /><span>{$file}</span>";
            }
            if ($js_tag) {
                //if (strpos($file,' '))
                $tag = "insertTags('{$tag_open}','{$tag_close}','{$file}',true)";
                $link = "javascript:{$tag}";
            }
        }
        $file = _html_escape($file);
        if ($use_admin) {
            $out .= "<td class='wiki'><input type='{$checkbox}' name='files[{$idx}]' value=\"{$file}\" /></td>";
        }
        $out .= "<td class='wiki'><a href=\"{$link}\"{$attr}>{$fname}</a></td>";
        if ($use_fileinfo) {
            $out .= "<td align='right' class='wiki'>{$size}</td><td class='wiki'>{$date}</td>";
        }
        if ($iidx % $col == 0) {
            $out .= "</tr>\n<tr>\n";
        }
        if ($use_admin && $use_fileinfo) {
            $out .= "<td>&nbsp;</td><td{$colspan}>";
            if ($use_admin) {
                $out .= $dir . '/';
            }
            $out .= "{$file}</td>\n";
            $out .= "</tr>\n<tr>";
        }
        $idx++;
        $iidx++;
    }
    $kidx = $iidx - 1;
    $k = 0;
    // setup colspan to fill up <tr> with colspaned <td>
    while ($kidx % $col != 0) {
        $k += $c;
        $kidx++;
    }
    if ($k > 0) {
        // fill tr
        $out .= '<td colspan="' . $k . '">&nbsp;</td>';
    }
    if (substr($out, -4) == '<tr>') {
        $out = substr($out, 0, -4);
    } else {
        $out .= "</tr>\n";
    }
    $idx--;
    $msg = sprintf(_("%d files"), $idx);
    if (count($dirs)) {
        $msg .= ' / ' . sprintf(_("Total %d files"), $count_files);
        $msg .= ' / ' . sprintf(_("%d dirs"), $count_dirs);
    }
    // colspan for multi column case.
    if ($col > 1) {
        $colspan = ' colspan="' . $col * $c . '"';
    }
    $out .= "<tr>";
    if ($use_admin && $c > 1) {
        $out .= "<td>&nbsp;</td>";
    }
    // fill checkbox column
    $out .= "<th {$colspan}>{$msg}</th></tr>\n";
    if ($plink) {
        $out .= "<tr><th {$colspan}>{$plink}</th></tr>\n";
    }
    $out .= "</table>\n";
    if ($use_admin) {
        if ($DBInfo->security->is_protected("deletefile", $options)) {
            $out .= '<p>' . _("Password") . ": <input type='password' name='passwd' size='10' /></p>\n";
        }
        $out .= "<p><input type='submit' value='" . _("Delete selected files") . "' /></p>";
    }
    $out .= "</form>\n";
    if (!$value and !in_array('UploadFile', $formatter->actions)) {
        $formatter->actions[] = 'UploadFile';
    }
    if ($uploader and !in_array('UploadedFiles', $formatter->actions)) {
        $out .= $formatter->macro_repl($uploader);
    }
    if ($use_preview) {
        $class = ' class="fileList preview"';
        return $js_script . "<div{$class}>" . $out . "</div>\n";
    }
    return $js_script . $out;
}
Exemplo n.º 4
0
function macro_TitleIndex($formatter, $value, $options = array())
{
    global $DBInfo;
    $pc = !empty($DBInfo->titleindex_pagecount) ? intval($DBInfo->titleindex_pagecount) : 100;
    if ($pc < 1) {
        $pc = 100;
    }
    $pg = empty($options['p']) ? 1 : intval($options['p']);
    if ($pg < 1) {
        $pg = 1;
    }
    $group = $formatter->group;
    $key = -1;
    $keys = array();
    if ($value == '' or $value == 'all') {
        $sel = '';
    } else {
        $sel = ucfirst($value);
    }
    // get all keys
    $all_keys = get_keys();
    if (isset($sel[0])) {
        if (!isset($all_keys[$sel])) {
            $sel = key($all_keys);
        }
        // default
    }
    if (@preg_match('/' . $sel . '/i', '') === false) {
        $sel = '';
    }
    $titleindex = array();
    // cache titleindex
    $kc = new Cache_text('titleindex');
    $delay = !empty($DBInfo->default_delaytime) ? $DBInfo->default_delaytime : 0;
    $uid = '';
    if (function_exists('posix_getuid')) {
        $uid = '.' . posix_getuid();
    }
    $lock_file = _fake_lock_file($DBInfo->vartmp_dir, 'titleindex' . $uid);
    $locked = _fake_locked($lock_file, $DBInfo->mtime());
    if ($locked or $kc->exists('key') and $DBInfo->checkUpdated($kc->mtime('key'), $delay)) {
        if (!empty($formatter->use_group) and $formatter->group) {
            $keys = $kc->fetch('key.' . $formatter->group);
            $titleindex = $kc->fetch('titleindex.' . $formatter->group);
        } else {
            $keys = $kc->fetch('key');
            $titleindex = $kc->fetch('titleindex' . $sel);
        }
        if (isset($sel[0]) and isset($titleindex[$sel])) {
            $all_pages = $titleindex[$sel];
        }
        if (empty($titleindex) and $locked) {
            // no cache found
            return _("Please wait...");
        }
    }
    if (empty($all_pages)) {
        $all_pages = array();
        $indexer = $DBInfo->lazyLoad('titleindexer');
        if (!empty($formatter->use_group) and $formatter->group) {
            $group_pages = $indexer->getLikePages('^' . $formatter->group);
            foreach ($group_pages as $page) {
                $all_pages[] = str_replace($formatter->group, '', $page);
            }
        } else {
            $all_pages = $indexer->getLikePages('^' . $all_keys[$sel], 0);
        }
        #natcasesort($all_pages);
        #sort($all_pages,SORT_STRING);
        //usort($all_pages, 'strcasecmp');
        $pages = array_flip($all_pages);
        if (!empty($formatter->use_group)) {
            array_walk($pages, '_setpagekey');
        } else {
            array_walk($pages, create_function('&$p, $k', '$p = $k;'));
        }
        $all_pages = array_flip($pages);
        uksort($all_pages, 'strcasecmp');
    }
    if (empty($keys) or empty($titleindex)) {
        _fake_lock($lock_file);
        foreach ($all_pages as $page => $rpage) {
            $p = ltrim($page);
            $pkey = get_key("{$p}");
            if ($key != $pkey) {
                $key = $pkey;
                //$keys[] = $pkey;
                if (!isset($titleindex[$pkey])) {
                    $titleindex[$pkey] = array();
                }
            }
            $titleindex[$pkey][$page] = $rpage;
        }
        $keys = array_keys($all_keys);
        if (!empty($tlink)) {
            $keys[] = 'all';
        }
        if (!empty($formatter->use_group) and $formatter->group) {
            $kc->update('key.' . $formatter->group, $keys);
            $kc->update('titleindex.' . $formatter->group, $titleindex);
        } else {
            $kc->update('key', $keys);
            $kc->update('titleindex' . $sel, $titleindex);
        }
        if (isset($sel[0]) and isset($titleindex[$sel])) {
            $all_pages = $titleindex[$sel];
        }
        _fake_lock($lock_file, LOCK_UN);
    }
    $pnut = null;
    if (isset($sel[0]) and count($all_pages) > $pc) {
        $pages_number = intval(count($all_pages) / $pc);
        if (count($all_pages) % $pc) {
            $pages_number++;
        }
        $pages = array_keys($all_pages);
        $pages = array_splice($pages, ($pg - 1) * $pc, $pc);
        $selected = array();
        foreach ($pages as $p) {
            $selected[$p] = $all_pages[$p];
        }
        $pages = $selected;
        $pnut = get_pagelist($formatter, $pages_number, '?action=titleindex&amp;sec=' . $sel . '&amp;p=', !empty($pg) ? $pg : 1);
    } else {
        $pages =& $all_pages;
    }
    //print count($all_pages);
    //exit;
    $out = '';
    #  if ($DBInfo->use_titlecache)
    #    $cache=new Cache_text('title');
    $key = '';
    foreach ($pages as $page => $rpage) {
        $p = ltrim($page);
        $pkey = get_key("{$p}");
        if ($key != $pkey) {
            $key = $pkey;
            if (isset($sel[0]) and !preg_match('/^' . $sel . '/i', $pkey)) {
                continue;
            }
            if (!empty($out)) {
                $out .= "</ul>";
            }
            $out .= "<a name='{$key}'></a><h3><a href='#top'>{$key}</a></h3>\n";
            $out .= "<ul>";
        }
        if (isset($sel[0]) and !preg_match('/^' . $sel . '/i', $pkey)) {
            continue;
        }
        #
        #    if ($DBInfo->use_titlecache and $cache->exists($page))
        #      $title=$cache->fetch($page);
        #    else
        $title = get_title($rpage, $page);
        #$out.= '<li>' . $formatter->word_repl('"'.$page.'"',$title,'',0,0);
        $urlname = _urlencode($group . $rpage);
        $out .= '<li>' . $formatter->link_tag($urlname, '', _html_escape($title));
        $keyname = $DBInfo->pageToKeyname(urldecode($rpage));
        if (is_dir($DBInfo->upload_dir . "/{$keyname}") or !empty($DBInfo->use_hashed_upload_dir) and is_dir($DBInfo->upload_dir . '/' . get_hashed_prefix($keyname) . $keyname)) {
            $out .= ' ' . $formatter->link_tag($urlname, "?action=uploadedfiles", $formatter->icon['attach']);
        }
        $out .= "</li>\n";
    }
    if (!empty($pnut)) {
        $out .= '<li style="list-style:none">' . $pnut . '</li>' . "\n";
    }
    $out .= "</ul>\n";
    $index = '';
    $tlink = '';
    if (isset($sel[0])) {
        $tlink = $formatter->link_url($formatter->page->urlname, '?action=titleindex&amp;sec=');
    }
    $index = array();
    foreach ($keys as $key) {
        $name = strval($key);
        $tag = '#' . $key;
        $link = !empty($tlink) ? preg_replace('/sec=/', 'sec=' . _urlencode($key), $tlink) : '';
        if ($name == 'Others') {
            $name = _("Others");
        } else {
            if ($name == 'all') {
                $name = _("Show all");
            }
        }
        $index[] = "<a href='{$link}{$tag}'>{$name}</a>";
    }
    $str = implode(' | ', $index);
    return "<center><a name='top'></a>{$str}</center>\n{$out}";
}
Exemplo n.º 5
0
function do_download($formatter, $options)
{
    global $DBInfo;
    if (!$options['value']) {
        if (!function_exists('do_uploadedfiles')) {
            include_once dirname(__FILE__) . '/UploadedFiles.php';
        }
        do_uploadedfiles($formatter, $options);
        return;
    }
    $value =& $options['value'];
    $down_mode = (!empty($options['mode']) and $options['mode'][0] == 'a') ? 'attachment' : (!empty($DBInfo->download_mode) ? $DBInfo->download_mode : 'inline');
    // SubPage:foobar.png == SubPage/foobar.png
    // SubPage:thumbnails/foobar.png == SubPage/thumbnails/foobar.png
    // SubPage/FoobarPage:thumbnails/foobar.png == SubPage/FoobarPage/thumbnails/foobar.png
    // check acceptable subdirs
    $acceptable_subdirs = array('thumbnails');
    $tmp = explode('/', $value);
    $subdir = '';
    if (($c = count($tmp)) > 1) {
        if (in_array($tmp[$c - 2], $acceptable_subdirs)) {
            $subdir = $tmp[$c - 2] . '/';
            unset($tmp[$c - 2]);
            $value = implode('/', $tmp);
        }
    }
    if (($p = strpos($value, ':')) !== false or ($p = strrpos($value, '/')) !== false) {
        $subpage = substr($value, 0, $p);
        $file = substr($value, $p + 1);
        $value = $subpage . '/' . $file;
        # normalize page arg
        if ($subpage and $DBInfo->hasPage($subpage)) {
            $pagename =& $subpage;
            $key = $DBInfo->pageToKeyname($subpage);
        }
    }
    if (!isset($pagename[0])) {
        $pagename =& $formatter->page->name;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
    }
    $prefix = '';
    if (isset($key[0])) {
        // for compatibility
        $dir = $DBInfo->upload_dir . '/' . $key;
        if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
            // support hashed upload_dir
            $prefix = get_hashed_prefix($key);
            $dir = $DBInfo->upload_dir . '/' . $prefix . $key;
        }
    }
    if ($value[0] == '/' or $key == 'UploadFile') {
        $dir = $DBInfo->upload_dir;
    }
    if (file_exists($dir)) {
        $handle = opendir($dir);
    } else {
        $dir = $DBInfo->upload_dir;
        $handle = opendir($dir);
    }
    $file = explode('/', $value);
    $file = $file[count($file) - 1];
    $params = $options;
    // copy request params
    /**
     * Thumbnail feature
     *
     * foo/bar/foo.png
     * - pagename = foo/bar
     * - attached image = foo.png
     * foo/bar/foo.png?thumb=1
     * - generate thumbnail with default width
     * foo/bar/foo.png?thumbwidth=320
     * - generate thumbnails/foo.w320.png
     *   if 320 is acceptable width
     * foo/bar/thumbnails/foo.w320.png
     * == foo/bar/foo.png?thumbwidth=320
     * foo/bar/foo.w320.png
     * == foo/bar/foo.png?thumbwidth=320
     * you can also upload foo.w320.png manually
     */
    // check thumbnail width from filename
    if (preg_match('@(\\.w(\\d+)\\.(png|jpe?g|gif))$@i', $file, $m)) {
        // drop w320 from given filename
        $orgfile = substr($file, 0, -strlen($m[1])) . '.' . $m[3];
        $params['thumbwidth'] = $m[2];
        unset($params['thumb']);
    }
    // check file exists
    $tmp = _l_filename($file);
    if (file_exists($dir . '/' . $subdir . $tmp)) {
        $_l_file = $subdir . $tmp;
        if (!empty($orgfile)) {
            unset($orgfile);
            // no need to generate thumbnails
            unset($params['thumbwidth']);
            $nothumb = true;
        }
    } else {
        $_l_file = !empty($orgfile) ? _l_filename($orgfile) : _l_filename($file);
        if (!file_exists("{$dir}/{$_l_file}")) {
            header("HTTP/1.1 404 Not Found");
            echo "File not found";
            return;
        }
    }
    $lines = @file($DBInfo->data_dir . '/mime.types');
    if ($lines) {
        foreach ($lines as $line) {
            rtrim($line);
            if (preg_match('/^\\#/', $line)) {
                continue;
            }
            $elms = preg_split('/\\s+/', $line);
            $type = array_shift($elms);
            foreach ($elms as $elm) {
                $mime[$elm] = $type;
            }
        }
    } else {
        $mime = array();
    }
    $realfile = $dir . '/' . $_l_file;
    # set filename
    if (preg_match("/\\.(.{1,4})\$/", $file, $match)) {
        $ext = strtolower($match[1]);
        $mimetype = !empty($mime[$ext]) ? $mime[$ext] : '';
        $ext = '.' . $ext;
    }
    // auto generate thumbnails
    if (empty($nothumb) and !empty($mimetype) and preg_match('@image/(png|jpe?g|gif)$@', $mimetype)) {
        list($w, $h) = getimagesize($realfile);
        $thumbfile = '';
        if (!empty($params['thumbwidth'])) {
            // check allowed thumb widths.
            $thumb_widths = isset($DBInfo->thumb_widths) ? $DBInfo->thumb_widths : array('120', '240', '320', '480', '600', '800', '1024');
            $width = 320;
            // default
            if (!empty($DBInfo->default_thumb_width)) {
                $width = $DBInfo->default_thumb_width;
            }
            if (!empty($thumb_widths)) {
                if (in_array($params['thumbwidth'], $thumb_widths)) {
                    $width = $params['thumbwidth'];
                } else {
                    header("HTTP/1.1 404 Not Found");
                    echo "Invalid thumbnail width", "<br />", "valid thumb widths are ", implode(', ', $thumb_widths);
                    return;
                }
            } else {
                $width = $params['thumbwidth'];
            }
            if ($w > $width) {
                $thumb_width = $width;
                $force_thumb = true;
            }
        } else {
            // automatically generate thumb images to support low-bandwidth mobile version
            if ($params['is_mobile']) {
                $force_thumb = (!isset($params['m']) or $params['m'] == 1);
            } else {
                if (!isset($params['thumb']) and !empty($DBInfo->max_image_width) and $w > $DBInfo->max_image_width) {
                    $force_thumb = true;
                    $thumb_width = $DBInfo->max_image_width;
                }
            }
        }
        while (!empty($params['thumb']) or $force_thumb) {
            if (empty($thumb_width)) {
                $thumb_width = 320;
                // default
                if (!empty($DBInfo->default_thumb_width)) {
                    $thumb_width = $DBInfo->default_thumb_width;
                }
            }
            $thumbfiles = array();
            $thumbname = preg_replace('@' . $ext . '$@i', '.w' . $thumb_width . $ext, $_l_file);
            $thumbfiles[] = $thumbname;
            $thumbfiles[] = 'thumbnails/' . $thumbname;
            foreach ($thumbfiles as $file) {
                $thumbfile = $dir . '/' . $file;
                if (file_exists($thumbfile)) {
                    $thumb_ok = true;
                    break;
                }
            }
            if ($thumb_ok) {
                break;
            }
            if ($w <= $thumb_width) {
                if (!empty($orgfile)) {
                    header("HTTP/1.1 404 Not Found");
                    echo "the thumbnail width have to smaller than original";
                    return;
                }
                $thumbfile = $realfile;
                break;
            }
            if (!file_exists($dir . "/thumbnails")) {
                @mkdir($dir . "/thumbnails", 0777);
            }
            require_once 'lib/mediautils.php';
            // generate thumbnail using the gd func or the ImageMagick(convert)
            resize_image($ext, $realfile, $thumbfile, $w, $h, $thumb_width);
            break;
        }
        if (!empty($thumbfile)) {
            $realfile = $thumbfile;
        }
    }
    if (empty($mimetype)) {
        $mimetype = "application/x-unknown";
    }
    if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        // IE: rawurlencode()
        $fn = preg_replace('/[:\\x5c\\/*?"<>|]/', '_', $file);
        $fname = 'filename="' . rawurlencode($fn) . '"';
        // fix IE bug
        $fname = preg_replace('/\\./', '%2e', $fname, substr_count($fname, '.') - 1);
        #header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        #header('Pragma: public');
    } else {
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'Mozilla')) {
            // Mozilla: RFC 2047
            $fname = 'filename="=?' . $DBInfo->charset . '?B?' . base64_encode($file) . '?="';
        } else {
            // etc. Safari, Opera 9: RFC 2231
            $fn = preg_replace('/[:\\x5c\\/{?]/', '_', $file);
            $fname = 'filename*=' . $DBInfo->charset . "''" . rawurlencode($fn) . '';
            //$fname='filename="'.$fn.'"';
        }
    }
    if (!empty($DBInfo->use_resume_download)) {
        $header = array("Content-Description: MoniWiki PHP Downloader");
        dl_file_resume($mimetype, $realfile, $fname, $down_mode, $header);
        return;
    }
    header("Content-Type: {$mimetype}\r\n");
    header("Content-Length: " . filesize($realfile));
    header("Content-Disposition: {$down_mode}; " . $fname);
    header("Content-Description: MoniWiki PHP Downloader");
    $mtime = filemtime($realfile);
    $lastmod = gmdate("D, d M Y H:i:s", $mtime) . ' GMT';
    $etag = md5($lastmod . $thumbfile);
    header("Last-Modified: " . $lastmod);
    header('ETag: "' . $etag . '"');
    header("Pragma:");
    $maxage = 60 * 60 * 24 * 7;
    header('Cache-Control: public, max-age=' . $maxage);
    $need = http_need_cond_request($mtime, $lastmod, $etag);
    if (!$need) {
        header('X-Cache-Debug: Cached OK');
        header('HTTP/1.0 304 Not Modified');
        @ob_end_clean();
        return;
    }
    $fp = readfile($realfile);
    return;
}
Exemplo n.º 6
0
function macro_Attachment($formatter, $value, $options = array())
{
    global $DBInfo;
    if (!is_array($options) and $options == 1) {
        $options = array('link' => 1);
    }
    // compatible
    $attr = '';
    if (!empty($DBInfo->force_download) or !empty($DBInfo->pull_url)) {
        $force_download = 1;
    }
    if (!empty($DBInfo->download_action)) {
        $mydownload = $DBInfo->download_action;
    } else {
        $mydownload = 'download';
    }
    $extra_action = '';
    $pull_url = $fetch_url = '';
    if (!empty($DBInfo->pull_url)) {
        $pull_url = $DBInfo->pull_url;
        if (empty($formatter->fetch_action)) {
            $fetch_url = $formatter->link_url('', '?action=fetch&url=');
        } else {
            $fetch_url = $formatter->fetch_action;
        }
    }
    $text = '';
    $caption = '';
    $cap_bra = '';
    $cap_ket = '';
    $bra = '';
    $ket = '';
    if ($options and !$DBInfo->security->is_allowed($mydownload, $options)) {
        return $text;
    }
    if (!empty($formatter->wikimarkup) and empty($options['nomarkup'])) {
        $ll = $rr = '';
        if (strpos($value, ' ') !== false) {
            $ll = '[';
            $rr = ']';
        }
        $bra = "<span class='wikiMarkup'><!-- wiki:\n{$ll}attachment:{$value}{$rr}\n-->";
        $ket = '</span>';
    }
    #  if ($value[0]=='"' and ($p2=strpos(substr($value,1),'"')) !== false)
    #    $value=substr($value,1,$p2); # attachment:"my image.png" => my image.png
    # FIXME attachment:"hello.png" => error
    if (($p = strpos($value, ' ')) !== false and strpos(substr($value, 0, $p), ',') === false) {
        // [[Attachment(my.png,width=100,height=200,caption="Hello(space)World")]]
        // [attachment:my.ext(space)hello]
        // [attachment:my.ext(space)attachment:my.png]
        // [attachment:my.ext(space)http://url/../my.png]
        if ($value[0] == '"' and ($p2 = strpos(substr($value, 1), '"')) !== false) {
            $text = $ntext = substr($value, $p2 + 3);
            $dummy = substr($value, 1, $p2);
            # "my image.png" => my image.png
            $args = substr($value, $p2 + 2);
            $value = $dummy . $args;
            # append query string
        } else {
            $text = $ntext = substr($value, $p + 1);
            $value = substr($value, 0, $p);
        }
        if (substr($text, 0, 11) == 'attachment:') {
            $fname = substr($text, 11);
            $ntext = macro_Attachment($formatter, $fname, array('link' => 1));
        }
        if (preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $ntext)) {
            $_l_ntext = _l_filename($ntext);
            if (!file_exists($_l_ntext)) {
                $fname = preg_replace('/^"([^"]*)"$/', "\\1", $fname);
                $mydownload = 'UploadFile&amp;rename=' . $fname;
                $text = sprintf(_("Upload new Attachment \"%s\""), $fname);
                $text = str_replace('"', '\'', $text);
            }
            $ntext = qualifiedUrl($DBInfo->url_prefix . '/' . $ntext);
            $img_link = '<img src="' . $ntext . '" alt="' . $text . '" border="0" />';
        } else {
            if (($q = strpos($ntext, ',')) !== false) {
                $alt = substr($ntext, 0, $q);
                $caption = substr($ntext, $q + 1);
            } else {
                $alt = $ntext;
            }
        }
    } else {
        $value = str_replace('%20', ' ', $value);
    }
    $lightbox_attr = '';
    $imgalign = '';
    // allowed thumb widths.
    $thumb_widths = isset($DBInfo->thumb_widths) ? $DBInfo->thumb_widths : array('120', '240', '320', '480', '600', '800', '1024');
    // parse query string of macro arguments
    if ($dummy = strpos($value, '?')) {
        # for attachment: syntax
        parse_str(substr($value, $dummy + 1), $attrs);
        $value = substr($value, 0, $dummy);
    } else {
        if (($dummy = strpos($value, ',')) !== false) {
            # for Attachment macro
            $tmp = substr($value, $dummy + 1);
            $tmp = preg_replace('/,+\\s*/', ',', $tmp);
            $tmp = preg_replace('/\\s*=\\s*/', '=', $tmp);
            $tmp = str_replace(',', '&', $tmp);
            parse_str($tmp, $attrs);
            $value = substr($value, 0, $dummy);
        }
    }
    $use_thumb = !empty($DBInfo->use_thumb_by_default) && empty($options['link_url']) ? true : false;
    if (!empty($attrs)) {
        if (!empty($attrs['action'])) {
            // check extra_action
            if ($attrs['action'] == 'deletefile') {
                $extra_action = $attrs['action'];
            } else {
                $mydownload = $attrs['action'];
            }
            unset($attrs['action']);
        }
        foreach ($attrs as $k => $v) {
            if (in_array($k, array('width', 'height'))) {
                $attr .= "{$k}=\"{$v}\" ";
                if (!empty($DBInfo->use_lightbox)) {
                    $lightbox_attr = ' rel="lightbox" ';
                }
            } else {
                if ($k == 'align') {
                    $imgalign = 'img' . ucfirst($v);
                } else {
                    if (in_array($k, array('caption', 'alt', 'title'))) {
                        $caption = preg_replace("/^([\"'])([^\\1]+)\\1\$/", "\\2", $v);
                        $caption = trim($caption);
                    } else {
                        if (in_array($k, array('thumb', 'thumbwidth', 'thumbheight'))) {
                            if ($k == 'thumbwidth' || $k == 'thumbheight') {
                                if (!empty($thumb_widths)) {
                                    if (in_array($v, $thumb_widths)) {
                                        $thumb[$k] = $v;
                                    }
                                } else {
                                    $thumb[$k] = $v;
                                }
                            } else {
                                $thumb[$k] = $v;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($thumb)) {
            $use_thumb = true;
        }
    }
    if (preg_match('/^data:image\\/(gif|jpe?g|png);base64,/', $value)) {
        // need to hack for IE ?
        return "<img src='" . $value . "' {$attr} />";
    }
    $attr .= $lightbox_attr;
    $info = '';
    if (($p = strrpos($value, ':')) !== false or ($p = strrpos($value, '/')) !== false) {
        $subpage = substr($value, 0, $p);
        $file = substr($value, $p + 1);
        $value = $subpage . '/' . $file;
        # normalize page arg
        if (isset($subpage[0])) {
            $pagename = $subpage;
            $key = $DBInfo->pageToKeyname($subpage);
            $value = $file;
        } else {
            $pagename = '';
            $key = '';
        }
    } else {
        $pagename = $formatter->page->name;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        $file = $value;
    }
    if (isset($key[0])) {
        $dir = $DBInfo->upload_dir . '/' . $key;
        // support hashed upload_dir
        if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
            $pre = get_hashed_prefix($key);
            $dir = $DBInfo->upload_dir . '/' . $pre . $key;
            if (!is_dir($dir)) {
                $dir = $DBInfo->upload_dir;
            }
        }
    } else {
        $dir = $DBInfo->upload_dir;
    }
    // check file name XXX
    if (!$file) {
        if (!empty($options['link']) and $options['link'] == 1) {
            return 'attachment:' . $value;
        }
        return $bra . 'attachment:/' . $ket;
    }
    $upload_file = $dir . '/' . $file;
    if (!empty($options['link']) and $options['link'] == 1) {
        return $upload_file;
    }
    if (!$text) {
        $text = $file;
    }
    $_l_file = _l_filename($file);
    $_l_upload_file = $dir . '/' . $_l_file;
    if (file_exists($_l_upload_file)) {
        $file_ok = 1;
    } else {
        if (!empty($pull_url)) {
            if (isset($subpage[0])) {
                $pagename = $subpage;
                $val = _urlencode($file);
            } else {
                $val = _urlencode($value);
            }
            $url = $pull_url . _rawurlencode($pagename) . "?action={$mydownload}&value=" . $val;
            $hsz = $formatter->macro_repl('ImageFileSize', $url);
            $info = ' (' . $hsz . ')';
            $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $url);
            // check url to retrieve the size of file
            if (empty($formatter->preview) or floatval($sz) != 0) {
                $file_ok = 2;
            }
        }
    }
    if (empty($file_ok) and !empty($formatter->wikimarkup) and empty($options['nomarkup'])) {
        if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
            $depth = $DBInfo->swfupload_depth;
        } else {
            $depth = 2;
        }
        if (session_id() == '') {
            // ip based
            $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI');
            // FIXME
        } else {
            $myid = session_id();
        }
        $prefix = substr($myid, 0, $depth);
        $mydir = $DBInfo->upload_dir . '/.swfupload/' . $prefix . '/' . $myid;
        if (file_exists($mydir . '/' . $_l_file)) {
            if (!$img_link && preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $upload_file)) {
                $ntext = qualifiedUrl($DBInfo->url_prefix . '/' . $mydir . '/' . $text);
                $img_link = '<img src="' . $ntext . '" alt="' . $text . '" border="0" />';
                return $bra . "<span class=\"attach\">{$img_link}</span>" . $ket;
            } else {
                $sz = filesize($mydir . '/' . $_l_file);
                $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
                for ($i = 0; $i < 4; $i++) {
                    if ($sz <= 1024) {
                        #$sz= round($sz,2).' '.$unit[$i];
                        break;
                    }
                    $sz = $sz / 1024;
                }
                $info = ' (' . round($sz, 2) . ' ' . $unit[$i] . ') ';
                return $bra . "<span class=\"attach\">" . $formatter->icon['attach'] . $text . '</span>' . $info . $ket;
            }
        }
    }
    if (!empty($file_ok)) {
        $imgcls = 'imgAttach';
        if ($imgalign == 'imgCenter' or $caption && empty($imgalign)) {
            if ($file_ok == 1 and !$attrs['width']) {
                $size = getimagesize($_l_upload_file);
                // XXX
                $attrs['width'] = $size[0];
            }
        }
        $img_width = '';
        if (!empty($attrs['width'])) {
            $img_width = ' style="width:' . $attrs['width'] . 'px"';
        }
        if ($caption) {
            $cls = $imgalign ? 'imgContainer ' . $imgalign : 'imgContainer';
            $cap_bra = '<div class="' . $cls . '"' . '>';
            $cap_ket = '</div>';
            $img_width = '';
        } else {
            $imgcls = $imgalign ? 'imgAttach ' . $imgalign : 'imgAttach';
        }
        if ($file_ok == 1) {
            $sz = filesize($_l_upload_file);
            $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB');
            for ($i = 0; $i < 4; $i++) {
                if ($sz <= 1024) {
                    break;
                }
                $sz = $sz / 1024;
            }
            $info = ' (' . round($sz, 2) . ' ' . $unit[$i] . ')';
        }
        if (!in_array('UploadedFiles', $formatter->actions)) {
            $formatter->actions[] = 'UploadedFiles';
        }
        if (empty($img_link) && preg_match("/\\.(png|gif|jpeg|jpg|bmp)\$/i", $upload_file, $m)) {
            // get the extension of the image
            $ext = $m[1];
            $type = strtoupper($m[1]);
            if (!empty($caption)) {
                $caption = '<div class="caption">' . $caption . ' <span>[' . $type . ' ' . _("image") . $info . ']</span></div>';
            } else {
                $caption = '<div class="info"><span>[' . $type . ' ' . _("image") . $info . ']</span></div>';
            }
            if ($file_ok == 1 and !empty($use_thumb)) {
                $thumb_width = !empty($DBInfo->thumb_width) ? $DBInfo->thumb_width : 320;
                if (!empty($thumb['thumbwidth'])) {
                    $thumb_width = $thumb['thumbwidth'];
                }
                // guess thumbnails
                $thumbfiles = array();
                $thumbfiles[] = $_l_file;
                $thumbfiles[] = preg_replace('@' . $ext . '$@i', 'w' . $thumb_width . '.' . $ext, $_l_file);
                $thumb_ok = false;
                foreach ($thumbfiles as $thumbfile) {
                    if (file_exists($dir . '/thumbnails/' . $thumbfile)) {
                        $thumb_ok = true;
                        break;
                    }
                }
                // auto generate thumbnail
                if (!empty($DBInfo->use_convert_thumbs) and !$thumb_ok) {
                    if (!file_exists($dir . "/thumbnails")) {
                        @mkdir($dir . "/thumbnails", 0777);
                    }
                    $fname = $dir . '/' . $_l_file;
                    list($w, $h) = getimagesize($fname);
                    // generate thumbnail using the gd func or the ImageMagick(convert)
                    if ($w > $thumb_width) {
                        require_once 'lib/mediautils.php';
                        resize_image($ext, $fname, $dir . '/thumbnails/' . $thumbfile, $w, $h, $thumb_width);
                        $thumb_ok = true;
                    }
                }
            }
            $alt = !empty($alt) ? $alt : $file;
            if ($key != $pagename || !empty($force_download)) {
                $val = _urlencode($value);
                if ($thumb_ok and !empty($use_thumb)) {
                    if (($p = strrpos($val, '/')) > 0) {
                        $val = substr($val, 0, $p) . '/thumbnails/' . $thumbfile;
                    } else {
                        $val = 'thumbnails/' . $thumbfile;
                    }
                    // use download link ?
                    if (!empty($DBInfo->use_thumb_with_download_link)) {
                        $extra_action = 'download';
                    }
                }
                if ($file_ok == 2 and !empty($pull_url)) {
                    if (isset($subpage[0])) {
                        $pagename = $subpage;
                        $val = _urlencode($file);
                    }
                    $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $pull_url . urlencode(_rawurlencode($pagename)) . "?action={$mydownload}&value=" . $val);
                    if ($use_thumb and isset($thumb['thumb'])) {
                        $url .= '&thumb=' . $thumb['thumb'];
                    }
                } else {
                    $url = $formatter->link_url(_rawurlencode($pagename), "?action={$mydownload}&amp;value=" . $val);
                }
            } else {
                if ($thumb_ok and !empty($use_thumb)) {
                    // FIXME
                    $url = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir . '/thumbnails/' . _urlencode($thumbfile));
                } else {
                    $_my_file = str_replace($DBInfo->upload_dir, $DBInfo->upload_dir_url, $dir . '/' . $file);
                    $url = _urlencode($_my_file);
                }
            }
            if (!empty($options['link_url'])) {
                return qualifiedUrl($url);
            }
            $img = "<img src='{$url}' title='{$alt}' alt='{$alt}' style='border:0' {$attr}/>";
            if ($extra_action) {
                $url = $formatter->link_url(_rawurlencode($pagename), "?action={$extra_action}&amp;value=" . urlencode($value));
                if ($file_ok == 2 and !empty($pull_url)) {
                    if (isset($subpage[0])) {
                        $pagename = $subpage;
                    }
                    $url = $fetch_url . str_replace(array('&', '?'), array('%26', '%3f'), $pull_url . urlencode(_rawurlencode($pagename)) . "?action={$mydownload}&value=" . $val);
                }
                $img = "<a href='{$url}'>{$img}</a>";
            } else {
                if (preg_match('@^(https?|ftp)://@', $alt)) {
                    $img = "<a href='{$alt}'>{$img}</a>";
                }
            }
            return $bra . $cap_bra . "<div class=\"{$imgcls}\"><div>{$img}{$caption}</div></div>" . $cap_ket . $ket;
            #return $bra.$cap_bra."<span class=\"$cls\">$img$caption</span>".$cap_ket.$ket;
        } else {
            $mydownload = $extra_action ? $extra_action : $mydownload;
            $link = $formatter->link_url(_rawurlencode($pagename), "?action={$mydownload}&amp;value=" . urlencode($value), $text);
            if (!empty($options['link_url'])) {
                return qualifiedUrl($link);
            }
            if (!empty($img_link)) {
                return $bra . "<span class=\"attach\"><a href='{$link}'>{$img_link}</a></span>" . $ket;
            }
            return $bra . "<span class=\"attach\">" . $formatter->icon['attach'] . '<a href="' . $link . '">' . $text . '</a></span>' . $info . $ket;
        }
    }
    // no attached file found.
    if (!empty($options['link_url'])) {
        return 'attachment:' . $value;
    }
    if ($formatter->_macrocache and empty($options['call'])) {
        return $formatter->macro_cache_repl('Attachment', $value);
    }
    if (empty($options['call'])) {
        $formatter->_dynamic_macros['@Attachment'] = 1;
    }
    $paste = '';
    if (!empty($DBInfo->use_clipmacro) and preg_match('/^(.*)\\.png$/i', $file, $m)) {
        $now = time();
        $url = $formatter->link_url($pagename, "?action=clip&amp;value={$m['1']}&amp;now={$now}");
        $paste = " <a href='{$url}'>" . _("or paste a new png picture") . "</a>";
    }
    if (!empty($DBInfo->use_drawmacro) and preg_match('/^(.*)\\.gif$/i', $file, $m)) {
        $now = time();
        $url = $formatter->link_url($pagename, "?action=draw&amp;mode=attach&amp;value={$m['1']}&amp;now={$now}");
        $paste = " <a href='{$url}'>" . _("or draw a new gif picture") . "</a>";
    }
    if ($pagename == $formatter->page->name) {
        return $bra . '<span class="attach">' . $formatter->link_to("?action=UploadFile&amp;rename=" . urlencode($file), sprintf(_("Upload new Attachment \"%s\""), $file)) . $paste . '</span>' . $ket;
    }
    if (!$pagename) {
        $pagename = 'UploadFile';
    }
    return $bra . '<span class="attach">' . $formatter->link_tag($pagename, "?action=UploadFile&amp;rename=" . urlencode($file), sprintf(_("Upload new Attachment \"%s\" on the \"%s\""), $file, $pagename)) . $paste . '</span>' . $ket;
}
Exemplo n.º 7
0
function macro_SWFUpload($formatter, $value, $opts = array())
{
    global $DBInfo;
    $swf_ver = 10;
    if (!empty($DBInfo->swfupload_depth) and $DBInfo->swfupload_depth > 2) {
        $depth = $DBInfo->swfupload_depth;
    } else {
        $depth = 2;
    }
    if (session_id() == '') {
        // ip based
        $myid = md5($_SERVER['REMOTE_ADDR'] . '.' . 'MONIWIKI');
        // FIXME
    } else {
        if (!empty($_SESSION['_swfupload'])) {
            $myid = $_SESSION['_swfupload'];
        } else {
            $myid = session_id();
            $_SESSION['_swfupload'] = $myid;
        }
    }
    $prefix = substr($myid, 0, $depth);
    $mysubdir = $prefix . '/' . $myid . '/';
    $myoptions = "<input type='hidden' name='mysubdir' value='{$mysubdir}' />";
    if (!empty($DBInfo->use_lightbox)) {
        $myoptions .= "\n<input type='hidden' name='use_lightbox' value='1' />";
    } else {
        $myoptions .= "\n<input type='hidden' name='use_lightbox' value='0' />";
    }
    $jsPreview = '';
    if (!empty($formatter->preview)) {
        $js_tag = 1;
        $jsPreview = ' class="previewTag"';
        $uploader = 'UploadForm';
    } else {
        if (!empty($options['preview'])) {
            $jsPreview = ' class="previewTag"';
        }
    }
    $default_allowed = '*.gif;*.jpg;*.png;*.psd';
    $allowed = $default_allowed;
    if (!empty($DBInfo->pds_allowed)) {
        $allowed = '*.' . str_replace('|', ';*.', $DBInfo->pds_allowed);
    }
    $swfupload_num = !empty($GLOBALS['swfupload_num']) ? $GLOBALS['swfupload_num'] : 0;
    // get already uploaded files list
    $uploaded = '';
    if (is_dir($DBInfo->upload_dir . '/.swfupload/' . $mysubdir)) {
        $mydir = $DBInfo->upload_dir . '/.swfupload/' . $mysubdir . '/';
        $handle = @opendir($mydir);
        if ($handle) {
            $files = array();
            while ($file = readdir($handle)) {
                if (is_dir($mydir . $file) or $file[0] == '.') {
                    continue;
                }
                $files[] = $file;
            }
            closedir($handle);
            foreach ($files as $f) {
                $uploaded .= "<li id='{$f}'><input checked=\"checked\" type=\"checkbox\">" . "<a href='javascript:showImgPreview(\"{$f}\")'>{$f}</a></li>";
            }
        }
    }
    //
    // check already uploaed files
    //
    if (1) {
        $value = $formatter->page->urlname;
        $key = $DBInfo->pageToKeyname($formatter->page->name);
        $mydir = $DBInfo->upload_dir . "/{$key}";
        // support hashed upload dir
        if (!is_dir($mydir) and !empty($DBInfo->use_hashed_upload_dir)) {
            $prefix = get_hashed_prefix($key);
            $mydir = $DBInfo->upload_dir . '/' . $prefix . $key;
        }
        $handle = @opendir($mydir);
        if ($handle) {
            $files = array();
            while ($file = readdir($handle)) {
                if (is_dir($mydir . $file) or $file[0] == '.') {
                    continue;
                }
                $files[] = $file;
            }
            closedir($handle);
            foreach ($files as $f) {
                $uploaded .= "<li><input checked=\"checked\" disabled=\"disabled\" type=\"checkbox\">" . "<a href='javascript:showImgPreview(\"{$f}\",true)'>{$f}</a></li>";
            }
        }
    }
    if (empty($swfupload_num)) {
        if ($swf_ver == 9) {
            $formatter->register_javascripts(array('js/swfobject.js', 'SWFUpload/mmSWFUpload.js', 'SWFUpload/preview.js', 'SWFUpload/moni.js'));
        } else {
            $formatter->register_javascripts(array('js/swfobject.js', 'SWFUpload/swfupload.js', 'SWFUpload/swfupload.swfobject.js', 'SWFUpload/swfupload.queue.js', 'SWFUpload/preview.js', 'SWFUpload/handlers.js'));
        }
    }
    $swf_css = <<<CSS
<style type="text/css">
@import url("{$DBInfo->url_prefix}/local/SWFUpload/swfupload.css");
</style>
CSS;
    $btn = _("Files...");
    $btn2 = _("Upload files");
    $btn3 = _("Cancel All files");
    $prefix = qualifiedUrl($DBInfo->url_prefix . '/local');
    $action = $formatter->link_url($formatter->page->urlname);
    $action2 = $action . '----swfupload';
    if ($mysubdir) {
        $action2 .= '----' . $mysubdir;
    }
    $action2 = qualifiedUrl($action2);
    $myprefix = qualifiedUrl($DBInfo->url_prefix);
    $swfupload_script = '';
    if ($swf_ver == 9) {
        $swf_js = <<<EOF
        <script type="text/javascript">
        /*<![CDATA[*/
\t\tmmSWFUpload.init({
\t\t\t//debug : true,
\t\t\tupload_backend : "{$action2}",
\t\t\ttarget : "SWFUpload",
\t\t\t// cssClass : "myCustomClass",
\t\t\t_prefix : "{$myprefix}",
\t\t\tallowed_filesize : "40000",
\t\t\tallowed_filetypes : "{$allowed}",
\t\t\tupload_start_callback : 'uploadStart',
\t\t\tupload_progress_callback : 'uploadProgress',
\t\t\tupload_complete_callback : 'uploadComplete',
\t\t\t// upload_error_callback : 'uploadError',
                        upload_cancel_callback : 'uploadCancel'
                });
        /*]]>*/
\t</script>
EOF;
        $submit_btn = "<input type='button' value='{$btn}' onclick='javascript:mmSWFUpload.callSWF();' />\n";
        $cancel_btn = '';
    } else {
        $submit_btn = '<span id="spanButtonPlaceHolder"><input type="file" name="upload" /></span>';
        $cancel_btn = "<button id='btnCancel' onclick='swfu.cancelQueue();' disabled='disabled' ><span>" . $btn3 . "</span></button>\n";
        $swf_js = <<<EOF
<script type="text/javascript">
/*<![CDATA[*/
var swfu;

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

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

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

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

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

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

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

\t</td>
        </tr>
\t<tr>
\t<td colspan='2'>
\t\t<div id="fileProgressInfo"></div>
\t</td>
\t</tr>
\t</table>
\t</div>
EOF;
    return $swfupload_script . $swf_css . $form;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
function macro_UploadForm($formatter, $value)
{
    global $DBInfo;
    static $id = 1;
    $use_fake = 1;
    $hide_btn = 1;
    $name = 'upfile';
    $show = true;
    $msg2 = _("Successfully Uploaded");
    $msg = _("Choose File");
    $formatter->register_javascripts("wikibits.js");
    $script = '';
    if ($id == 1) {
        $script = <<<EOF
<script type="text/javascript">
/*<![CDATA[*/
function addRow(id, name, size) {
    if (size == undefined)
        size = 50;
    if((tmpbutton = document.getElementById(id).getElementsByTagName('button').item(0)) != undefined)
\ttmpbutton = tmpbutton.clientWidth;

    // check editform
    var editform = document.getElementById('editform');
    if (editform) {
        var iframe = document.getElementById('upload-iframe');
        if (!iframe) {
            if (document.all)
                iframe = document.createElement('<iframe frameBorder="0" name="upload-iframe" width="1px" height="1px">');
            else
                iframe = document.createElement('iframe');
            iframe.setAttribute('id','upload-iframe');
            iframe.setAttribute('name','upload-iframe');
            iframe.setAttribute('style','display:none;border:0;');
            if (document.all) {
                // magic for IE6
                /*@cc_on
                if (@_jscript_version==5.6 ||
                    (@_jscript_version==5.7 && navigator.userAgent.toLowerCase().indexOf("msie 6.") != -1)) {
                    iframe.src = 'javascript:document.write("' + "<script>document.domain='" + document.domain + "';</" + "script>" + '");';
                }
                @*/
            }
            var body = document.getElementsByTagName('body')[0];
            body.appendChild(iframe);
        }
    }
    var fform = document.getElementById(id);
    var lastRow = fform.rows.length;
    var row = fform.insertRow(lastRow);

    var cell = row.insertCell(0);
    var div = document.createElement('div');
    div.setAttribute('style', 'position:relative');
    var newInput = document.createElement('input');
    newInput.setAttribute('type', 'file');
    newInput.setAttribute('name', name+'[]');
    newInput.setAttribute('size', size);

    var tmpstyle = "width:80px";
    if(tmpbutton != undefined)
\ttmpstyle = "width:" + tmpbutton + "px;";
    else
\ttmpbutton = 80; // set 80px for IE

    newInput.style.position = 'absolute'; // IE
    newInput.style.left = -8; // IE
    newInput.style.width = tmpbutton+3; // IE
    newInput.setAttribute('style', 'position:absolute;left:-5;'+tmpstyle);

    var btn = document.getElementById('button-' + id);
    if (btn) {
        btn.setAttribute('style','display:none;');
        btn.style.display = 'none';
    }

EOF;
    }
    if ($id == 1 and $hide_btn) {
        $script .= <<<EOF
EOF;
    }
    if ($id == 1 and $use_fake) {
        $script .= <<<EOF
    newInput.className = 'form-file';
    // get basename with replace() for IE
    newInput.onchange = function() {
        // add new row if and only if this input element is in the bottom row of upload table
        this_row = this.parentNode.parentNode.parentNode.parentNode;
        this_table = this_row.parentNode;
        if (this_table.lastChild == this_row) {
                addRow(id, name, size);
        }

        fakeInp.style.display='inline-block';
        fakeInp.value = this.value.replace(/^.*[\\\\]/g, '');

        var btn = document.getElementById('button-' + id);
        if (btn) {
            btn.setAttribute('style','display:inline-block;');
            btn.style.display = 'inline-block';
        }
    };

    var span = document.createElement('span');
    span.style.position='relative';
    var fakeInp = document.createElement('input');
    fakeInp.setAttribute('type', 'text');
    fakeInp.setAttribute('size', size);
    fakeInp.className = 'fake-file';
    fakeInp.setAttribute('readonly', 'true');
    fakeInp.style.display = 'none';
    if (document.all)
        fakeInp.readOnly = true; // for IE
    fakeInp.onclick = function() {if (this.value) { this.value = ''; newInput.value = ''; } else {delRow(id,this);} };

    var addbtn = document.createElement('button');
    var span2 = document.createElement('span');
    var txt = document.createTextNode('{$msg}');
    span2.appendChild(txt);
    addbtn.appendChild(span2);
    addbtn.setAttribute('onclick',"return false;");
    addbtn.className = 'add-file';

    div.appendChild(fakeInp);
    span.appendChild(addbtn);
    span.appendChild(newInput);
    div.appendChild(span);
    cell.appendChild(div);
    /* newInput.click(); /* */
EOF;
    } else {
        if ($id == 1) {
            $script .= <<<EOF
    div.appendChild(newInput);
    cell.appendChild(div);
    /* newInput.click(); /* */
EOF;
        }
    }
    if ($id == 1) {
        $script .= <<<EOF
}

function delRow(id,obj) {
    obj.parentNode.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode.parentNode);

EOF;
    }
    if ($id == 1 and $hide_btn) {
        $script .= <<<EOF
    var form = document.getElementById("form-" + id);
    var inputs = form.getElementsByTagName('input');
    var mysubmit = null;
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'file' && inputs[i].value != '') {
            return;
        }
    }
    var btn = document.getElementById('button-' + id);
    if (btn) btn.style.display = 'none';

EOF;
    }
    if ($id == 1) {
        $script .= <<<EOF
    
}

function check_attach(id) {
    // check if the form has attached files.
    attach = document.getElementById(id);
    var ok = false;
    files = '';
    var tmp = '';
    inputs = attach.getElementsByTagName('input');
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'file' && inputs[i].value != '') {
            ok = true;
            break;
        }
    }
    if (ok == false)
        return false;
    // check editform
    var editform = document.getElementById('editform');
    if (editform) {
        // iframe upload
        iframe = document.getElementById('upload-iframe');
        var attachform = document.getElementById('form-'+id);
        if (attachform) {
            // set domain name.
            if (location.host != document.domain) {
                if (document.all) {
                    var mydomain = document.createElement('<input name="domain">');
                } else {
                    var mydomain = document.createElement('input');
                    mydomain.setAttribute('name', 'domain');
                }

                mydomain.setAttribute('type', 'hidden');
                mydomain.setAttribute('value', document.domain + '');
                attachform.appendChild(mydomain);
            }

            attachform.setAttribute('target', 'upload-iframe');
            attachform.elements['action'].value='UploadFile/ajax';
        }

        var timer = setInterval(function() {check_upload_result(iframe, attach, timer);}, 1500);
        return ok;
    }
    return ok;
}

function check_upload_result (iframe,attach, timer) {
    if (!iframe) return;

    try {
        var doc = iframe.contentDocument || iframe.contentWindow.document;
    } catch(e) {
        // silently ignore
        alert('Error: '+ e + ' - Security restriction detected !\\nPlease check your "document.domain=' + document.domain + '"');
        return;
    }
    if (!doc || !doc.body) return;

    var p = doc.body.firstChild;
    if (p && p.nodeType == 3 && p.nodeValue) { // text node
        eval("var ret = " + p.nodeValue);
        // remove iframe;
        iframe.parentNode.removeChild(iframe);
        alert(ret['title'] + "\\n" + ret['msg']);
        for (var i = 0; i < ret['files'].length; i++) {
            if (ret['files'][i] == '') continue;
            insertTags('attachment:',' ', ret['files'][i], 3);
        }
        clearInterval(timer);
        resetForm(attach);
    }
}

function resetForm(form) {
    inputs = form.getElementsByTagName('input');
    var name = "{$name}", size = 50; // default
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'file') {
            name = inputs[i].getAttribute('name');
            size = inputs[i].getAttribute('size');
            break;
        }
    }

    if (form && form.rows.length) { // for UploadForm
        for (var i=form.rows.length;i>0;i--) {
            form.deleteRow(i-1);
        }
    }
    name = name.replace(/\\[\\]\$/g, '');
    addRow(form.getAttribute('id'), name, size);
}

/*]]>*/
</script>
EOF;
    }
    $msg = _("add files");
    $msg2 = _("add a file");
    $msg3 = _("Upload files");
    $msg4 = _("Reset");
    $attach_msg = _("Attachments");
    $url = $formatter->link_url($formatter->page->urlname);
    $form = <<<EOS
  <form target='_blank' id="form-upload{$id}" method="post" action="{$url}" enctype="multipart/form-data">
  <div class='uploadForm'>
  <input type='hidden' name='action' value='UploadFile' />
EOS;
    $icon = $DBInfo->icon['attach'];
    $multiform = <<<EOF
  <table border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td valign='top' rowspan='2'>
        <span onclick="addRow('upload{$id}','{$name}')" class='icon-clip' title="{$msg}">{$attach_msg}</span>
      </td>
      <td>
        <table cellspacing="0" cellpadding="0" border="0">
          <tbody id="upload{$id}">
          </tbody>
        </table>
      </td>
    </tr>
    <tr>
      <td>
      <div class='buttons'>
  <!-- button type='button' class='add-file' onclick="addRow('upload{$id}','{$name}')"><span>{$msg2}</span></button -->
  <input type="hidden" name="upload{$id}" value="upload{$id}" />
  <input type="hidden" name="popup" value="1" />
EOF;
    if (!empty($show)) {
        $multiform .= <<<EOF
  <button type="submit" class='upload-file' id='button-upload{$id}' onclick="check_attach('upload{$id}')" name="upload"><span>{$msg3}</span></button>
  <!-- <input type="reset" name="reset" value="{$msg4}" /> -->
EOF;
    }
    $multiform .= <<<EOF
      </div>
      </td>
    </tr>
  </table>
  </div>
  </form>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
    var btn = document.getElementById('button-upload{$id}');
    if (btn) btn.style.display = 'none';
})();

function init_uploadForm() {
        addRow('upload{$id}','{$name}');
}

if (window.addEventListener) {
\twindow.addEventListener("load", init_uploadForm, false);
} else if (window.attachEvent) {
\twindow.attachEvent("onload", init_uploadForm);
} else {
\twindow.onload = init_uploadForm;
}

/*]]>*/
</script>
EOF;
    if (!in_array('UploadedFiles', $formatter->actions)) {
        $formatter->actions[] = 'UploadedFiles';
    }
    $id++;
    if (!empty($formatter->preview) and !in_array('UploadFile', $formatter->actions)) {
        if (!empty($DBInfo->use_preview_uploads)) {
            $keyname = $DBInfo->pageToKeyname($formatter->page->name);
            $dir = $DBInfo->upload_dir . '/' . $keyname;
            if (!is_dir($dir) and !empty($DBInfo->use_hashed_upload_dir)) {
                // support hashed upload_dir
                $prefix = get_hashed_prefix($keyname);
                $dir = $DBInfo->upload_dir . '/' . $prefix . $keyname;
            }
            if (is_dir($dir)) {
                $form = $formatter->macro_repl('UploadedFiles(tag=1)') . $form;
            }
        }
    }
    return $script . $form . $multiform;
}
Exemplo n.º 10
0
$idx = 0;
while (($file = readdir($handle)) !== false) {
    if ($file[0] == '.' || in_array($file, array('RCS', 'CVS'))) {
        continue;
    }
    $subdir = $src_dir . '/' . $file;
    if (!is_dir($subdir)) {
        continue;
    }
    $idx++;
    $dirs = get_sub_dir($subdir);
    if (sizeof($dirs)) {
        for ($i = 0; $i < sizeof($dirs); $i++) {
            $key = basename($dirs[$i]);
            $pagename = $from->keyToPagename($key);
            $newname = $to->pageToKeyname($pagename);
            //echo ' * ',$pagename,"\n";
            if (!empty($DBInfo->use_hashed_upload_dir)) {
                $prefix = get_hashed_prefix($newname);
                $newname = $prefix . $newname;
            }
            fwrite($fp, '$CP ' . $dirs[$i] . ' ' . $dest_dir . '/' . $newname . "\n");
        }
    }
}
fclose($fp);
echo "conv.sh generated!\n";
closedir($handle);
$options['timer']->Check("done");
echo $options['timer']->Write();
// vim:et:sts=4:sw=4:
Exemplo n.º 11
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;
}