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