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