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