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