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