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