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