xref: /dokuwiki/inc/media.php (revision 88a71175e3de9e3ad8b20ca9eb710aaf773cb788)
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 * @author Kate Arzamastseva <pshns@ukr.net>
44 */
45function media_metasave($id,$auth,$data){
46    if($auth < AUTH_UPLOAD) return false;
47    if(!checkSecurityToken()) return false;
48    global $lang;
49    global $conf;
50    $src = mediaFN($id);
51
52    $meta = new JpegMeta($src);
53    $meta->_parseAll();
54
55    foreach($data as $key => $val){
56        $val=trim($val);
57        if(empty($val)){
58            $meta->deleteField($key);
59        }else{
60            $meta->setField($key,$val);
61        }
62    }
63
64    $old = @filemtime($src);
65    if(!@file_exists(mediaFN($id, $old)) && @file_exists($src)) {
66        // add old revision to the attic
67        media_saveOldRevision($id);
68    }
69
70    if($meta->save()){
71        if($conf['fperm']) chmod($src, $conf['fperm']);
72
73        $new = @filemtime($src);
74        // add a log entry to the media changelog
75        addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, $lang['media_meta_edited']);
76
77        msg($lang['metasaveok'],1);
78        return $id;
79    }else{
80        msg($lang['metasaveerr'],-1);
81        return false;
82    }
83}
84
85/**
86 * Display the form to edit image meta data
87 *
88 * @author Andreas Gohr <andi@splitbrain.org>
89 * @author Kate Arzamastseva <pshns@ukr.net>
90 */
91function media_metaform($id,$auth,$fullscreen = false){
92    global $lang, $config_cascade;
93
94    if($auth < AUTH_UPLOAD) {
95        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
96        return false;
97    }
98
99    // load the field descriptions
100    static $fields = null;
101    if(is_null($fields)){
102
103        foreach (array('default','local') as $config_group) {
104            if (empty($config_cascade['mediameta'][$config_group])) continue;
105            foreach ($config_cascade['mediameta'][$config_group] as $config_file) {
106                if(@file_exists($config_file)){
107                    include($config_file);
108                }
109            }
110        }
111    }
112
113    $src = mediaFN($id);
114
115    // output
116    if (!$fullscreen) {
117        echo '<h1>'.hsc(noNS($id)).'</h1>'.NL;
118        echo '<form action="'.DOKU_BASE.'lib/exe/mediamanager.php" accept-charset="utf-8" method="post" class="meta">'.NL;
119    } else {
120        echo '<form action="'.media_managerURL(array('tab_details' => 'view')).
121            '" accept-charset="utf-8" method="post" class="meta">'.NL;
122    }
123    formSecurityToken();
124    foreach($fields as $key => $field){
125        // get current value
126        $tags = array($field[0]);
127        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
128        $value = tpl_img_getTag($tags,'',$src);
129        $value = cleanText($value);
130
131        // prepare attributes
132        $p = array();
133        $p['class'] = 'edit';
134        $p['id']    = 'meta__'.$key;
135        $p['name']  = 'meta['.$field[0].']';
136
137        // put label
138        echo '<div class="metafield">';
139        echo '<label for="meta__'.$key.'">';
140        echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1];
141        echo ':</label>';
142
143        // put input field
144        if($field[2] == 'text'){
145            $p['value'] = $value;
146            $p['type']  = 'text';
147            $att = buildAttributes($p);
148            echo "<input $att/>".NL;
149        }else{
150            $att = buildAttributes($p);
151            echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL;
152        }
153        echo '</div>'.NL;
154    }
155    echo '<div class="buttons">'.NL;
156    echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL;
157    if (!$fullscreen) $do = 'do';
158    else $do = 'mediado';
159    echo '<input name="'.$do.'[save]" type="submit" value="'.$lang['btn_save'].
160        '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL;
161    if (!$fullscreen)
162    echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel'].
163        '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL;
164    echo '</div>'.NL;
165    echo '</form>'.NL;
166}
167
168/**
169 * Convenience function to check if a media file is still in use
170 *
171 * @author Michael Klier <chi@chimeric.de>
172 */
173function media_inuse($id) {
174    global $conf;
175    $mediareferences = array();
176    if($conf['refcheck']){
177        $mediareferences = ft_mediause($id,$conf['refshow']);
178        if(!count($mediareferences)) {
179            return false;
180        } else {
181            return $mediareferences;
182        }
183    } else {
184        return false;
185    }
186}
187
188define('DOKU_MEDIA_DELETED', 1);
189define('DOKU_MEDIA_NOT_AUTH', 2);
190define('DOKU_MEDIA_INUSE', 4);
191define('DOKU_MEDIA_EMPTY_NS', 8);
192
193/**
194 * Handles media file deletions
195 *
196 * If configured, checks for media references before deletion
197 *
198 * @author Andreas Gohr <andi@splitbrain.org>
199 * @return int One of: 0,
200                       DOKU_MEDIA_DELETED,
201                       DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS,
202                       DOKU_MEDIA_NOT_AUTH,
203                       DOKU_MEDIA_INUSE
204 */
205function media_delete($id,$auth){
206    if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
207    if(media_inuse($id)) return DOKU_MEDIA_INUSE;
208
209    $file = mediaFN($id);
210
211    // trigger an event - MEDIA_DELETE_FILE
212    $data['id']   = $id;
213    $data['name'] = basename($file);
214    $data['path'] = $file;
215    $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
216
217    $data['unl'] = false;
218    $data['del'] = false;
219    $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
220    if ($evt->advise_before()) {
221        $data['unl'] = @unlink($file);
222        if($data['unl']){
223            addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE);
224            $data['del'] = io_sweepNS($id,'mediadir');
225        }
226    }
227    $evt->advise_after();
228    unset($evt);
229
230    if($data['unl'] && $data['del']){
231        return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
232    }
233
234    return $data['unl'] ? DOKU_MEDIA_DELETED : 0;
235}
236
237/**
238 * Handles media file uploads
239 *
240 * @author Andreas Gohr <andi@splitbrain.org>
241 * @author Michael Klier <chi@chimeric.de>
242 * @return mixed false on error, id of the new file on success
243 */
244function media_upload($ns,$auth){
245    if(!checkSecurityToken()) return false;
246    global $lang;
247
248    // get file and id
249    $id   = $_POST['id'];
250    $file = $_FILES['upload'];
251    if(empty($id)) $id = $file['name'];
252
253    // check for errors (messages are done in lib/exe/mediamanager.php)
254    if($file['error']) return false;
255
256    // check extensions
257    list($fext,$fmime,$dl) = mimetype($file['name']);
258    list($iext,$imime,$dl) = mimetype($id);
259    if($fext && !$iext){
260        // no extension specified in id - read original one
261        $id   .= '.'.$fext;
262        $imime = $fmime;
263    }elseif($fext && $fext != $iext){
264        // extension was changed, print warning
265        msg(sprintf($lang['mediaextchange'],$fext,$iext));
266    }
267
268    $res = media_save(array('name' => $file['tmp_name'],
269                            'mime' => $imime,
270                            'ext'  => $iext), $ns.':'.$id,
271                      $_REQUEST['ow'], $auth, 'move_uploaded_file');
272    if (is_array($res)) {
273        msg($res[0], $res[1]);
274        return false;
275    }
276    return $res;
277}
278
279/**
280 * This generates an action event and delegates to _media_upload_action().
281 * Action plugins are allowed to pre/postprocess the uploaded file.
282 * (The triggered event is preventable.)
283 *
284 * Event data:
285 * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
286 * $data[1]     fn: the file name of the uploaded file
287 * $data[2]     id: the future directory id of the uploaded file
288 * $data[3]     imime: the mimetype of the uploaded file
289 * $data[4]     overwrite: if an existing file is going to be overwritten
290 *
291 * @triggers MEDIA_UPLOAD_FINISH
292 */
293function media_save($file, $id, $ow, $auth, $move) {
294    if($auth < AUTH_UPLOAD) {
295        return array("You don't have permissions to upload files.", -1);
296    }
297
298    if (!isset($file['mime']) || !isset($file['ext'])) {
299        list($ext, $mime) = mimetype($id);
300        if (!isset($file['mime'])) {
301            $file['mime'] = $mime;
302        }
303        if (!isset($file['ext'])) {
304            $file['ext'] = $ext;
305        }
306    }
307
308    global $lang;
309
310    // get filename
311    $id   = cleanID($id,false,true);
312    $fn   = mediaFN($id);
313
314    // get filetype regexp
315    $types = array_keys(getMimeTypes());
316    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
317    $regex = join('|',$types);
318
319    // because a temp file was created already
320    if(!preg_match('/\.('.$regex.')$/i',$fn)) {
321        return array($lang['uploadwrong'],-1);
322    }
323
324    //check for overwrite
325    $overwrite = @file_exists($fn);
326    if($overwrite && (!$ow || $auth < AUTH_DELETE)) {
327        return array($lang['uploadexist'], 0);
328    }
329    // check for valid content
330    $ok = media_contentcheck($file['name'], $file['mime']);
331    if($ok == -1){
332        return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
333    }elseif($ok == -2){
334        return array($lang['uploadspam'],-1);
335    }elseif($ok == -3){
336        return array($lang['uploadxss'],-1);
337    }
338
339    // prepare event data
340    $data[0] = $file['name'];
341    $data[1] = $fn;
342    $data[2] = $id;
343    $data[3] = $file['mime'];
344    $data[4] = $overwrite;
345    $data[5] = $move;
346
347    // trigger event
348    return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
349}
350
351/**
352 * Callback adapter for media_upload_finish()
353 * @author Michael Klier <chi@chimeric.de>
354 */
355function _media_upload_action($data) {
356    // fixme do further sanity tests of given data?
357    if(is_array($data) && count($data)===6) {
358        return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
359    } else {
360        return false; //callback error
361    }
362}
363
364/**
365 * Saves an uploaded media file
366 *
367 * @author Andreas Gohr <andi@splitbrain.org>
368 * @author Michael Klier <chi@chimeric.de>
369 * @author Kate Arzamastseva <pshns@ukr.net>
370 */
371function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'move_uploaded_file') {
372    global $conf;
373    global $lang;
374
375    $old = @filemtime($fn);
376    if(!@file_exists(mediaFN($id, $old)) && @file_exists($fn)) {
377        // add old revision to the attic if missing
378        media_saveOldRevision($id);
379    }
380
381    // prepare directory
382    io_createNamespace($id, 'media');
383
384    if($move($fn_tmp, $fn)) {
385        $new = @filemtime($fn);
386        // Set the correct permission here.
387        // Always chmod media because they may be saved with different permissions than expected from the php umask.
388        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
389        chmod($fn, $conf['fmode']);
390        msg($lang['uploadsucc'],1);
391        media_notify($id,$fn,$imime);
392        // add a log entry to the media changelog
393        if ($overwrite) {
394            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT);
395        } else {
396            addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created']);
397        }
398        return $id;
399    }else{
400        return array($lang['uploadfail'],-1);
401    }
402}
403
404/**
405 * Moves the current version of media file to the media_attic
406 * directory
407 *
408 * @author Kate Arzamastseva <pshns@ukr.net>
409 * @param string $id
410 * @return int - revision date
411 */
412function media_saveOldRevision($id){
413    global $conf;
414    $oldf = mediaFN($id);
415    if(!@file_exists($oldf)) return '';
416    $date = filemtime($oldf);
417    $newf = mediaFN($id,$date);
418    io_makeFileDir($newf);
419    if(copy($oldf, $newf)) {
420        // Set the correct permission here.
421        // Always chmod media because they may be saved with different permissions than expected from the php umask.
422        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
423        chmod($newf, $conf['fmode']);
424    }
425    return $date;
426}
427
428/**
429 * This function checks if the uploaded content is really what the
430 * mimetype says it is. We also do spam checking for text types here.
431 *
432 * We need to do this stuff because we can not rely on the browser
433 * to do this check correctly. Yes, IE is broken as usual.
434 *
435 * @author Andreas Gohr <andi@splitbrain.org>
436 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
437 * @fixme  check all 26 magic IE filetypes here?
438 */
439function media_contentcheck($file,$mime){
440    global $conf;
441    if($conf['iexssprotect']){
442        $fh = @fopen($file, 'rb');
443        if($fh){
444            $bytes = fread($fh, 256);
445            fclose($fh);
446            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
447                return -3;
448            }
449        }
450    }
451    if(substr($mime,0,6) == 'image/'){
452        $info = @getimagesize($file);
453        if($mime == 'image/gif' && $info[2] != 1){
454            return -1;
455        }elseif($mime == 'image/jpeg' && $info[2] != 2){
456            return -1;
457        }elseif($mime == 'image/png' && $info[2] != 3){
458            return -1;
459        }
460        # fixme maybe check other images types as well
461    }elseif(substr($mime,0,5) == 'text/'){
462        global $TEXT;
463        $TEXT = io_readFile($file);
464        if(checkwordblock()){
465            return -2;
466        }
467    }
468    return 0;
469}
470
471/**
472 * Send a notify mail on uploads
473 *
474 * @author Andreas Gohr <andi@splitbrain.org>
475 */
476function media_notify($id,$file,$mime){
477    global $lang;
478    global $conf;
479    global $INFO;
480    if(empty($conf['notify'])) return; //notify enabled?
481
482    $ip = clientIP();
483
484    $text = rawLocale('uploadmail');
485    $text = str_replace('@DATE@',dformat(),$text);
486    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
487    $text = str_replace('@IPADDRESS@',$ip,$text);
488    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
489    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
490    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
491    $text = str_replace('@MIME@',$mime,$text);
492    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
493    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
494
495    $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
496
497    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
498}
499
500/**
501 * List all files in a given Media namespace
502 */
503function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false){
504    global $conf;
505    global $lang;
506    $ns = cleanID($ns);
507
508    // check auth our self if not given (needed for ajax calls)
509    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
510
511    if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
512
513    if($auth < AUTH_READ){
514        // FIXME: print permission warning here instead?
515        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
516    }else{
517        if (!$fullscreenview) media_uploadform($ns, $auth);
518
519        $dir = utf8_encodeFN(str_replace(':','/',$ns));
520        $data = array();
521        search($data,$conf['mediadir'],'search_media',
522                array('showmsg'=>true,'depth'=>1),$dir);
523
524        if(!count($data)){
525            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
526        }else foreach($data as $item){
527            if (!$fullscreenview) media_printfile($item,$auth,$jump);
528            else if ($fullscreenview == 'thumbs') media_printfile_thumbs($item,$auth,$jump);
529        }
530    }
531    if (!$fullscreenview) media_searchform($ns);
532}
533
534/**
535 * Prints tabs for files list actions
536 *
537 * @author Kate Arzamastseva <pshns@ukr.net>
538 * @param string $selected - opened tab
539 */
540function media_tabs_files($selected=false){
541    global $lang;
542
543    echo '<div class="mediamanager-tabs" id="id-mediamanager-tabs">';
544    $tab = '<a href="'.media_managerURL(array('tab_files' => 'files')).
545        '" rel=".mediamanager-tab-files"';
546    if (!empty($selected) && $selected == 'files') $class = 'files selected';
547    else $class = 'files';
548    $tab .= ' class="'.$class.'" >'.$lang['mediaselect'].'</a>';
549    echo $tab;
550
551    $tab = '<a href="'.media_managerURL(array('tab_files' => 'upload')).
552        '" rel=".mediamanager-tab-upload"';
553    if (!empty($selected) && $selected == 'upload') $class = 'upload selected';
554    else $class = 'upload';
555    $tab .= ' class="'.$class.'" >'.$lang['media_uploadtab'].'</a>';
556    echo $tab;
557
558    $tab = '<a href="'.media_managerURL(array('tab_files' => 'search')).
559        '" rel=".mediamanager-tab-search"';
560    if (!empty($selected) && $selected == 'search') $class = 'search selected';
561    else $class = 'search';
562    $tab .= ' class="'.$class.'" >'.$lang['media_searchtab'].'</a>';
563    echo $tab;
564
565    echo '<div class="clearer"></div>';
566    echo '</div>';
567}
568
569/**
570 * Prints tabs for files details actions
571 *
572 * @author Kate Arzamastseva <pshns@ukr.net>
573 * @param string $selected - opened tab
574 */
575function media_tabs_details($selected=false){
576    global $lang;
577
578    echo '<div class="mediamanager-tabs" id="id-mediamanager-tabs-detail">';
579    $tab = '<a href="'.media_managerURL(array('tab_details' => 'view')).
580        '" rel=".mediamanager-tab-view"';
581    if (!empty($selected) && $selected == 'view') $class = 'view selected';
582    else $class = 'view';
583    $tab .= ' class="'.$class.'" >'.$lang['media_viewtab'].'</a>';
584    echo $tab;
585
586    $tab = '<a href="'.media_managerURL(array('tab_details' => 'edit')).
587        '" rel=".mediamanager-tab-edit"';
588    if (!empty($selected) && $selected == 'edit') $class = 'edit selected';
589    else $class = 'edit';
590    $tab .= ' class="'.$class.'" >'.$lang['media_edittab'].'</a>';
591    echo $tab;
592
593    $tab = '<a href="'.media_managerURL(array('tab_details' => 'history')).
594        '" rel=".mediamanager-tab-history"';
595    if (!empty($selected) && $selected == 'history') $class = 'history selected';
596    else $class = 'history';
597    $tab .= ' class="'.$class.'" >'.$lang['media_historytab'].'</a>';
598    echo $tab;
599
600    echo '<div class="clearer"></div>';
601    echo '</div>';
602}
603
604/**
605 * Prints options for the tab that displays a list of all files
606 *
607 * @author Kate Arzamastseva <pshns@ukr.net>
608 */
609function media_tab_files_options(){
610    global $lang;
611
612    echo '<div class="background-container">';
613    echo '<div id="id-mediamanager-tabs-files" style="display: inline;">';
614    echo '<a href="'.media_managerURL(array('view' => 'thumbs')).'"
615        rel=".mediamanager-files-thumbnails-tab" class="mediamanager-link-thumbnails">'.
616        $lang['media_thumbsview'].'</a>';
617    echo '<a href="'.media_managerURL(array('view' => 'list')).'"
618        rel=".mediamanager-files-list-tab" class="mediamanager-link-list"
619        title="View as list">'.$lang['media_listview'].'</a>';
620
621    echo '</div>';
622    echo '<div class="mediamanager-block-sort">'.$lang['media_sort'];
623    //select
624    echo '</div>';
625    echo '<div class="clearer"></div>';
626    echo '</div>';
627}
628
629/**
630 * Prints tab that displays a list of all files
631 *
632 * @author Kate Arzamastseva <pshns@ukr.net>
633 */
634function media_tab_files($ns,$auth=null,$jump='') {
635    global $lang;
636    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
637
638    echo '<div class="mediamanager-tab-files">';
639    media_tab_files_options();
640    echo '<div class="scroll-container">';
641
642    $view = $_REQUEST['view'];
643    if($auth < AUTH_READ){
644        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
645    }else{
646        if ($view == 'list') {
647            echo '<ul class="mediamanager-file-list mediamanager-list" id="id-mediamanager-file-list">';
648        } else {
649            echo '<ul class="mediamanager-file-list mediamanager-thumbs" id="id-mediamanager-file-list">';
650        }
651        media_filelist($ns,$auth,$jump,'thumbs');
652        echo '</ul>';
653    }
654    echo '</div>';
655    echo '</div>';
656}
657
658/**
659 * Prints tab that displays uploading form
660 *
661 * @author Kate Arzamastseva <pshns@ukr.net>
662 */
663function media_tab_upload($ns,$auth=null,$jump='') {
664    global $lang;
665    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
666
667    echo '<div class="mediamanager-tab-upload"">';
668    echo '<div class="background-container">';
669    echo $lang['mediaupload'];
670    echo '</div>';
671
672    echo '<div class="scroll-container">';
673    media_uploadform($ns, $auth, true);
674    echo '</div>';
675    echo '</div>';
676}
677
678/**
679 * Prints tab that displays search form
680 *
681 * @author Kate Arzamastseva <pshns@ukr.net>
682 */
683function media_tab_search($ns,$auth=null) {
684    global $lang;
685
686    $do = $_REQUEST['mediado'];
687    $query = $_REQUEST['q'];
688    if (!$query) $query = '';
689
690    echo '<div class="mediamanager-tab-search">';
691    echo '<div class="background-container">';
692    echo $lang['media_search'];
693    echo'</div>';
694
695    echo '<div class="scroll-container">';
696    media_searchform($ns, $query, true);
697
698    if($do == 'searchlist'){
699        media_searchlist($query,$ns,$auth,true);
700    }
701    echo '</div>';
702    echo '</div>';
703}
704
705/**
706 * Prints tab that displays mediafile details
707 *
708 * @author Kate Arzamastseva <pshns@ukr.net>
709 */
710function media_tab_view($image, $ns, $auth=null) {
711    global $lang, $conf;
712    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
713
714    echo '<div class="mediamanager-tab-detail-view">';
715    echo '<div class="background-container">';
716    echo $image;
717    echo '</div>';
718
719    echo '<div class="scroll-container">';
720    $rev = (int) $_REQUEST['rev'];
721    media_preview($image, $auth, $rev);
722    media_details($image, $auth, $rev);
723    echo '</div>';
724    echo '</div>';
725}
726
727/**
728 * Prints tab that displays form for editing mediafile metadata
729 *
730 * @author Kate Arzamastseva <pshns@ukr.net>
731 */
732function media_tab_edit($image, $ns, $auth=null) {
733    global $lang;
734    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
735
736    echo '<div class="mediamanager-tab-detail-edit">';
737    echo '<div class="background-container">';
738    echo $lang['media_edit'];
739    echo '</div>';
740
741    echo '<div class="scroll-container">';
742    if ($image) {
743        list($ext, $mime) = mimetype($image);
744        if ($mime == 'image/jpeg') media_metaform($image,$auth,true);
745    }
746    echo '</div>';
747    echo '</div>';
748}
749
750/**
751 * Prints tab that displays mediafile revisions
752 *
753 * @author Kate Arzamastseva <pshns@ukr.net>
754 */
755function media_tab_history($image, $ns, $auth=null) {
756    global $lang;
757    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
758    $do = $_REQUEST['mediado'];
759
760    echo '<div class="mediamanager-tab-detail-history">';
761    echo '<div class="background-container">';
762    echo $lang['media_history'];
763    echo '</div>';
764
765    echo '<div class="scroll-container">';
766    if ($auth >= AUTH_READ && $image) {
767        if ($do == 'diff'){
768            media_diff($image, $ns, $auth);
769        } else {
770            $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
771            html_revisions($first, $image);
772        }
773    } else {
774        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
775    }
776    echo '</div>';
777    echo '</div>';
778}
779
780/**
781 * Prints mediafile details
782 *
783 * @author Kate Arzamastseva <pshns@ukr.net>
784 */
785function media_preview($image, $auth, $rev=false) {
786    global $lang;
787    if (!$image) return '';
788    if ($auth < AUTH_READ) {
789        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
790        return '';
791    }
792    $info = getimagesize(mediaFN($image));
793    $w = (int) $info[0];
794
795    $more = '';
796    if ($rev) $more = "rev=$rev";
797    $src = ml($image, $more);
798
799    echo '<img src="'.$src.'" alt="" width="99%" style="max-width: '.$w.'px;" /><br /><br />';
800
801    $link = ml($image,$more,true);
802    echo $image.' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
803    'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
804
805    // delete button
806    if($auth >= AUTH_DELETE && !$rev){
807       $link = media_managerURL(array('delete' => $image,'sectok' => getSecurityToken()));
808        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$image.'">'.
809            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
810            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
811    }
812
813}
814
815/**
816 * Prints mediafile tags
817 *
818 * @author Kate Arzamastseva <pshns@ukr.net>
819 */
820function media_details($image, $auth, $rev=false) {
821    global $lang, $config_cascade;;
822
823    if (!$image) return '';
824    if ($auth < AUTH_READ) {
825        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
826        return '';
827    }
828
829    // load the field descriptions
830    static $tags = null;
831    if(is_null($tags)){
832        foreach (array('default','local') as $config_group) {
833            if (empty($config_cascade['mediameta'][$config_group])) continue;
834            foreach ($config_cascade['mediameta'][$config_group] as $config_file) {
835                if(@file_exists($config_file)){
836                    include($config_file);
837                }
838            }
839        }
840    }
841
842    $src = mediaFN($image, $rev);
843    $meta = new JpegMeta($src);
844    echo '<dl class="img_tags">';
845    foreach($tags as $key => $tag){
846        $t = $tag[0];
847        if (!is_array($t)) $t = array($tag[0]);
848        $value = media_getTag($t, $meta, '-');
849        $value = cleanText($value);
850        echo '<dt>'.$lang[$tag[1]].':</dt><dd>';
851        if ($tag[2] == 'text') echo hsc($value);
852        if ($tag[2] == 'date') echo dformat($value);
853        echo '</dd>';
854    }
855    echo '</dl>';
856}
857
858/**
859 * Returns the requested EXIF/IPTC tag from the image meta
860 *
861 * @author Kate Arzamastseva <pshns@ukr.net>
862 * @param array $tags
863 * @param JpegMeta $meta
864 * @param string $alt
865 * @return string
866 */
867function media_getTag($tags,$meta,$alt=''){
868    if($meta === false) return $alt;
869    $info = $meta->getField($tags);
870    if($info == false) return $alt;
871    return $info;
872}
873
874/**
875 * Shows difference between two revisions of file
876 *
877 * @author Kate Arzamastseva <pshns@ukr.net>
878 */
879function media_diff($image, $ns, $auth) {
880    global $lang;
881    global $conf;
882
883    $rev1 = (int) $_REQUEST['rev'];
884
885    if(is_array($_REQUEST['rev2'])){
886        $rev1 = (int) $_REQUEST['rev2'][0];
887        $rev2 = (int) $_REQUEST['rev2'][1];
888
889        if(!$rev1){
890            $rev1 = $rev2;
891            unset($rev2);
892        }
893    }else{
894        $rev2 = (int) $_REQUEST['rev2'];
895    }
896    if($rev1 && $rev2){            // two specific revisions wanted
897        // make sure order is correct (older on the left)
898        if($rev1 < $rev2){
899            $l_rev = $rev1;
900            $r_rev = $rev2;
901        }else{
902            $l_rev = $rev2;
903            $r_rev = $rev1;
904        }
905    }elseif($rev1){                // single revision given, compare to current
906        $r_rev = '';
907        $l_rev = $rev1;
908    }else{                        // no revision was given, compare previous to current
909        $r_rev = '';
910        $revs = getRevisions($image, 0, 1, 8192, true);
911        $l_rev = $revs[0];
912    }
913    echo '<ul class="mediamanager-table-50"><li><div>';
914    media_preview($image, $auth, $l_rev);
915    echo '</div></li>';
916    echo '<li><div>';
917    media_preview($image, $auth, $r_rev);
918    echo '</div></li><li><div>';
919    media_details($image, $auth, $l_rev);
920    echo '</div></li>';
921    echo '<li><div>';
922    media_details($image, $auth, $r_rev);
923    echo '</div></li></ul>';
924}
925
926/**
927 * List all files found by the search request
928 *
929 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
930 * @author Andreas Gohr <gohr@cosmocode.de>
931 * @author Kate Arzamastseva <pshns@ukr.net>
932 * @triggers MEDIA_SEARCH
933 */
934function media_searchlist($query,$ns,$auth=null,$fullscreen=false){
935    global $conf;
936    global $lang;
937
938    $ns = cleanID($ns);
939
940    if ($query) {
941        $evdata = array(
942                'ns'    => $ns,
943                'data'  => array(),
944                'query' => $query
945                );
946        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
947        if ($evt->advise_before()) {
948            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
949            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
950            search($evdata['data'],
951                    $conf['mediadir'],
952                    'search_media',
953                    array('showmsg'=>false,'pattern'=>$pattern),
954                    $dir);
955        }
956        $evt->advise_after();
957        unset($evt);
958    }
959
960    if (!$fullscreen) {
961        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
962        media_searchform($ns,$query);
963    }
964
965    if(!count($evdata['data'])){
966        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
967    }else foreach($evdata['data'] as $item){
968        if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
969        else media_printfile_thumbs($item,$item['perm'],'',true);
970    }
971}
972
973/**
974 * Print action links for a file depending on filetype
975 * and available permissions
976 */
977function media_fileactions($item,$auth){
978    global $lang;
979
980    // view button
981    $link = ml($item['id'],'',true);
982    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
983        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
984
985    // no further actions if not writable
986    if(!$item['writable']) return;
987
988    // delete button
989    if($auth >= AUTH_DELETE){
990        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
991            '&amp;sectok='.getSecurityToken();
992        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
993            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
994            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
995    }
996
997    // edit button
998    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
999        $link = DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']);
1000        echo ' <a href="'.$link.'">'.
1001            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
1002            'title="'.$lang['metaedit'].'" class="btn" /></a>';
1003    }
1004
1005}
1006
1007/**
1008 * Formats and prints one file in the list
1009 */
1010function media_printfile($item,$auth,$jump,$display_namespace=false){
1011    global $lang;
1012    global $conf;
1013
1014    // Prepare zebra coloring
1015    // I always wanted to use this variable name :-D
1016    static $twibble = 1;
1017    $twibble *= -1;
1018    $zebra = ($twibble == -1) ? 'odd' : 'even';
1019
1020    // Automatically jump to recent action
1021    if($jump == $item['id']) {
1022        $jump = ' id="scroll__here" ';
1023    }else{
1024        $jump = '';
1025    }
1026
1027    // Prepare fileicons
1028    list($ext,$mime,$dl) = mimetype($item['file'],false);
1029    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1030    $class = 'select mediafile mf_'.$class;
1031
1032    // Prepare filename
1033    $file = utf8_decodeFN($item['file']);
1034
1035    // Prepare info
1036    $info = '';
1037    if($item['isimg']){
1038        $info .= (int) $item['meta']->getField('File.Width');
1039        $info .= '&#215;';
1040        $info .= (int) $item['meta']->getField('File.Height');
1041        $info .= ' ';
1042    }
1043    $info .= '<i>'.dformat($item['mtime']).'</i>';
1044    $info .= ' ';
1045    $info .= filesize_h($item['size']);
1046
1047    // output
1048    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
1049    if (!$display_namespace) {
1050        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1051    } else {
1052        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1053    }
1054    echo '<span class="info">('.$info.')</span>'.NL;
1055    media_fileactions($item,$auth);
1056    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1057    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1058    echo '</div>';
1059    if($item['isimg']) media_printimgdetail($item);
1060    echo '<div class="clearer"></div>'.NL;
1061    echo '</div>'.NL;
1062}
1063
1064/**
1065 * Formats and prints one file in the list in the thumbnails view
1066 *
1067 * @author Kate Arzamastseva <pshns@ukr.net>
1068 */
1069function media_printfile_thumbs($item,$auth,$jump){
1070    global $lang;
1071    global $conf;
1072
1073    // Prepare filename
1074    $file = utf8_decodeFN($item['file']);
1075
1076    // output
1077    echo '<li><div>';
1078    if($item['isimg']) {
1079        media_printimgdetail($item, true);
1080    } else {
1081        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1082            media_managerURL(array('image' => hsc($item['id']))).'">';
1083        echo '<img src="'.DOKU_BASE.'lib/images/icon-file.png" width="90px" />';
1084        echo '</a>';
1085    }
1086    echo '<a href="'.media_managerURL(array('image' => hsc($item['id']))).'" name=
1087        "h_:'.$item['id'].'" class="info" >'.hsc($file).'</a>';
1088    if($item['isimg']){
1089        $info = '';
1090        $info .= (int) $item['meta']->getField('File.Width');
1091        $info .= '&#215;';
1092        $info .= (int) $item['meta']->getField('File.Height');
1093        echo '<span class="info">'.$info.'</span>';
1094    } else {
1095        echo '<span class="info">&nbsp;</span>';
1096    }
1097    $info = '<i>'.dformat($item['mtime']).'</i>';
1098    echo '<span class="info">'.$info.'</span>';
1099    $info = filesize_h($item['size']);
1100    echo '<span class="info">'.$info.'</span>';
1101    echo '<div class="clearer"></div>';
1102    echo '</div></li>'.NL;
1103}
1104
1105/**
1106 * Prints a thumbnail and metainfos
1107 */
1108function media_printimgdetail($item, $fullscreen=false){
1109    // prepare thumbnail
1110    if (!$fullscreen) $size = 120;
1111    else $size = 90;
1112    $w = (int) $item['meta']->getField('File.Width');
1113    $h = (int) $item['meta']->getField('File.Height');
1114    if($w>$size || $h>$size){
1115        if (!$fullscreen) {
1116            $ratio = $item['meta']->getResizeRatio($size);
1117        } else {
1118            $ratio = $item['meta']->getResizeRatio($size,$size);
1119        }
1120        $w = floor($w * $ratio);
1121        $h = floor($h * $ratio);
1122    }
1123    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
1124    $p = array();
1125    $p['width']  = $w;
1126    if (!$fullscreen) $p['height'] = $h;
1127    $p['alt']    = $item['id'];
1128    $p['class']  = 'thumb';
1129    $att = buildAttributes($p);
1130
1131    // output
1132    if ($fullscreen) {
1133        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1134            media_managerURL(array('image' => hsc($item['id']))).'">';
1135        echo '<img src="'.$src.'" '.$att.' />';
1136        echo '</a>';
1137        return 1;
1138    }
1139
1140    echo '<div class="detail">';
1141    echo '<div class="thumb">';
1142    echo '<a name="d_:'.$item['id'].'" class="select">';
1143    echo '<img src="'.$src.'" '.$att.' />';
1144    echo '</a>';
1145    echo '</div>';
1146
1147    // read EXIF/IPTC data
1148    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1149    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1150                'EXIF.TIFFImageDescription',
1151                'EXIF.TIFFUserComment'));
1152    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1153    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1154
1155    // print EXIF/IPTC data
1156    if($t || $d || $k ){
1157        echo '<p>';
1158        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1159        if($d) echo htmlspecialchars($d).'<br />';
1160        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1161        echo '</p>';
1162    }
1163    echo '</div>';
1164}
1165
1166/**
1167 * Build link based on the current, adding/rewriting
1168 * parameters
1169 *
1170 * @author Kate Arzamastseva <pshns@ukr.net>
1171 * @param array $params
1172 * @param string $amp - separator
1173 * @return string - link
1174 */
1175function media_managerURL($params=false, $amp='&') {
1176    global $conf;
1177    global $ID;
1178
1179    $url = $_SERVER['REQUEST_URI'];
1180
1181    $urlArray = explode('?', $url, 2);
1182    $gets = @$urlArray[1];
1183    parse_str($gets, $gets);
1184
1185    if ($gets['edit']) $gets['image'] = $gets['edit'];
1186    unset($gets['edit']);
1187    unset($gets['sectok']);
1188    unset($gets['delete']);
1189    unset($gets['rev']);
1190    unset($gets['mediado']);
1191
1192    if ($params) {
1193        foreach ($params as $k => $v) {
1194            $gets[$k] = $v;
1195        }
1196    }
1197    unset($gets['id']);
1198    if ($gets['delete']) {
1199        unset($gets['image']);
1200        unset($gets['tab_details']);
1201    }
1202
1203    return wl($ID,$gets,false,$amp);
1204}
1205
1206/**
1207 * Print the media upload form if permissions are correct
1208 *
1209 * @author Andreas Gohr <andi@splitbrain.org>
1210 * @author Kate Arzamastseva <pshns@ukr.net>
1211 */
1212function media_uploadform($ns, $auth, $fullscreen = false){
1213    global $lang;
1214
1215    if($auth < AUTH_UPLOAD) {
1216        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1217        return;
1218    }
1219
1220    // The default HTML upload form
1221    $params = array('id'      => 'dw__upload',
1222                    'enctype' => 'multipart/form-data');
1223    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1224    else $params['action'] = media_managerURL(array('tab_files' => 'files'));
1225
1226    $form = new Doku_Form($params);
1227    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
1228    $form->addElement(formSecurityToken());
1229    $form->addHidden('ns', hsc($ns));
1230    $form->addElement(form_makeOpenTag('p'));
1231    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1232    $form->addElement(form_makeCloseTag('p'));
1233    $form->addElement(form_makeOpenTag('p'));
1234    $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name'));
1235    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1236    $form->addElement(form_makeCloseTag('p'));
1237
1238    if($auth >= AUTH_DELETE){
1239        $form->addElement(form_makeOpenTag('p'));
1240        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check'));
1241        $form->addElement(form_makeCloseTag('p'));
1242    }
1243    html_form('upload', $form);
1244
1245    // prepare flashvars for multiupload
1246    $opt = array(
1247            'L_gridname'  => $lang['mu_gridname'] ,
1248            'L_gridsize'  => $lang['mu_gridsize'] ,
1249            'L_gridstat'  => $lang['mu_gridstat'] ,
1250            'L_namespace' => $lang['mu_namespace'] ,
1251            'L_overwrite' => $lang['txt_overwrt'],
1252            'L_browse'    => $lang['mu_browse'],
1253            'L_upload'    => $lang['btn_upload'],
1254            'L_toobig'    => $lang['mu_toobig'],
1255            'L_ready'     => $lang['mu_ready'],
1256            'L_done'      => $lang['mu_done'],
1257            'L_fail'      => $lang['mu_fail'],
1258            'L_authfail'  => $lang['mu_authfail'],
1259            'L_progress'  => $lang['mu_progress'],
1260            'L_filetypes' => $lang['mu_filetypes'],
1261            'L_info'      => $lang['mu_info'],
1262            'L_lasterr'   => $lang['mu_lasterr'],
1263
1264            'O_ns'        => ":$ns",
1265            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
1266            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
1267            'O_extensions'=> join('|',array_keys(getMimeTypes())),
1268            'O_overwrite' => ($auth >= AUTH_DELETE),
1269            'O_sectok'    => getSecurityToken(),
1270            'O_authtok'   => auth_createToken(),
1271            );
1272    $var = buildURLparams($opt);
1273    // output the flash uploader
1274    ?>
1275        <div id="dw__flashupload" style="display:none">
1276        <div class="upload"><?php echo $lang['mu_intro']?></div>
1277        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
1278        </div>
1279        <?php
1280}
1281
1282/**
1283 * Print the search field form
1284 *
1285 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1286 * @author Kate Arzamastseva <pshns@ukr.net>
1287 */
1288function media_searchform($ns,$query='',$fullscreen=false){
1289    global $lang;
1290
1291    // The default HTML search form
1292    $params = array('id' => 'dw__mediasearch');
1293    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1294    else $params['action'] = media_managerURL();
1295    $form = new Doku_Form($params);
1296    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
1297    $form->addElement(formSecurityToken());
1298    $form->addHidden('ns', $ns);
1299    if (!$fullscreen) $form->addHidden('do', 'searchlist');
1300    else $form->addHidden('mediado', 'searchlist');
1301    $form->addElement(form_makeOpenTag('p'));
1302    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1303    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1304    $form->addElement(form_makeCloseTag('p'));
1305    html_form('searchmedia', $form);
1306}
1307
1308/**
1309 * Build a tree outline of available media namespaces
1310 *
1311 * @author Andreas Gohr <andi@splitbrain.org>
1312 */
1313function media_nstree($ns){
1314    global $conf;
1315    global $lang;
1316
1317    // currently selected namespace
1318    $ns  = cleanID($ns);
1319    if(empty($ns)){
1320        global $ID;
1321        $ns = dirname(str_replace(':','/',$ID));
1322        if($ns == '.') $ns ='';
1323    }
1324    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1325
1326    $data = array();
1327    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1328
1329    // wrap a list with the root level around the other namespaces
1330    $item = array( 'level' => 0, 'id' => '',
1331            'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
1332
1333    echo '<ul class="idx">';
1334    echo media_nstree_li($item);
1335    echo media_nstree_item($item);
1336    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1337    echo '</li>';
1338    echo '</ul>';
1339}
1340
1341/**
1342 * Userfunction for html_buildlist
1343 *
1344 * Prints a media namespace tree item
1345 *
1346 * @author Andreas Gohr <andi@splitbrain.org>
1347 */
1348function media_nstree_item($item){
1349    $pos   = strrpos($item['id'], ':');
1350    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1351    if(!$item['label']) $item['label'] = $label;
1352
1353    $ret  = '';
1354    if (!($_REQUEST['do'] == 'media'))
1355    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1356    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id']))).'" class="idx_dir">';
1357    $ret .= $item['label'];
1358    $ret .= '</a>';
1359    return $ret;
1360}
1361
1362/**
1363 * Userfunction for html_buildlist
1364 *
1365 * Prints a media namespace tree item opener
1366 *
1367 * @author Andreas Gohr <andi@splitbrain.org>
1368 */
1369function media_nstree_li($item){
1370    $class='media level'.$item['level'];
1371    if($item['open']){
1372        $class .= ' open';
1373        $img   = DOKU_BASE.'lib/images/minus.gif';
1374        $alt   = '&minus;';
1375    }else{
1376        $class .= ' closed';
1377        $img   = DOKU_BASE.'lib/images/plus.gif';
1378        $alt   = '+';
1379    }
1380    // TODO: only deliver an image if it actually has a subtree...
1381    return '<li class="'.$class.'">'.
1382        '<img src="'.$img.'" alt="'.$alt.'" />';
1383}
1384
1385/**
1386 * Resizes the given image to the given size
1387 *
1388 * @author  Andreas Gohr <andi@splitbrain.org>
1389 */
1390function media_resize_image($file, $ext, $w, $h=0){
1391    global $conf;
1392
1393    $info = @getimagesize($file); //get original size
1394    if($info == false) return $file; // that's no image - it's a spaceship!
1395
1396    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1397
1398    // we wont scale up to infinity
1399    if($w > 2000 || $h > 2000) return $file;
1400
1401    //cache
1402    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1403    $mtime = @filemtime($local); // 0 if not exists
1404
1405    if( $mtime > filemtime($file) ||
1406            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1407            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1408        if($conf['fperm']) chmod($local, $conf['fperm']);
1409        return $local;
1410    }
1411    //still here? resizing failed
1412    return $file;
1413}
1414
1415/**
1416 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1417 * to the wanted size
1418 *
1419 * Crops are centered horizontally but prefer the upper third of an vertical
1420 * image because most pics are more interesting in that area (rule of thirds)
1421 *
1422 * @author  Andreas Gohr <andi@splitbrain.org>
1423 */
1424function media_crop_image($file, $ext, $w, $h=0){
1425    global $conf;
1426
1427    if(!$h) $h = $w;
1428    $info = @getimagesize($file); //get original size
1429    if($info == false) return $file; // that's no image - it's a spaceship!
1430
1431    // calculate crop size
1432    $fr = $info[0]/$info[1];
1433    $tr = $w/$h;
1434    if($tr >= 1){
1435        if($tr > $fr){
1436            $cw = $info[0];
1437            $ch = (int) $info[0]/$tr;
1438        }else{
1439            $cw = (int) $info[1]*$tr;
1440            $ch = $info[1];
1441        }
1442    }else{
1443        if($tr < $fr){
1444            $cw = (int) $info[1]*$tr;
1445            $ch = $info[1];
1446        }else{
1447            $cw = $info[0];
1448            $ch = (int) $info[0]/$tr;
1449        }
1450    }
1451    // calculate crop offset
1452    $cx = (int) ($info[0]-$cw)/2;
1453    $cy = (int) ($info[1]-$ch)/3;
1454
1455    //cache
1456    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1457    $mtime = @filemtime($local); // 0 if not exists
1458
1459    if( $mtime > filemtime($file) ||
1460            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1461            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1462        if($conf['fperm']) chmod($local, $conf['fperm']);
1463        return media_resize_image($local,$ext, $w, $h);
1464    }
1465
1466    //still here? cropping failed
1467    return media_resize_image($file,$ext, $w, $h);
1468}
1469
1470/**
1471 * Download a remote file and return local filename
1472 *
1473 * returns false if download fails. Uses cached file if available and
1474 * wanted
1475 *
1476 * @author  Andreas Gohr <andi@splitbrain.org>
1477 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1478 */
1479function media_get_from_URL($url,$ext,$cache){
1480    global $conf;
1481
1482    // if no cache or fetchsize just redirect
1483    if ($cache==0)           return false;
1484    if (!$conf['fetchsize']) return false;
1485
1486    $local = getCacheName(strtolower($url),".media.$ext");
1487    $mtime = @filemtime($local); // 0 if not exists
1488
1489    //decide if download needed:
1490    if( ($mtime == 0) ||                           // cache does not exist
1491            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1492      ){
1493        if(media_image_download($url,$local)){
1494            return $local;
1495        }else{
1496            return false;
1497        }
1498    }
1499
1500    //if cache exists use it else
1501    if($mtime) return $local;
1502
1503    //else return false
1504    return false;
1505}
1506
1507/**
1508 * Download image files
1509 *
1510 * @author Andreas Gohr <andi@splitbrain.org>
1511 */
1512function media_image_download($url,$file){
1513    global $conf;
1514    $http = new DokuHTTPClient();
1515    $http->max_bodysize = $conf['fetchsize'];
1516    $http->timeout = 25; //max. 25 sec
1517    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1518
1519    $data = $http->get($url);
1520    if(!$data) return false;
1521
1522    $fileexists = @file_exists($file);
1523    $fp = @fopen($file,"w");
1524    if(!$fp) return false;
1525    fwrite($fp,$data);
1526    fclose($fp);
1527    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1528
1529    // check if it is really an image
1530    $info = @getimagesize($file);
1531    if(!$info){
1532        @unlink($file);
1533        return false;
1534    }
1535
1536    return true;
1537}
1538
1539/**
1540 * resize images using external ImageMagick convert program
1541 *
1542 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1543 * @author Andreas Gohr <andi@splitbrain.org>
1544 */
1545function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1546    global $conf;
1547
1548    // check if convert is configured
1549    if(!$conf['im_convert']) return false;
1550
1551    // prepare command
1552    $cmd  = $conf['im_convert'];
1553    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1554    if ($ext == 'jpg' || $ext == 'jpeg') {
1555        $cmd .= ' -quality '.$conf['jpg_quality'];
1556    }
1557    $cmd .= " $from $to";
1558
1559    @exec($cmd,$out,$retval);
1560    if ($retval == 0) return true;
1561    return false;
1562}
1563
1564/**
1565 * crop images using external ImageMagick convert program
1566 *
1567 * @author Andreas Gohr <andi@splitbrain.org>
1568 */
1569function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1570    global $conf;
1571
1572    // check if convert is configured
1573    if(!$conf['im_convert']) return false;
1574
1575    // prepare command
1576    $cmd  = $conf['im_convert'];
1577    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1578    if ($ext == 'jpg' || $ext == 'jpeg') {
1579        $cmd .= ' -quality '.$conf['jpg_quality'];
1580    }
1581    $cmd .= " $from $to";
1582
1583    @exec($cmd,$out,$retval);
1584    if ($retval == 0) return true;
1585    return false;
1586}
1587
1588/**
1589 * resize or crop images using PHP's libGD support
1590 *
1591 * @author Andreas Gohr <andi@splitbrain.org>
1592 * @author Sebastian Wienecke <s_wienecke@web.de>
1593 */
1594function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1595    global $conf;
1596
1597    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1598
1599    // check available memory
1600    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1601        return false;
1602    }
1603
1604    // create an image of the given filetype
1605    if ($ext == 'jpg' || $ext == 'jpeg'){
1606        if(!function_exists("imagecreatefromjpeg")) return false;
1607        $image = @imagecreatefromjpeg($from);
1608    }elseif($ext == 'png') {
1609        if(!function_exists("imagecreatefrompng")) return false;
1610        $image = @imagecreatefrompng($from);
1611
1612    }elseif($ext == 'gif') {
1613        if(!function_exists("imagecreatefromgif")) return false;
1614        $image = @imagecreatefromgif($from);
1615    }
1616    if(!$image) return false;
1617
1618    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1619        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1620    }
1621    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1622    if(!$newimg){
1623        imagedestroy($image);
1624        return false;
1625    }
1626
1627    //keep png alpha channel if possible
1628    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1629        imagealphablending($newimg, false);
1630        imagesavealpha($newimg,true);
1631    }
1632
1633    //keep gif transparent color if possible
1634    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1635        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1636            $transcolorindex = @imagecolortransparent($image);
1637            if($transcolorindex >= 0 ) { //transparent color exists
1638                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1639                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1640                @imagefill($newimg, 0, 0, $transcolorindex);
1641                @imagecolortransparent($newimg, $transcolorindex);
1642            }else{ //filling with white
1643                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1644                @imagefill($newimg, 0, 0, $whitecolorindex);
1645            }
1646        }else{ //filling with white
1647            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1648            @imagefill($newimg, 0, 0, $whitecolorindex);
1649        }
1650    }
1651
1652    //try resampling first
1653    if(function_exists("imagecopyresampled")){
1654        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1655            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1656        }
1657    }else{
1658        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1659    }
1660
1661    $okay = false;
1662    if ($ext == 'jpg' || $ext == 'jpeg'){
1663        if(!function_exists('imagejpeg')){
1664            $okay = false;
1665        }else{
1666            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1667        }
1668    }elseif($ext == 'png') {
1669        if(!function_exists('imagepng')){
1670            $okay = false;
1671        }else{
1672            $okay =  imagepng($newimg, $to);
1673        }
1674    }elseif($ext == 'gif') {
1675        if(!function_exists('imagegif')){
1676            $okay = false;
1677        }else{
1678            $okay = imagegif($newimg, $to);
1679        }
1680    }
1681
1682    // destroy GD image ressources
1683    if($image) imagedestroy($image);
1684    if($newimg) imagedestroy($newimg);
1685
1686    return $okay;
1687}
1688
1689/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1690