xref: /dokuwiki/inc/media.php (revision 8d56551e75f273694893a29a06d8164d3d60ae17)
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    $old = @filemtime($fn);
350    //
351    if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn)) {
352        // add old revision to the attic if missing
353        saveOldMediaRevision($id);
354    }
355
356    // prepare directory
357    io_createNamespace($id, 'media');
358
359    if($move($fn_tmp, $fn)) {
360        // Set the correct permission here.
361        // Always chmod media because they may be saved with different permissions than expected from the php umask.
362        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
363        chmod($fn, $conf['fmode']);
364        msg($lang['uploadsucc'],1);
365        media_notify($id,$fn,$imime);
366        // add a log entry to the media changelog
367        if ($overwrite) {
368            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_EDIT);
369        } else {
370            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_CREATE);
371        }
372        return $id;
373    }else{
374        return array($lang['uploadfail'],-1);
375    }
376}
377
378/**
379 * moves the current version to the media_attic and returns its
380 * revision date
381 */
382function saveOldMediaRevision($id, $move = 'copy'){
383    global $conf;
384    $oldf = mediaFN($id);
385    if(!@file_exists($oldf)) return '';
386    $date = filemtime($oldf);
387    $newf = mediaFN($id,$date);
388    io_makeFileDir($newf);
389    if($move($oldf, $newf)) {
390        // Set the correct permission here.
391        // Always chmod media because they may be saved with different permissions than expected from the php umask.
392        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
393        chmod($newf, $conf['fmode']);
394    }
395    return $date;
396}
397
398/**
399 * This function checks if the uploaded content is really what the
400 * mimetype says it is. We also do spam checking for text types here.
401 *
402 * We need to do this stuff because we can not rely on the browser
403 * to do this check correctly. Yes, IE is broken as usual.
404 *
405 * @author Andreas Gohr <andi@splitbrain.org>
406 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
407 * @fixme  check all 26 magic IE filetypes here?
408 */
409function media_contentcheck($file,$mime){
410    global $conf;
411    if($conf['iexssprotect']){
412        $fh = @fopen($file, 'rb');
413        if($fh){
414            $bytes = fread($fh, 256);
415            fclose($fh);
416            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
417                return -3;
418            }
419        }
420    }
421    if(substr($mime,0,6) == 'image/'){
422        $info = @getimagesize($file);
423        if($mime == 'image/gif' && $info[2] != 1){
424            return -1;
425        }elseif($mime == 'image/jpeg' && $info[2] != 2){
426            return -1;
427        }elseif($mime == 'image/png' && $info[2] != 3){
428            return -1;
429        }
430        # fixme maybe check other images types as well
431    }elseif(substr($mime,0,5) == 'text/'){
432        global $TEXT;
433        $TEXT = io_readFile($file);
434        if(checkwordblock()){
435            return -2;
436        }
437    }
438    return 0;
439}
440
441/**
442 * Send a notify mail on uploads
443 *
444 * @author Andreas Gohr <andi@splitbrain.org>
445 */
446function media_notify($id,$file,$mime){
447    global $lang;
448    global $conf;
449    global $INFO;
450    if(empty($conf['notify'])) return; //notify enabled?
451
452    $ip = clientIP();
453
454    $text = rawLocale('uploadmail');
455    $text = str_replace('@DATE@',dformat(),$text);
456    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
457    $text = str_replace('@IPADDRESS@',$ip,$text);
458    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
459    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
460    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
461    $text = str_replace('@MIME@',$mime,$text);
462    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
463    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
464
465    $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
466
467    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
468}
469
470/**
471 * List all files in a given Media namespace
472 */
473function media_filelist($ns,$auth=null,$jump=''){
474    global $conf;
475    global $lang;
476    $ns = cleanID($ns);
477
478    // check auth our self if not given (needed for ajax calls)
479    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
480
481    echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
482
483    if($auth < AUTH_READ){
484        // FIXME: print permission warning here instead?
485        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
486    }else{
487        media_uploadform($ns, $auth);
488
489        $dir = utf8_encodeFN(str_replace(':','/',$ns));
490        $data = array();
491        search($data,$conf['mediadir'],'search_media',
492                array('showmsg'=>true,'depth'=>1),$dir);
493
494        if(!count($data)){
495            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
496        }else foreach($data as $item){
497            media_printfile($item,$auth,$jump);
498        }
499    }
500    media_searchform($ns);
501}
502
503/**
504 * List all files found by the search request
505 *
506 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
507 * @author Andreas Gohr <gohr@cosmocode.de>
508 * @triggers MEDIA_SEARCH
509 */
510function media_searchlist($query,$ns,$auth=null){
511    global $conf;
512    global $lang;
513    $ns = cleanID($ns);
514
515    if ($query) {
516        $evdata = array(
517                'ns'    => $ns,
518                'data'  => array(),
519                'query' => $query
520                );
521        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
522        if ($evt->advise_before()) {
523            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
524            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
525            search($evdata['data'],
526                    $conf['mediadir'],
527                    'search_media',
528                    array('showmsg'=>false,'pattern'=>$pattern),
529                    $dir);
530        }
531        $evt->advise_after();
532        unset($evt);
533    }
534
535    echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
536    media_searchform($ns,$query);
537
538    if(!count($evdata['data'])){
539        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
540    }else foreach($evdata['data'] as $item){
541        media_printfile($item,$item['perm'],'',true);
542    }
543}
544
545/**
546 * Print action links for a file depending on filetype
547 * and available permissions
548 */
549function media_fileactions($item,$auth){
550    global $lang;
551
552    // view button
553    $link = ml($item['id'],'',true);
554    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
555        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
556
557    // no further actions if not writable
558    if(!$item['writable']) return;
559
560    // delete button
561    if($auth >= AUTH_DELETE){
562        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
563            '&amp;sectok='.getSecurityToken().'" class="btn_media_delete" title="'.$item['id'].'">'.
564            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
565            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
566    }
567
568    // edit button
569    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
570        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']).'">'.
571            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
572            'title="'.$lang['metaedit'].'" class="btn" /></a>';
573    }
574
575}
576
577/**
578 * Formats and prints one file in the list
579 */
580function media_printfile($item,$auth,$jump,$display_namespace=false){
581    global $lang;
582    global $conf;
583
584    // Prepare zebra coloring
585    // I always wanted to use this variable name :-D
586    static $twibble = 1;
587    $twibble *= -1;
588    $zebra = ($twibble == -1) ? 'odd' : 'even';
589
590    // Automatically jump to recent action
591    if($jump == $item['id']) {
592        $jump = ' id="scroll__here" ';
593    }else{
594        $jump = '';
595    }
596
597    // Prepare fileicons
598    list($ext,$mime,$dl) = mimetype($item['file'],false);
599    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
600    $class = 'select mediafile mf_'.$class;
601
602    // Prepare filename
603    $file = utf8_decodeFN($item['file']);
604
605    // Prepare info
606    $info = '';
607    if($item['isimg']){
608        $info .= (int) $item['meta']->getField('File.Width');
609        $info .= '&#215;';
610        $info .= (int) $item['meta']->getField('File.Height');
611        $info .= ' ';
612    }
613    $info .= '<i>'.dformat($item['mtime']).'</i>';
614    $info .= ' ';
615    $info .= filesize_h($item['size']);
616
617    // output
618    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
619    if (!$display_namespace) {
620        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
621    } else {
622        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
623    }
624    echo '<span class="info">('.$info.')</span>'.NL;
625    media_fileactions($item,$auth);
626    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
627    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
628    echo '</div>';
629    if($item['isimg']) media_printimgdetail($item);
630    echo '<div class="clearer"></div>'.NL;
631    echo '</div>'.NL;
632}
633
634/**
635 * Prints a thumbnail and metainfos
636 */
637function media_printimgdetail($item){
638    // prepare thumbnail
639    $w = (int) $item['meta']->getField('File.Width');
640    $h = (int) $item['meta']->getField('File.Height');
641    if($w>120 || $h>120){
642        $ratio = $item['meta']->getResizeRatio(120);
643        $w = floor($w * $ratio);
644        $h = floor($h * $ratio);
645    }
646    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
647    $p = array();
648    $p['width']  = $w;
649    $p['height'] = $h;
650    $p['alt']    = $item['id'];
651    $p['class']  = 'thumb';
652    $att = buildAttributes($p);
653
654    // output
655    echo '<div class="detail">';
656    echo '<div class="thumb">';
657    echo '<a name="d_:'.$item['id'].'" class="select">';
658    echo '<img src="'.$src.'" '.$att.' />';
659    echo '</a>';
660    echo '</div>';
661
662    // read EXIF/IPTC data
663    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
664    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
665                'EXIF.TIFFImageDescription',
666                'EXIF.TIFFUserComment'));
667    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
668    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
669
670    // print EXIF/IPTC data
671    if($t || $d || $k ){
672        echo '<p>';
673        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
674        if($d) echo htmlspecialchars($d).'<br />';
675        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
676        echo '</p>';
677    }
678    echo '</div>';
679}
680
681/**
682 * Print the media upload form if permissions are correct
683 *
684 * @author Andreas Gohr <andi@splitbrain.org>
685 */
686function media_uploadform($ns, $auth){
687    global $lang;
688
689    if($auth < AUTH_UPLOAD) return; //fixme print info on missing permissions?
690
691    // The default HTML upload form
692    $form = new Doku_Form(array('id'      => 'dw__upload',
693                                'action'  => DOKU_BASE.'lib/exe/mediamanager.php',
694                                'enctype' => 'multipart/form-data'));
695    $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
696    $form->addElement(formSecurityToken());
697    $form->addHidden('ns', hsc($ns));
698    $form->addElement(form_makeOpenTag('p'));
699    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
700    $form->addElement(form_makeCloseTag('p'));
701    $form->addElement(form_makeOpenTag('p'));
702    $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name'));
703    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
704    $form->addElement(form_makeCloseTag('p'));
705
706    if($auth >= AUTH_DELETE){
707        $form->addElement(form_makeOpenTag('p'));
708        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check'));
709        $form->addElement(form_makeCloseTag('p'));
710    }
711    html_form('upload', $form);
712
713    // prepare flashvars for multiupload
714    $opt = array(
715            'L_gridname'  => $lang['mu_gridname'] ,
716            'L_gridsize'  => $lang['mu_gridsize'] ,
717            'L_gridstat'  => $lang['mu_gridstat'] ,
718            'L_namespace' => $lang['mu_namespace'] ,
719            'L_overwrite' => $lang['txt_overwrt'],
720            'L_browse'    => $lang['mu_browse'],
721            'L_upload'    => $lang['btn_upload'],
722            'L_toobig'    => $lang['mu_toobig'],
723            'L_ready'     => $lang['mu_ready'],
724            'L_done'      => $lang['mu_done'],
725            'L_fail'      => $lang['mu_fail'],
726            'L_authfail'  => $lang['mu_authfail'],
727            'L_progress'  => $lang['mu_progress'],
728            'L_filetypes' => $lang['mu_filetypes'],
729            'L_info'      => $lang['mu_info'],
730            'L_lasterr'   => $lang['mu_lasterr'],
731
732            'O_ns'        => ":$ns",
733            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
734            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
735            'O_extensions'=> join('|',array_keys(getMimeTypes())),
736            'O_overwrite' => ($auth >= AUTH_DELETE),
737            'O_sectok'    => getSecurityToken(),
738            'O_authtok'   => auth_createToken(),
739            );
740    $var = buildURLparams($opt);
741    // output the flash uploader
742    ?>
743        <div id="dw__flashupload" style="display:none">
744        <div class="upload"><?php echo $lang['mu_intro']?></div>
745        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
746        </div>
747        <?php
748}
749
750/**
751 * Print the search field form
752 *
753 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
754 */
755function media_searchform($ns,$query=''){
756    global $lang;
757
758    // The default HTML search form
759    $form = new Doku_Form(array('id' => 'dw__mediasearch', 'action' => DOKU_BASE.'lib/exe/mediamanager.php'));
760    $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
761    $form->addElement(formSecurityToken());
762    $form->addHidden('ns', $ns);
763    $form->addHidden('do', 'searchlist');
764    $form->addElement(form_makeOpenTag('p'));
765    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
766    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
767    $form->addElement(form_makeCloseTag('p'));
768    html_form('searchmedia', $form);
769}
770
771/**
772 * Build a tree outline of available media namespaces
773 *
774 * @author Andreas Gohr <andi@splitbrain.org>
775 */
776function media_nstree($ns){
777    global $conf;
778    global $lang;
779
780    // currently selected namespace
781    $ns  = cleanID($ns);
782    if(empty($ns)){
783        global $ID;
784        $ns = dirname(str_replace(':','/',$ID));
785        if($ns == '.') $ns ='';
786    }
787    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
788
789    $data = array();
790    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
791
792    // wrap a list with the root level around the other namespaces
793    $item = array( 'level' => 0, 'id' => '',
794            'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
795
796    echo '<ul class="idx">';
797    echo media_nstree_li($item);
798    echo media_nstree_item($item);
799    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
800    echo '</li>';
801    echo '</ul>';
802}
803
804/**
805 * Userfunction for html_buildlist
806 *
807 * Prints a media namespace tree item
808 *
809 * @author Andreas Gohr <andi@splitbrain.org>
810 */
811function media_nstree_item($item){
812    $pos   = strrpos($item['id'], ':');
813    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
814    if(!$item['label']) $item['label'] = $label;
815
816    $ret  = '';
817    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
818    $ret .= $item['label'];
819    $ret .= '</a>';
820    return $ret;
821}
822
823/**
824 * Userfunction for html_buildlist
825 *
826 * Prints a media namespace tree item opener
827 *
828 * @author Andreas Gohr <andi@splitbrain.org>
829 */
830function media_nstree_li($item){
831    $class='media level'.$item['level'];
832    if($item['open']){
833        $class .= ' open';
834        $img   = DOKU_BASE.'lib/images/minus.gif';
835        $alt   = '&minus;';
836    }else{
837        $class .= ' closed';
838        $img   = DOKU_BASE.'lib/images/plus.gif';
839        $alt   = '+';
840    }
841    // TODO: only deliver an image if it actually has a subtree...
842    return '<li class="'.$class.'">'.
843        '<img src="'.$img.'" alt="'.$alt.'" />';
844}
845
846/**
847 * Resizes the given image to the given size
848 *
849 * @author  Andreas Gohr <andi@splitbrain.org>
850 */
851function media_resize_image($file, $ext, $w, $h=0){
852    global $conf;
853
854    $info = @getimagesize($file); //get original size
855    if($info == false) return $file; // that's no image - it's a spaceship!
856
857    if(!$h) $h = round(($w * $info[1]) / $info[0]);
858
859    // we wont scale up to infinity
860    if($w > 2000 || $h > 2000) return $file;
861
862    //cache
863    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
864    $mtime = @filemtime($local); // 0 if not exists
865
866    if( $mtime > filemtime($file) ||
867            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
868            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
869        if($conf['fperm']) chmod($local, $conf['fperm']);
870        return $local;
871    }
872    //still here? resizing failed
873    return $file;
874}
875
876/**
877 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
878 * to the wanted size
879 *
880 * Crops are centered horizontally but prefer the upper third of an vertical
881 * image because most pics are more interesting in that area (rule of thirds)
882 *
883 * @author  Andreas Gohr <andi@splitbrain.org>
884 */
885function media_crop_image($file, $ext, $w, $h=0){
886    global $conf;
887
888    if(!$h) $h = $w;
889    $info = @getimagesize($file); //get original size
890    if($info == false) return $file; // that's no image - it's a spaceship!
891
892    // calculate crop size
893    $fr = $info[0]/$info[1];
894    $tr = $w/$h;
895    if($tr >= 1){
896        if($tr > $fr){
897            $cw = $info[0];
898            $ch = (int) $info[0]/$tr;
899        }else{
900            $cw = (int) $info[1]*$tr;
901            $ch = $info[1];
902        }
903    }else{
904        if($tr < $fr){
905            $cw = (int) $info[1]*$tr;
906            $ch = $info[1];
907        }else{
908            $cw = $info[0];
909            $ch = (int) $info[0]/$tr;
910        }
911    }
912    // calculate crop offset
913    $cx = (int) ($info[0]-$cw)/2;
914    $cy = (int) ($info[1]-$ch)/3;
915
916    //cache
917    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
918    $mtime = @filemtime($local); // 0 if not exists
919
920    if( $mtime > filemtime($file) ||
921            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
922            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
923        if($conf['fperm']) chmod($local, $conf['fperm']);
924        return media_resize_image($local,$ext, $w, $h);
925    }
926
927    //still here? cropping failed
928    return media_resize_image($file,$ext, $w, $h);
929}
930
931/**
932 * Download a remote file and return local filename
933 *
934 * returns false if download fails. Uses cached file if available and
935 * wanted
936 *
937 * @author  Andreas Gohr <andi@splitbrain.org>
938 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
939 */
940function media_get_from_URL($url,$ext,$cache){
941    global $conf;
942
943    // if no cache or fetchsize just redirect
944    if ($cache==0)           return false;
945    if (!$conf['fetchsize']) return false;
946
947    $local = getCacheName(strtolower($url),".media.$ext");
948    $mtime = @filemtime($local); // 0 if not exists
949
950    //decide if download needed:
951    if( ($mtime == 0) ||                           // cache does not exist
952            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
953      ){
954        if(media_image_download($url,$local)){
955            return $local;
956        }else{
957            return false;
958        }
959    }
960
961    //if cache exists use it else
962    if($mtime) return $local;
963
964    //else return false
965    return false;
966}
967
968/**
969 * Download image files
970 *
971 * @author Andreas Gohr <andi@splitbrain.org>
972 */
973function media_image_download($url,$file){
974    global $conf;
975    $http = new DokuHTTPClient();
976    $http->max_bodysize = $conf['fetchsize'];
977    $http->timeout = 25; //max. 25 sec
978    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
979
980    $data = $http->get($url);
981    if(!$data) return false;
982
983    $fileexists = @file_exists($file);
984    $fp = @fopen($file,"w");
985    if(!$fp) return false;
986    fwrite($fp,$data);
987    fclose($fp);
988    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
989
990    // check if it is really an image
991    $info = @getimagesize($file);
992    if(!$info){
993        @unlink($file);
994        return false;
995    }
996
997    return true;
998}
999
1000/**
1001 * resize images using external ImageMagick convert program
1002 *
1003 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1004 * @author Andreas Gohr <andi@splitbrain.org>
1005 */
1006function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1007    global $conf;
1008
1009    // check if convert is configured
1010    if(!$conf['im_convert']) return false;
1011
1012    // prepare command
1013    $cmd  = $conf['im_convert'];
1014    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1015    if ($ext == 'jpg' || $ext == 'jpeg') {
1016        $cmd .= ' -quality '.$conf['jpg_quality'];
1017    }
1018    $cmd .= " $from $to";
1019
1020    @exec($cmd,$out,$retval);
1021    if ($retval == 0) return true;
1022    return false;
1023}
1024
1025/**
1026 * crop images using external ImageMagick convert program
1027 *
1028 * @author Andreas Gohr <andi@splitbrain.org>
1029 */
1030function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1031    global $conf;
1032
1033    // check if convert is configured
1034    if(!$conf['im_convert']) return false;
1035
1036    // prepare command
1037    $cmd  = $conf['im_convert'];
1038    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1039    if ($ext == 'jpg' || $ext == 'jpeg') {
1040        $cmd .= ' -quality '.$conf['jpg_quality'];
1041    }
1042    $cmd .= " $from $to";
1043
1044    @exec($cmd,$out,$retval);
1045    if ($retval == 0) return true;
1046    return false;
1047}
1048
1049/**
1050 * resize or crop images using PHP's libGD support
1051 *
1052 * @author Andreas Gohr <andi@splitbrain.org>
1053 * @author Sebastian Wienecke <s_wienecke@web.de>
1054 */
1055function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1056    global $conf;
1057
1058    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1059
1060    // check available memory
1061    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1062        return false;
1063    }
1064
1065    // create an image of the given filetype
1066    if ($ext == 'jpg' || $ext == 'jpeg'){
1067        if(!function_exists("imagecreatefromjpeg")) return false;
1068        $image = @imagecreatefromjpeg($from);
1069    }elseif($ext == 'png') {
1070        if(!function_exists("imagecreatefrompng")) return false;
1071        $image = @imagecreatefrompng($from);
1072
1073    }elseif($ext == 'gif') {
1074        if(!function_exists("imagecreatefromgif")) return false;
1075        $image = @imagecreatefromgif($from);
1076    }
1077    if(!$image) return false;
1078
1079    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1080        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1081    }
1082    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1083    if(!$newimg){
1084        imagedestroy($image);
1085        return false;
1086    }
1087
1088    //keep png alpha channel if possible
1089    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1090        imagealphablending($newimg, false);
1091        imagesavealpha($newimg,true);
1092    }
1093
1094    //keep gif transparent color if possible
1095    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1096        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1097            $transcolorindex = @imagecolortransparent($image);
1098            if($transcolorindex >= 0 ) { //transparent color exists
1099                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1100                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1101                @imagefill($newimg, 0, 0, $transcolorindex);
1102                @imagecolortransparent($newimg, $transcolorindex);
1103            }else{ //filling with white
1104                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1105                @imagefill($newimg, 0, 0, $whitecolorindex);
1106            }
1107        }else{ //filling with white
1108            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1109            @imagefill($newimg, 0, 0, $whitecolorindex);
1110        }
1111    }
1112
1113    //try resampling first
1114    if(function_exists("imagecopyresampled")){
1115        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1116            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1117        }
1118    }else{
1119        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1120    }
1121
1122    $okay = false;
1123    if ($ext == 'jpg' || $ext == 'jpeg'){
1124        if(!function_exists('imagejpeg')){
1125            $okay = false;
1126        }else{
1127            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1128        }
1129    }elseif($ext == 'png') {
1130        if(!function_exists('imagepng')){
1131            $okay = false;
1132        }else{
1133            $okay =  imagepng($newimg, $to);
1134        }
1135    }elseif($ext == 'gif') {
1136        if(!function_exists('imagegif')){
1137            $okay = false;
1138        }else{
1139            $okay = imagegif($newimg, $to);
1140        }
1141    }
1142
1143    // destroy GD image ressources
1144    if($image) imagedestroy($image);
1145    if($newimg) imagedestroy($newimg);
1146
1147    return $okay;
1148}
1149
1150/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1151