コード例 #1
0
ファイル: UploadedFiles.php プロジェクト: sedrion/moniwiki
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;
}
コード例 #2
0
ファイル: Attachment.php プロジェクト: reviforks/moniwiki
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;
}
コード例 #3
0
ファイル: download.php プロジェクト: sedrion/moniwiki
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;
}
コード例 #4
0
ファイル: UploadFile.php プロジェクト: NessunKim/MW_Skins
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;
}