xref: /dokuwiki/inc/media.php (revision 15965e387dfad6775563aebc18d38eda4fddf53b)
1<?php
2/**
3 * All output and handler function needed for the media management popup
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10if(!defined('NL')) define('NL',"\n");
11
12/**
13 * Lists pages which currently use a media file selected for deletion
14 *
15 * References uses the same visual as search results and share
16 * their CSS tags except pagenames won't be links.
17 *
18 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
19 */
20function media_filesinuse($data,$id){
21    global $lang;
22    echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
23    echo '<p>'.hsc($lang['ref_inuse']).'</p>';
24
25    $hidden=0; //count of hits without read permission
26    foreach($data as $row){
27        if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
28            echo '<div class="search_result">';
29            echo '<span class="mediaref_ref">'.hsc($row).'</span>';
30            echo '</div>';
31        }else
32            $hidden++;
33    }
34    if ($hidden){
35        print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
36    }
37}
38
39/**
40 * Handles the saving of image meta data
41 *
42 * @author Andreas Gohr <andi@splitbrain.org>
43 */
44function media_metasave($id,$auth,$data){
45    if($auth < AUTH_UPLOAD) return false;
46    if(!checkSecurityToken()) return false;
47    global $lang;
48    global $conf;
49    $src = mediaFN($id);
50
51    $meta = new JpegMeta($src);
52    $meta->_parseAll();
53
54    foreach($data as $key => $val){
55        $val=trim($val);
56        if(empty($val)){
57            $meta->deleteField($key);
58        }else{
59            $meta->setField($key,$val);
60        }
61    }
62
63    if($meta->save()){
64        if($conf['fperm']) chmod($src, $conf['fperm']);
65        msg($lang['metasaveok'],1);
66        return $id;
67    }else{
68        msg($lang['metasaveerr'],-1);
69        return false;
70    }
71}
72
73/**
74 * Display the form to edit image meta data
75 *
76 * @author Andreas Gohr <andi@splitbrain.org>
77 */
78function media_metaform($id,$auth){
79    if($auth < AUTH_UPLOAD) return false;
80    global $lang, $config_cascade;
81
82    // load the field descriptions
83    static $fields = null;
84    if(is_null($fields)){
85
86        foreach (array('default','local') as $config_group) {
87            if (empty($config_cascade['mediameta'][$config_group])) continue;
88            foreach ($config_cascade['mediameta'][$config_group] as $config_file) {
89                if(@file_exists($config_file)){
90                    include($config_file);
91                }
92            }
93        }
94    }
95
96    $src = mediaFN($id);
97
98    // output
99    echo '<h1>'.hsc(noNS($id)).'</h1>'.NL;
100    echo '<form action="'.DOKU_BASE.'lib/exe/mediamanager.php" accept-charset="utf-8" method="post" class="meta">'.NL;
101    formSecurityToken();
102    foreach($fields as $key => $field){
103        // get current value
104        $tags = array($field[0]);
105        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
106        $value = tpl_img_getTag($tags,'',$src);
107        $value = cleanText($value);
108
109        // prepare attributes
110        $p = array();
111        $p['class'] = 'edit';
112        $p['id']    = 'meta__'.$key;
113        $p['name']  = 'meta['.$field[0].']';
114
115        // put label
116        echo '<div class="metafield">';
117        echo '<label for="meta__'.$key.'">';
118        echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1];
119        echo ':</label>';
120
121        // put input field
122        if($field[2] == 'text'){
123            $p['value'] = $value;
124            $p['type']  = 'text';
125            $att = buildAttributes($p);
126            echo "<input $att/>".NL;
127        }else{
128            $att = buildAttributes($p);
129            echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL;
130        }
131        echo '</div>'.NL;
132    }
133    echo '<div class="buttons">'.NL;
134    echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL;
135    echo '<input name="do[save]" type="submit" value="'.$lang['btn_save'].
136        '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL;
137    echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel'].
138        '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL;
139    echo '</div>'.NL;
140    echo '</form>'.NL;
141}
142
143/**
144 * Convenience function to check if a media file is still in use
145 *
146 * @author Michael Klier <chi@chimeric.de>
147 */
148function media_inuse($id) {
149    global $conf;
150    $mediareferences = array();
151    if($conf['refcheck']){
152        $mediareferences = ft_mediause($id,$conf['refshow']);
153        if(!count($mediareferences)) {
154            return false;
155        } else {
156            return $mediareferences;
157        }
158    } else {
159        return false;
160    }
161}
162
163define('DOKU_MEDIA_DELETED', 1);
164define('DOKU_MEDIA_NOT_AUTH', 2);
165define('DOKU_MEDIA_INUSE', 4);
166define('DOKU_MEDIA_EMPTY_NS', 8);
167
168/**
169 * Handles media file deletions
170 *
171 * If configured, checks for media references before deletion
172 *
173 * @author Andreas Gohr <andi@splitbrain.org>
174 * @return int One of: 0,
175                       DOKU_MEDIA_DELETED,
176                       DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
177                       DOKU_MEDIA_NOT_AUTH,
178                       DOKU_MEDIA_INUSE
179 */
180function media_delete($id,$auth){
181    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
182    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
183
184    $file = mediaFN($id);
185
186    // trigger an event - MEDIA_DELETE_FILE
187    $data['id']   = $id;
188    $data['name'] = basename($file);
189    $data['path'] = $file;
190    $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
191
192    $data['unl'] = false;
193    $data['del'] = false;
194    $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
195    if ($evt->advise_before()) {
196        $data['unl'] = @unlink($file);
197        if($data['unl']){
198            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE);
199            $data['del'] = io_sweepNS($id,'mediadir');
200        }
201    }
202    $evt->advise_after();
203    unset($evt);
204
205    if($data['unl'] && $data['del']){
206        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
207    }
208
209    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
210}
211
212/**
213 * Handles media file uploads
214 *
215 * @author Andreas Gohr <andi@splitbrain.org>
216 * @author Michael Klier <chi@chimeric.de>
217 * @return mixed false on error, id of the new file on success
218 */
219function media_upload($ns,$auth){
220    if(!checkSecurityToken()) return false;
221    global $lang;
222
223    // get file and id
224    $id   = $_POST['id'];
225    $file = $_FILES['upload'];
226    if(empty($id)) $id = $file['name'];
227
228    // check for errors (messages are done in lib/exe/mediamanager.php)
229    if($file['error']) return false;
230
231    // check extensions
232    list($fext,$fmime,$dl) = mimetype($file['name']);
233    list($iext,$imime,$dl) = mimetype($id);
234    if($fext && !$iext){
235        // no extension specified in id - read original one
236        $id   .= '.'.$fext;
237        $imime = $fmime;
238    }elseif($fext && $fext != $iext){
239        // extension was changed, print warning
240        msg(sprintf($lang['mediaextchange'],$fext,$iext));
241    }
242
243    $res = media_save(array('name' => $file['tmp_name'],
244                            'mime' => $imime,
245                            'ext'  => $iext), $ns.':'.$id,
246                      $_REQUEST['ow'], $auth, 'move_uploaded_file');
247    if (is_array($res)) {
248        msg($res[0], $res[1]);
249        return false;
250    }
251    return $res;
252}
253
254/**
255 * This generates an action event and delegates to _media_upload_action().
256 * Action plugins are allowed to pre/postprocess the uploaded file.
257 * (The triggered event is preventable.)
258 *
259 * Event data:
260 * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
261 * $data[1]     fn: the file name of the uploaded file
262 * $data[2]     id: the future directory id of the uploaded file
263 * $data[3]     imime: the mimetype of the uploaded file
264 * $data[4]     overwrite: if an existing file is going to be overwritten
265 *
266 * @triggers MEDIA_UPLOAD_FINISH
267 */
268function media_save($file, $id, $ow, $auth, $move) {
269    if($auth < AUTH_UPLOAD) {
270        return array("You don't have permissions to upload files.", -1);
271    }
272
273    if (!isset($file['mime']) || !isset($file['ext'])) {
274        list($ext, $mime) = mimetype($id);
275        if (!isset($file['mime'])) {
276            $file['mime'] = $mime;
277        }
278        if (!isset($file['ext'])) {
279            $file['ext'] = $ext;
280        }
281    }
282
283    global $lang;
284
285    // get filename
286    $id   = cleanID($id,false,true);
287    $fn   = mediaFN($id);
288
289    // get filetype regexp
290    $types = array_keys(getMimeTypes());
291    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
292    $regex = join('|',$types);
293
294    // because a temp file was created already
295    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
296        return array($lang['uploadwrong'],-1);
297    }
298
299    //check for overwrite
300    $overwrite = @file_exists($fn);
301    if($overwrite && (!$ow || $auth < AUTH_DELETE)) {
302        return array($lang['uploadexist'], 0);
303    }
304    // check for valid content
305    $ok = media_contentcheck($file['name'], $file['mime']);
306    if($ok == -1){
307        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
308    }elseif($ok == -2){
309        return array($lang['uploadspam'],-1);
310    }elseif($ok == -3){
311        return array($lang['uploadxss'],-1);
312    }
313
314    // prepare event data
315    $data[0] = $file['name'];
316    $data[1] = $fn;
317    $data[2] = $id;
318    $data[3] = $file['mime'];
319    $data[4] = $overwrite;
320    $data[5] = $move;
321
322    // trigger event
323    return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
324}
325
326/**
327 * Callback adapter for media_upload_finish()
328 * @author Michael Klier <chi@chimeric.de>
329 */
330function _media_upload_action($data) {
331    // fixme do further sanity tests of given data?
332    if(is_array($data) && count($data)===6) {
333        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
334    } else {
335        return false; //callback error
336    }
337}
338
339/**
340 * Saves an uploaded media file
341 *
342 * @author Andreas Gohr <andi@splitbrain.org>
343 * @author Michael Klier <chi@chimeric.de>
344 */
345function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
346    global $conf;
347    global $lang;
348
349    // prepare directory
350    io_createNamespace($id, 'media');
351
352    if($move($fn_tmp, $fn)) {
353        // Set the correct permission here.
354        // Always chmod media because they may be saved with different permissions than expected from the php umask.
355        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
356        chmod($fn, $conf['fmode']);
357        msg($lang['uploadsucc'],1);
358        media_notify($id,$fn,$imime);
359        // add a log entry to the media changelog
360        if ($overwrite) {
361            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_EDIT);
362        } else {
363            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_CREATE);
364        }
365        return $id;
366    }else{
367        return array($lang['uploadfail'],-1);
368    }
369}
370
371/**
372 * This function checks if the uploaded content is really what the
373 * mimetype says it is. We also do spam checking for text types here.
374 *
375 * We need to do this stuff because we can not rely on the browser
376 * to do this check correctly. Yes, IE is broken as usual.
377 *
378 * @author Andreas Gohr <andi@splitbrain.org>
379 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
380 * @fixme  check all 26 magic IE filetypes here?
381 */
382function media_contentcheck($file,$mime){
383    global $conf;
384    if($conf['iexssprotect']){
385        $fh = @fopen($file, 'rb');
386        if($fh){
387            $bytes = fread($fh, 256);
388            fclose($fh);
389            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
390                return -3;
391            }
392        }
393    }
394    if(substr($mime,0,6) == 'image/'){
395        $info = @getimagesize($file);
396        if($mime == 'image/gif' && $info[2] != 1){
397            return -1;
398        }elseif($mime == 'image/jpeg' && $info[2] != 2){
399            return -1;
400        }elseif($mime == 'image/png' && $info[2] != 3){
401            return -1;
402        }
403        # fixme maybe check other images types as well
404    }elseif(substr($mime,0,5) == 'text/'){
405        global $TEXT;
406        $TEXT = io_readFile($file);
407        if(checkwordblock()){
408            return -2;
409        }
410    }
411    return 0;
412}
413
414/**
415 * Send a notify mail on uploads
416 *
417 * @author Andreas Gohr <andi@splitbrain.org>
418 */
419function media_notify($id,$file,$mime){
420    global $lang;
421    global $conf;
422    global $INFO;
423    if(empty($conf['notify'])) return; //notify enabled?
424
425    $ip = clientIP();
426
427    $text = rawLocale('uploadmail');
428    $text = str_replace('@DATE@',dformat(),$text);
429    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
430    $text = str_replace('@IPADDRESS@',$ip,$text);
431    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
432    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
433    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
434    $text = str_replace('@MIME@',$mime,$text);
435    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
436    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
437
438    $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
439
440    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
441}
442
443/**
444 * List all files in a given Media namespace
445 */
446function media_filelist($ns,$auth=null,$jump=''){
447    global $conf;
448    global $lang;
449    $ns = cleanID($ns);
450
451    // check auth our self if not given (needed for ajax calls)
452    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
453
454    echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
455
456    if($auth < AUTH_READ){
457        // FIXME: print permission warning here instead?
458        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
459    }else{
460        media_uploadform($ns, $auth);
461
462        $dir = utf8_encodeFN(str_replace(':','/',$ns));
463        $data = array();
464        search($data,$conf['mediadir'],'search_media',
465                array('showmsg'=>true,'depth'=>1),$dir);
466
467        if(!count($data)){
468            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
469        }else foreach($data as $item){
470            media_printfile($item,$auth,$jump);
471        }
472    }
473    media_searchform($ns);
474}
475
476/**
477 * List all files found by the search request
478 *
479 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
480 * @author Andreas Gohr <gohr@cosmocode.de>
481 * @triggers MEDIA_SEARCH
482 */
483function media_searchlist($query,$ns,$auth=null){
484    global $conf;
485    global $lang;
486    $ns = cleanID($ns);
487
488    if ($query) {
489        $evdata = array(
490                'ns'    => $ns,
491                'data'  => array(),
492                'query' => $query
493                );
494        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
495        if ($evt->advise_before()) {
496            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
497            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
498            search($evdata['data'],
499                    $conf['mediadir'],
500                    'search_media',
501                    array('showmsg'=>false,'pattern'=>$pattern),
502                    $dir);
503        }
504        $evt->advise_after();
505        unset($evt);
506    }
507
508    echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
509    media_searchform($ns,$query);
510
511    if(!count($evdata['data'])){
512        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
513    }else foreach($evdata['data'] as $item){
514        media_printfile($item,$item['perm'],'',true);
515    }
516}
517
518/**
519 * Print action links for a file depending on filetype
520 * and available permissions
521 */
522function media_fileactions($item,$auth){
523    global $lang;
524
525    // view button
526    $link = ml($item['id'],'',true);
527    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
528        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
529
530    // no further actions if not writable
531    if(!$item['writable']) return;
532
533    // delete button
534    if($auth >= AUTH_DELETE){
535        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
536            '&amp;sectok='.getSecurityToken().'" class="btn_media_delete" title="'.$item['id'].'">'.
537            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
538            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
539    }
540
541    // edit button
542    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
543        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']).'">'.
544            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
545            'title="'.$lang['metaedit'].'" class="btn" /></a>';
546    }
547
548}
549
550/**
551 * Formats and prints one file in the list
552 */
553function media_printfile($item,$auth,$jump,$display_namespace=false){
554    global $lang;
555    global $conf;
556
557    // Prepare zebra coloring
558    // I always wanted to use this variable name :-D
559    static $twibble = 1;
560    $twibble *= -1;
561    $zebra = ($twibble == -1) ? 'odd' : 'even';
562
563    // Automatically jump to recent action
564    if($jump == $item['id']) {
565        $jump = ' id="scroll__here" ';
566    }else{
567        $jump = '';
568    }
569
570    // Prepare fileicons
571    list($ext,$mime,$dl) = mimetype($item['file'],false);
572    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
573    $class = 'select mediafile mf_'.$class;
574
575    // Prepare filename
576    $file = utf8_decodeFN($item['file']);
577
578    // Prepare info
579    $info = '';
580    if($item['isimg']){
581        $info .= (int) $item['meta']->getField('File.Width');
582        $info .= '&#215;';
583        $info .= (int) $item['meta']->getField('File.Height');
584        $info .= ' ';
585    }
586    $info .= '<i>'.dformat($item['mtime']).'</i>';
587    $info .= ' ';
588    $info .= filesize_h($item['size']);
589
590    // output
591    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
592    if (!$display_namespace) {
593        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
594    } else {
595        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
596    }
597    echo '<span class="info">('.$info.')</span>'.NL;
598    media_fileactions($item,$auth);
599    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
600    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
601    echo '</div>';
602    if($item['isimg']) media_printimgdetail($item);
603    echo '<div class="clearer"></div>'.NL;
604    echo '</div>'.NL;
605}
606
607/**
608 * Prints a thumbnail and metainfos
609 */
610function media_printimgdetail($item){
611    // prepare thumbnail
612    $w = (int) $item['meta']->getField('File.Width');
613    $h = (int) $item['meta']->getField('File.Height');
614    if($w>120 || $h>120){
615        $ratio = $item['meta']->getResizeRatio(120);
616        $w = floor($w * $ratio);
617        $h = floor($h * $ratio);
618    }
619    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
620    $p = array();
621    $p['width']  = $w;
622    $p['height'] = $h;
623    $p['alt']    = $item['id'];
624    $p['class']  = 'thumb';
625    $att = buildAttributes($p);
626
627    // output
628    echo '<div class="detail">';
629    echo '<div class="thumb">';
630    echo '<a name="d_:'.$item['id'].'" class="select">';
631    echo '<img src="'.$src.'" '.$att.' />';
632    echo '</a>';
633    echo '</div>';
634
635    // read EXIF/IPTC data
636    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
637    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
638                'EXIF.TIFFImageDescription',
639                'EXIF.TIFFUserComment'));
640    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
641    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
642
643    // print EXIF/IPTC data
644    if($t || $d || $k ){
645        echo '<p>';
646        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
647        if($d) echo htmlspecialchars($d).'<br />';
648        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
649        echo '</p>';
650    }
651    echo '</div>';
652}
653
654/**
655 * Print the media upload form if permissions are correct
656 *
657 * @author Andreas Gohr <andi@splitbrain.org>
658 */
659function media_uploadform($ns, $auth){
660    global $lang;
661
662    if($auth < AUTH_UPLOAD) return; //fixme print info on missing permissions?
663
664    // The default HTML upload form
665    $form = new Doku_Form(array('id'      => 'dw__upload',
666                                'action'  => DOKU_BASE.'lib/exe/mediamanager.php',
667                                'enctype' => 'multipart/form-data'));
668    $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
669    $form->addElement(formSecurityToken());
670    $form->addHidden('ns', hsc($ns));
671    $form->addElement(form_makeOpenTag('p'));
672    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
673    $form->addElement(form_makeCloseTag('p'));
674    $form->addElement(form_makeOpenTag('p'));
675    $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name'));
676    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
677    $form->addElement(form_makeCloseTag('p'));
678
679    if($auth >= AUTH_DELETE){
680        $form->addElement(form_makeOpenTag('p'));
681        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check'));
682        $form->addElement(form_makeCloseTag('p'));
683    }
684    html_form('upload', $form);
685
686    // prepare flashvars for multiupload
687    $opt = array(
688            'L_gridname'  => $lang['mu_gridname'] ,
689            'L_gridsize'  => $lang['mu_gridsize'] ,
690            'L_gridstat'  => $lang['mu_gridstat'] ,
691            'L_namespace' => $lang['mu_namespace'] ,
692            'L_overwrite' => $lang['txt_overwrt'],
693            'L_browse'    => $lang['mu_browse'],
694            'L_upload'    => $lang['btn_upload'],
695            'L_toobig'    => $lang['mu_toobig'],
696            'L_ready'     => $lang['mu_ready'],
697            'L_done'      => $lang['mu_done'],
698            'L_fail'      => $lang['mu_fail'],
699            'L_authfail'  => $lang['mu_authfail'],
700            'L_progress'  => $lang['mu_progress'],
701            'L_filetypes' => $lang['mu_filetypes'],
702            'L_info'      => $lang['mu_info'],
703            'L_lasterr'   => $lang['mu_lasterr'],
704
705            'O_ns'        => ":$ns",
706            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
707            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
708            'O_extensions'=> join('|',array_keys(getMimeTypes())),
709            'O_overwrite' => ($auth >= AUTH_DELETE),
710            'O_sectok'    => getSecurityToken(),
711            'O_authtok'   => auth_createToken(),
712            );
713    $var = buildURLparams($opt);
714    // output the flash uploader
715    ?>
716        <div id="dw__flashupload" style="display:none">
717        <div class="upload"><?php echo $lang['mu_intro']?></div>
718        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
719        </div>
720        <?php
721}
722
723/**
724 * Print the search field form
725 *
726 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
727 */
728function media_searchform($ns,$query=''){
729    global $lang;
730
731    // The default HTML search form
732    $form = new Doku_Form(array('id' => 'dw__mediasearch', 'action' => DOKU_BASE.'lib/exe/mediamanager.php'));
733    $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
734    $form->addElement(formSecurityToken());
735    $form->addHidden('ns', $ns);
736    $form->addHidden('do', 'searchlist');
737    $form->addElement(form_makeOpenTag('p'));
738    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
739    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
740    $form->addElement(form_makeCloseTag('p'));
741    html_form('searchmedia', $form);
742}
743
744/**
745 * Build a tree outline of available media namespaces
746 *
747 * @author Andreas Gohr <andi@splitbrain.org>
748 */
749function media_nstree($ns){
750    global $conf;
751    global $lang;
752
753    // currently selected namespace
754    $ns  = cleanID($ns);
755    if(empty($ns)){
756        global $ID;
757        $ns = dirname(str_replace(':','/',$ID));
758        if($ns == '.') $ns ='';
759    }
760    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
761
762    $data = array();
763    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
764
765    // wrap a list with the root level around the other namespaces
766    $item = array( 'level' => 0, 'id' => '',
767            'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
768
769    echo '<ul class="idx">';
770    echo media_nstree_li($item);
771    echo media_nstree_item($item);
772    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
773    echo '</li>';
774    echo '</ul>';
775}
776
777/**
778 * Userfunction for html_buildlist
779 *
780 * Prints a media namespace tree item
781 *
782 * @author Andreas Gohr <andi@splitbrain.org>
783 */
784function media_nstree_item($item){
785    $pos   = strrpos($item['id'], ':');
786    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
787    if(!$item['label']) $item['label'] = $label;
788
789    $ret  = '';
790    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
791    $ret .= $item['label'];
792    $ret .= '</a>';
793    return $ret;
794}
795
796/**
797 * Userfunction for html_buildlist
798 *
799 * Prints a media namespace tree item opener
800 *
801 * @author Andreas Gohr <andi@splitbrain.org>
802 */
803function media_nstree_li($item){
804    $class='media level'.$item['level'];
805    if($item['open']){
806        $class .= ' open';
807        $img   = DOKU_BASE.'lib/images/minus.gif';
808        $alt   = '&minus;';
809    }else{
810        $class .= ' closed';
811        $img   = DOKU_BASE.'lib/images/plus.gif';
812        $alt   = '+';
813    }
814    return '<li class="'.$class.'">'.
815        '<img src="'.$img.'" alt="'.$alt.'" />';
816}
817
818/**
819 * Resizes the given image to the given size
820 *
821 * @author  Andreas Gohr <andi@splitbrain.org>
822 */
823function media_resize_image($file, $ext, $w, $h=0){
824    global $conf;
825
826    $info = @getimagesize($file); //get original size
827    if($info == false) return $file; // that's no image - it's a spaceship!
828
829    if(!$h) $h = round(($w * $info[1]) / $info[0]);
830
831    // we wont scale up to infinity
832    if($w > 2000 || $h > 2000) return $file;
833
834    //cache
835    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
836    $mtime = @filemtime($local); // 0 if not exists
837
838    if( $mtime > filemtime($file) ||
839            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
840            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
841        if($conf['fperm']) chmod($local, $conf['fperm']);
842        return $local;
843    }
844    //still here? resizing failed
845    return $file;
846}
847
848/**
849 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
850 * to the wanted size
851 *
852 * Crops are centered horizontally but prefer the upper third of an vertical
853 * image because most pics are more interesting in that area (rule of thirds)
854 *
855 * @author  Andreas Gohr <andi@splitbrain.org>
856 */
857function media_crop_image($file, $ext, $w, $h=0){
858    global $conf;
859
860    if(!$h) $h = $w;
861    $info = @getimagesize($file); //get original size
862    if($info == false) return $file; // that's no image - it's a spaceship!
863
864    // calculate crop size
865    $fr = $info[0]/$info[1];
866    $tr = $w/$h;
867    if($tr >= 1){
868        if($tr > $fr){
869            $cw = $info[0];
870            $ch = (int) $info[0]/$tr;
871        }else{
872            $cw = (int) $info[1]*$tr;
873            $ch = $info[1];
874        }
875    }else{
876        if($tr < $fr){
877            $cw = (int) $info[1]*$tr;
878            $ch = $info[1];
879        }else{
880            $cw = $info[0];
881            $ch = (int) $info[0]/$tr;
882        }
883    }
884    // calculate crop offset
885    $cx = (int) ($info[0]-$cw)/2;
886    $cy = (int) ($info[1]-$ch)/3;
887
888    //cache
889    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
890    $mtime = @filemtime($local); // 0 if not exists
891
892    if( $mtime > filemtime($file) ||
893            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
894            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
895        if($conf['fperm']) chmod($local, $conf['fperm']);
896        return media_resize_image($local,$ext, $w, $h);
897    }
898
899    //still here? cropping failed
900    return media_resize_image($file,$ext, $w, $h);
901}
902
903/**
904 * Download a remote file and return local filename
905 *
906 * returns false if download fails. Uses cached file if available and
907 * wanted
908 *
909 * @author  Andreas Gohr <andi@splitbrain.org>
910 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
911 */
912function media_get_from_URL($url,$ext,$cache){
913    global $conf;
914
915    // if no cache or fetchsize just redirect
916    if ($cache==0)           return false;
917    if (!$conf['fetchsize']) return false;
918
919    $local = getCacheName(strtolower($url),".media.$ext");
920    $mtime = @filemtime($local); // 0 if not exists
921
922    //decide if download needed:
923    if( ($mtime == 0) ||                           // cache does not exist
924            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
925      ){
926        if(media_image_download($url,$local)){
927            return $local;
928        }else{
929            return false;
930        }
931    }
932
933    //if cache exists use it else
934    if($mtime) return $local;
935
936    //else return false
937    return false;
938}
939
940/**
941 * Download image files
942 *
943 * @author Andreas Gohr <andi@splitbrain.org>
944 */
945function media_image_download($url,$file){
946    global $conf;
947    $http = new DokuHTTPClient();
948    $http->max_bodysize = $conf['fetchsize'];
949    $http->timeout = 25; //max. 25 sec
950    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
951
952    $data = $http->get($url);
953    if(!$data) return false;
954
955    $fileexists = @file_exists($file);
956    $fp = @fopen($file,"w");
957    if(!$fp) return false;
958    fwrite($fp,$data);
959    fclose($fp);
960    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
961
962    // check if it is really an image
963    $info = @getimagesize($file);
964    if(!$info){
965        @unlink($file);
966        return false;
967    }
968
969    return true;
970}
971
972/**
973 * resize images using external ImageMagick convert program
974 *
975 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
976 * @author Andreas Gohr <andi@splitbrain.org>
977 */
978function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
979    global $conf;
980
981    // check if convert is configured
982    if(!$conf['im_convert']) return false;
983
984    // prepare command
985    $cmd  = $conf['im_convert'];
986    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
987    if ($ext == 'jpg' || $ext == 'jpeg') {
988        $cmd .= ' -quality '.$conf['jpg_quality'];
989    }
990    $cmd .= " $from $to";
991
992    @exec($cmd,$out,$retval);
993    if ($retval == 0) return true;
994    return false;
995}
996
997/**
998 * crop images using external ImageMagick convert program
999 *
1000 * @author Andreas Gohr <andi@splitbrain.org>
1001 */
1002function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1003    global $conf;
1004
1005    // check if convert is configured
1006    if(!$conf['im_convert']) return false;
1007
1008    // prepare command
1009    $cmd  = $conf['im_convert'];
1010    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1011    if ($ext == 'jpg' || $ext == 'jpeg') {
1012        $cmd .= ' -quality '.$conf['jpg_quality'];
1013    }
1014    $cmd .= " $from $to";
1015
1016    @exec($cmd,$out,$retval);
1017    if ($retval == 0) return true;
1018    return false;
1019}
1020
1021/**
1022 * resize or crop images using PHP's libGD support
1023 *
1024 * @author Andreas Gohr <andi@splitbrain.org>
1025 * @author Sebastian Wienecke <s_wienecke@web.de>
1026 */
1027function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1028    global $conf;
1029
1030    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1031
1032    // check available memory
1033    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1034        return false;
1035    }
1036
1037    // create an image of the given filetype
1038    if ($ext == 'jpg' || $ext == 'jpeg'){
1039        if(!function_exists("imagecreatefromjpeg")) return false;
1040        $image = @imagecreatefromjpeg($from);
1041    }elseif($ext == 'png') {
1042        if(!function_exists("imagecreatefrompng")) return false;
1043        $image = @imagecreatefrompng($from);
1044
1045    }elseif($ext == 'gif') {
1046        if(!function_exists("imagecreatefromgif")) return false;
1047        $image = @imagecreatefromgif($from);
1048    }
1049    if(!$image) return false;
1050
1051    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1052        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1053    }
1054    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1055    if(!$newimg){
1056        imagedestroy($image);
1057        return false;
1058    }
1059
1060    //keep png alpha channel if possible
1061    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1062        imagealphablending($newimg, false);
1063        imagesavealpha($newimg,true);
1064    }
1065
1066    //keep gif transparent color if possible
1067    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1068        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1069            $transcolorindex = @imagecolortransparent($image);
1070            if($transcolorindex >= 0 ) { //transparent color exists
1071                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1072                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1073                @imagefill($newimg, 0, 0, $transcolorindex);
1074                @imagecolortransparent($newimg, $transcolorindex);
1075            }else{ //filling with white
1076                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1077                @imagefill($newimg, 0, 0, $whitecolorindex);
1078            }
1079        }else{ //filling with white
1080            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1081            @imagefill($newimg, 0, 0, $whitecolorindex);
1082        }
1083    }
1084
1085    //try resampling first
1086    if(function_exists("imagecopyresampled")){
1087        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1088            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1089        }
1090    }else{
1091        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1092    }
1093
1094    $okay = false;
1095    if ($ext == 'jpg' || $ext == 'jpeg'){
1096        if(!function_exists('imagejpeg')){
1097            $okay = false;
1098        }else{
1099            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1100        }
1101    }elseif($ext == 'png') {
1102        if(!function_exists('imagepng')){
1103            $okay = false;
1104        }else{
1105            $okay =  imagepng($newimg, $to);
1106        }
1107    }elseif($ext == 'gif') {
1108        if(!function_exists('imagegif')){
1109            $okay = false;
1110        }else{
1111            $okay = imagegif($newimg, $to);
1112        }
1113    }
1114
1115    // destroy GD image ressources
1116    if($image) imagedestroy($image);
1117    if($newimg) imagedestroy($newimg);
1118
1119    return $okay;
1120}
1121
1122/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1123