xref: /dokuwiki/inc/media.php (revision a2dc299eb0593f35454deb21a2cb5d51a235e80a)
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    if(empty($conf['mailprefix'])) {
496        $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
497    } else {
498        $subject = '['.$conf['mailprefix'].'] '.$lang['mail_upload'].' '.$id;
499    }
500
501    mail_send($conf['notify'],$subject,$text,$conf['mailfrom']);
502}
503
504/**
505 * List all files in a given Media namespace
506 */
507function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false){
508    global $conf;
509    global $lang;
510    $ns = cleanID($ns);
511
512    // check auth our self if not given (needed for ajax calls)
513    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
514
515    if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
516
517    if($auth < AUTH_READ){
518        // FIXME: print permission warning here instead?
519        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
520    }else{
521        if (!$fullscreenview) media_uploadform($ns, $auth);
522
523        $dir = utf8_encodeFN(str_replace(':','/',$ns));
524        $data = array();
525        search($data,$conf['mediadir'],'search_media',
526                array('showmsg'=>true,'depth'=>1),$dir);
527
528        if(!count($data)){
529            echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
530        }else foreach($data as $item){
531            if (!$fullscreenview) media_printfile($item,$auth,$jump);
532            else if ($fullscreenview == 'thumbs') media_printfile_thumbs($item,$auth,$jump);
533        }
534    }
535    if (!$fullscreenview) media_searchform($ns);
536}
537
538/**
539 * Prints tabs for files list actions
540 *
541 * @author Kate Arzamastseva <pshns@ukr.net>
542 * @param string $selected - opened tab
543 */
544function media_tabs_files($selected=false){
545    global $lang;
546
547    echo '<div class="mediamanager-tabs" id="id-mediamanager-tabs">';
548    $tab = '<a href="'.media_managerURL(array('tab_files' => 'files')).
549        '" rel=".mediamanager-tab-files"';
550    if (!empty($selected) && $selected == 'files') $class = 'files selected';
551    else $class = 'files';
552    $tab .= ' class="'.$class.'" >'.$lang['mediaselect'].'</a>';
553    echo $tab;
554
555    $tab = '<a href="'.media_managerURL(array('tab_files' => 'upload')).
556        '" rel=".mediamanager-tab-upload"';
557    if (!empty($selected) && $selected == 'upload') $class = 'upload selected';
558    else $class = 'upload';
559    $tab .= ' class="'.$class.'" >'.$lang['media_uploadtab'].'</a>';
560    echo $tab;
561
562    $tab = '<a href="'.media_managerURL(array('tab_files' => 'search')).
563        '" rel=".mediamanager-tab-search"';
564    if (!empty($selected) && $selected == 'search') $class = 'search selected';
565    else $class = 'search';
566    $tab .= ' class="'.$class.'" >'.$lang['media_searchtab'].'</a>';
567    echo $tab;
568
569    echo '<div class="clearer"></div>';
570    echo '</div>';
571}
572
573/**
574 * Prints tabs for files details actions
575 *
576 * @author Kate Arzamastseva <pshns@ukr.net>
577 * @param string $selected - opened tab
578 */
579function media_tabs_details($selected=false){
580    global $lang;
581
582    echo '<div class="mediamanager-tabs" id="id-mediamanager-tabs-detail">';
583    $tab = '<a href="'.media_managerURL(array('tab_details' => 'view')).
584        '" rel=".mediamanager-tab-view"';
585    if (!empty($selected) && $selected == 'view') $class = 'view selected';
586    else $class = 'view';
587    $tab .= ' class="'.$class.'" >'.$lang['media_viewtab'].'</a>';
588    echo $tab;
589
590    $tab = '<a href="'.media_managerURL(array('tab_details' => 'edit')).
591        '" rel=".mediamanager-tab-edit"';
592    if (!empty($selected) && $selected == 'edit') $class = 'edit selected';
593    else $class = 'edit';
594    $tab .= ' class="'.$class.'" >'.$lang['media_edittab'].'</a>';
595    echo $tab;
596
597    $tab = '<a href="'.media_managerURL(array('tab_details' => 'history')).
598        '" rel=".mediamanager-tab-history"';
599    if (!empty($selected) && $selected == 'history') $class = 'history selected';
600    else $class = 'history';
601    $tab .= ' class="'.$class.'" >'.$lang['media_historytab'].'</a>';
602    echo $tab;
603
604    echo '<div class="clearer"></div>';
605    echo '</div>';
606}
607
608/**
609 * Prints options for the tab that displays a list of all files
610 *
611 * @author Kate Arzamastseva <pshns@ukr.net>
612 */
613function media_tab_files_options(){
614    global $lang;
615
616    echo '<div class="background-container">';
617    echo '<div id="id-mediamanager-tabs-files" style="display: inline;">';
618    echo '<a href="'.media_managerURL(array('view' => 'thumbs')).'"
619        rel=".mediamanager-files-thumbnails-tab" class="mediamanager-link-thumbnails">'.
620        $lang['media_thumbsview'].'</a>';
621    echo '<a href="'.media_managerURL(array('view' => 'list')).'"
622        rel=".mediamanager-files-list-tab" class="mediamanager-link-list"
623        title="View as list">'.$lang['media_listview'].'</a>';
624
625    echo '</div>';
626    echo '<div class="mediamanager-block-sort">'.$lang['media_sort'];
627    //select
628    echo '</div>';
629    echo '<div class="clearer"></div>';
630    echo '</div>';
631}
632
633/**
634 * Prints tab that displays a list of all files
635 *
636 * @author Kate Arzamastseva <pshns@ukr.net>
637 */
638function media_tab_files($ns,$auth=null,$jump='') {
639    global $lang;
640    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
641
642    echo '<div class="mediamanager-tab-files">';
643    media_tab_files_options();
644    echo '<div class="scroll-container">';
645
646    $view = $_REQUEST['view'];
647    if($auth < AUTH_READ){
648        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
649    }else{
650        if ($view == 'list') {
651            echo '<ul class="mediamanager-file-list mediamanager-list" id="id-mediamanager-file-list">';
652        } else {
653            echo '<ul class="mediamanager-file-list mediamanager-thumbs" id="id-mediamanager-file-list">';
654        }
655        media_filelist($ns,$auth,$jump,'thumbs');
656        echo '</ul>';
657    }
658    echo '</div>';
659    echo '</div>';
660}
661
662/**
663 * Prints tab that displays uploading form
664 *
665 * @author Kate Arzamastseva <pshns@ukr.net>
666 */
667function media_tab_upload($ns,$auth=null,$jump='') {
668    global $lang;
669    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
670
671    echo '<div class="mediamanager-tab-upload"">';
672    echo '<div class="background-container">';
673    echo $lang['mediaupload'];
674    echo '</div>';
675
676    echo '<div class="scroll-container">';
677    media_uploadform($ns, $auth, true);
678    echo '</div>';
679    echo '</div>';
680}
681
682/**
683 * Prints tab that displays search form
684 *
685 * @author Kate Arzamastseva <pshns@ukr.net>
686 */
687function media_tab_search($ns,$auth=null) {
688    global $lang;
689
690    $do = $_REQUEST['mediado'];
691    $query = $_REQUEST['q'];
692    if (!$query) $query = '';
693
694    echo '<div class="mediamanager-tab-search">';
695    echo '<div class="background-container">';
696    echo $lang['media_search'];
697    echo'</div>';
698
699    echo '<div class="scroll-container">';
700    media_searchform($ns, $query, true);
701
702    if($do == 'searchlist'){
703        media_searchlist($query,$ns,$auth,true);
704    }
705    echo '</div>';
706    echo '</div>';
707}
708
709/**
710 * Prints tab that displays mediafile details
711 *
712 * @author Kate Arzamastseva <pshns@ukr.net>
713 */
714function media_tab_view($image, $ns, $auth=null) {
715    global $lang, $conf;
716    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
717
718    echo '<div class="mediamanager-tab-detail-view">';
719    echo '<div class="background-container">';
720    echo $image;
721    echo '</div>';
722
723    echo '<div class="scroll-container">';
724    $rev = (int) $_REQUEST['rev'];
725    media_preview($image, $auth, $rev);
726    media_details($image, $auth, $rev);
727    echo '</div>';
728    echo '</div>';
729}
730
731/**
732 * Prints tab that displays form for editing mediafile metadata
733 *
734 * @author Kate Arzamastseva <pshns@ukr.net>
735 */
736function media_tab_edit($image, $ns, $auth=null) {
737    global $lang;
738    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
739
740    echo '<div class="mediamanager-tab-detail-edit">';
741    echo '<div class="background-container">';
742    echo $lang['media_edit'];
743    echo '</div>';
744
745    echo '<div class="scroll-container">';
746    if ($image) {
747        list($ext, $mime) = mimetype($image);
748        if ($mime == 'image/jpeg') media_metaform($image,$auth,true);
749    }
750    echo '</div>';
751    echo '</div>';
752}
753
754/**
755 * Prints tab that displays mediafile revisions
756 *
757 * @author Kate Arzamastseva <pshns@ukr.net>
758 */
759function media_tab_history($image, $ns, $auth=null) {
760    global $lang;
761    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
762    $do = $_REQUEST['mediado'];
763
764    echo '<div class="mediamanager-tab-detail-history">';
765    echo '<div class="background-container">';
766    echo $lang['media_history'];
767    echo '</div>';
768
769    echo '<div class="scroll-container">';
770    if ($auth >= AUTH_READ && $image) {
771        if ($do == 'diff'){
772            media_diff($image, $ns, $auth);
773        } else {
774            $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
775            html_revisions($first, $image);
776        }
777    } else {
778        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
779    }
780    echo '</div>';
781    echo '</div>';
782}
783
784/**
785 * Prints mediafile details
786 *
787 * @author Kate Arzamastseva <pshns@ukr.net>
788 */
789function media_preview($image, $auth, $rev=false) {
790    global $lang;
791    if (!$image) return '';
792    if ($auth < AUTH_READ) {
793        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
794        return '';
795    }
796    $info = getimagesize(mediaFN($image));
797    $w = (int) $info[0];
798
799    $more = '';
800    if ($rev) $more = "rev=$rev";
801    $src = ml($image, $more);
802    echo '<div class="mediamanager-preview">';
803    echo '<img src="'.$src.'" alt="" width="99%" style="max-width: '.$w.'px;" /><br /><br />';
804
805    $link = ml($image,$more,true,'&');
806
807    $form = new Doku_Form(array('action'=>$link, 'target'=>'_blank'));
808    $form->addElement(form_makeButton('submit','',$lang['mediaview']));
809    $form->printForm();
810
811    // delete button
812    if($auth >= AUTH_DELETE && !$rev){
813        $form = new Doku_Form(array('action'=>media_managerURL(array('delete' => $image))));
814        $form->addElement(form_makeButton('submit','',$lang['btn_delete']));
815        $form->printForm();
816
817        $form = new Doku_Form(array('action'=>media_managerURL()));
818        $form->addHidden('mediado','update');
819        $form->addElement(form_makeButton('submit','',$lang['media_update']));
820        $form->printForm();
821    }
822    echo '</div>';
823}
824
825/**
826 * Prints mediafile tags
827 *
828 * @author Kate Arzamastseva <pshns@ukr.net>
829 */
830function media_details($image, $auth, $rev=false) {
831    global $lang, $config_cascade;;
832
833    if (!$image) return '';
834    if ($auth < AUTH_READ) {
835        echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
836        return '';
837    }
838
839    // load the field descriptions
840    static $tags = null;
841    if(is_null($tags)){
842        foreach (array('default','local') as $config_group) {
843            if (empty($config_cascade['mediameta'][$config_group])) continue;
844            foreach ($config_cascade['mediameta'][$config_group] as $config_file) {
845                if(@file_exists($config_file)){
846                    include($config_file);
847                }
848            }
849        }
850    }
851
852    $src = mediaFN($image, $rev);
853    $meta = new JpegMeta($src);
854    echo '<dl class="img_tags">';
855    foreach($tags as $key => $tag){
856        $t = $tag[0];
857        if (!is_array($t)) $t = array($tag[0]);
858        $value = media_getTag($t, $meta, '-');
859        $value = cleanText($value);
860        echo '<dt>'.$lang[$tag[1]].':</dt><dd>';
861        if ($tag[2] == 'text') echo hsc($value);
862        if ($tag[2] == 'date') echo dformat($value);
863        echo '</dd>';
864    }
865    echo '</dl>';
866}
867
868/**
869 * Returns the requested EXIF/IPTC tag from the image meta
870 *
871 * @author Kate Arzamastseva <pshns@ukr.net>
872 * @param array $tags
873 * @param JpegMeta $meta
874 * @param string $alt
875 * @return string
876 */
877function media_getTag($tags,$meta,$alt=''){
878    if($meta === false) return $alt;
879    $info = $meta->getField($tags);
880    if($info == false) return $alt;
881    return $info;
882}
883
884/**
885 * Shows difference between two revisions of file
886 *
887 * @author Kate Arzamastseva <pshns@ukr.net>
888 */
889function media_diff($image, $ns, $auth) {
890    global $lang;
891    global $conf;
892
893    $rev1 = (int) $_REQUEST['rev'];
894
895    if(is_array($_REQUEST['rev2'])){
896        $rev1 = (int) $_REQUEST['rev2'][0];
897        $rev2 = (int) $_REQUEST['rev2'][1];
898
899        if(!$rev1){
900            $rev1 = $rev2;
901            unset($rev2);
902        }
903    }else{
904        $rev2 = (int) $_REQUEST['rev2'];
905    }
906    if($rev1 && $rev2){            // two specific revisions wanted
907        // make sure order is correct (older on the left)
908        if($rev1 < $rev2){
909            $l_rev = $rev1;
910            $r_rev = $rev2;
911        }else{
912            $l_rev = $rev2;
913            $r_rev = $rev1;
914        }
915    }elseif($rev1){                // single revision given, compare to current
916        $r_rev = '';
917        $l_rev = $rev1;
918    }else{                        // no revision was given, compare previous to current
919        $r_rev = '';
920        $revs = getRevisions($image, 0, 1, 8192, true);
921        $l_rev = $revs[0];
922    }
923    echo '<ul class="mediamanager-table-50"><li><div>';
924    media_preview($image, $auth, $l_rev);
925    echo '</div></li>';
926    echo '<li><div>';
927    media_preview($image, $auth, $r_rev);
928    echo '</div></li><li><div>';
929    media_details($image, $auth, $l_rev);
930    echo '</div></li>';
931    echo '<li><div>';
932    media_details($image, $auth, $r_rev);
933    echo '</div></li></ul>';
934}
935
936/**
937 * List all files found by the search request
938 *
939 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
940 * @author Andreas Gohr <gohr@cosmocode.de>
941 * @author Kate Arzamastseva <pshns@ukr.net>
942 * @triggers MEDIA_SEARCH
943 */
944function media_searchlist($query,$ns,$auth=null,$fullscreen=false){
945    global $conf;
946    global $lang;
947
948    $ns = cleanID($ns);
949
950    if ($query) {
951        $evdata = array(
952                'ns'    => $ns,
953                'data'  => array(),
954                'query' => $query
955                );
956        $evt = new Doku_Event('MEDIA_SEARCH', $evdata);
957        if ($evt->advise_before()) {
958            $dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
959            $pattern = '/'.preg_quote($evdata['query'],'/').'/i';
960            search($evdata['data'],
961                    $conf['mediadir'],
962                    'search_media',
963                    array('showmsg'=>false,'pattern'=>$pattern),
964                    $dir);
965        }
966        $evt->advise_after();
967        unset($evt);
968    }
969
970    if (!$fullscreen) {
971        echo '<h1 id="media__ns">'.sprintf($lang['searchmedia_in'],hsc($ns).':*').'</h1>'.NL;
972        media_searchform($ns,$query);
973    }
974
975    if(!count($evdata['data'])){
976        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
977    }else foreach($evdata['data'] as $item){
978        if (!$fullscreen) media_printfile($item,$item['perm'],'',true);
979        else media_printfile_thumbs($item,$item['perm'],'',true);
980    }
981}
982
983/**
984 * Print action links for a file depending on filetype
985 * and available permissions
986 */
987function media_fileactions($item,$auth){
988    global $lang;
989
990    // view button
991    $link = ml($item['id'],'',true);
992    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
993        'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
994
995    // no further actions if not writable
996    if(!$item['writable']) return;
997
998    // delete button
999    if($auth >= AUTH_DELETE){
1000        $link = DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
1001            '&amp;sectok='.getSecurityToken();
1002        echo ' <a href="'.$link.'" class="btn_media_delete" title="'.$item['id'].'">'.
1003            '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
1004            'title="'.$lang['btn_delete'].'" class="btn" /></a>';
1005    }
1006
1007    // edit button
1008    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
1009        $link = DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']);
1010        echo ' <a href="'.$link.'">'.
1011            '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
1012            'title="'.$lang['metaedit'].'" class="btn" /></a>';
1013    }
1014
1015}
1016
1017/**
1018 * Formats and prints one file in the list
1019 */
1020function media_printfile($item,$auth,$jump,$display_namespace=false){
1021    global $lang;
1022    global $conf;
1023
1024    // Prepare zebra coloring
1025    // I always wanted to use this variable name :-D
1026    static $twibble = 1;
1027    $twibble *= -1;
1028    $zebra = ($twibble == -1) ? 'odd' : 'even';
1029
1030    // Automatically jump to recent action
1031    if($jump == $item['id']) {
1032        $jump = ' id="scroll__here" ';
1033    }else{
1034        $jump = '';
1035    }
1036
1037    // Prepare fileicons
1038    list($ext,$mime,$dl) = mimetype($item['file'],false);
1039    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
1040    $class = 'select mediafile mf_'.$class;
1041
1042    // Prepare filename
1043    $file = utf8_decodeFN($item['file']);
1044
1045    // Prepare info
1046    $info = '';
1047    if($item['isimg']){
1048        $info .= (int) $item['meta']->getField('File.Width');
1049        $info .= '&#215;';
1050        $info .= (int) $item['meta']->getField('File.Height');
1051        $info .= ' ';
1052    }
1053    $info .= '<i>'.dformat($item['mtime']).'</i>';
1054    $info .= ' ';
1055    $info .= filesize_h($item['size']);
1056
1057    // output
1058    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
1059    if (!$display_namespace) {
1060        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($file).'</a> ';
1061    } else {
1062        echo '<a name="h_:'.$item['id'].'" class="'.$class.'">'.hsc($item['id']).'</a><br/>';
1063    }
1064    echo '<span class="info">('.$info.')</span>'.NL;
1065    media_fileactions($item,$auth);
1066    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
1067    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
1068    echo '</div>';
1069    if($item['isimg']) media_printimgdetail($item);
1070    echo '<div class="clearer"></div>'.NL;
1071    echo '</div>'.NL;
1072}
1073
1074/**
1075 * Formats and prints one file in the list in the thumbnails view
1076 *
1077 * @author Kate Arzamastseva <pshns@ukr.net>
1078 */
1079function media_printfile_thumbs($item,$auth,$jump){
1080    global $lang;
1081    global $conf;
1082
1083    // Prepare filename
1084    $file = utf8_decodeFN($item['file']);
1085
1086    // output
1087    echo '<li><div>';
1088    if($item['isimg']) {
1089        media_printimgdetail($item, true);
1090    } else {
1091        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1092            media_managerURL(array('image' => hsc($item['id']))).'">';
1093        echo '<img src="'.DOKU_BASE.'lib/images/icon-file.png" width="90px" />';
1094        echo '</a>';
1095    }
1096    echo '<a href="'.media_managerURL(array('image' => hsc($item['id']))).'" name=
1097        "h_:'.$item['id'].'" class="info" >'.hsc($file).'</a>';
1098    if($item['isimg']){
1099        $info = '';
1100        $info .= (int) $item['meta']->getField('File.Width');
1101        $info .= '&#215;';
1102        $info .= (int) $item['meta']->getField('File.Height');
1103        echo '<span class="info">'.$info.'</span>';
1104    } else {
1105        echo '<span class="info">&nbsp;</span>';
1106    }
1107    $info = '<i>'.dformat($item['mtime']).'</i>';
1108    echo '<span class="info">'.$info.'</span>';
1109    $info = filesize_h($item['size']);
1110    echo '<span class="info">'.$info.'</span>';
1111    echo '<div class="clearer"></div>';
1112    echo '</div></li>'.NL;
1113}
1114
1115/**
1116 * Prints a thumbnail and metainfos
1117 */
1118function media_printimgdetail($item, $fullscreen=false){
1119    // prepare thumbnail
1120    if (!$fullscreen) $size = 120;
1121    else $size = 90;
1122    $w = (int) $item['meta']->getField('File.Width');
1123    $h = (int) $item['meta']->getField('File.Height');
1124    if($w>$size || $h>$size){
1125        if (!$fullscreen) {
1126            $ratio = $item['meta']->getResizeRatio($size);
1127        } else {
1128            $ratio = $item['meta']->getResizeRatio($size,$size);
1129        }
1130        $w = floor($w * $ratio);
1131        $h = floor($h * $ratio);
1132    }
1133    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
1134    $p = array();
1135    $p['width']  = $w;
1136    if (!$fullscreen) $p['height'] = $h;
1137    $p['alt']    = $item['id'];
1138    $p['class']  = 'thumb';
1139    $att = buildAttributes($p);
1140
1141    // output
1142    if ($fullscreen) {
1143        echo '<a name="d_:'.$item['id'].'" class="image" title="'.$item['id'].'" href="'.
1144            media_managerURL(array('image' => hsc($item['id']))).'">';
1145        echo '<img src="'.$src.'" '.$att.' />';
1146        echo '</a>';
1147        return 1;
1148    }
1149
1150    echo '<div class="detail">';
1151    echo '<div class="thumb">';
1152    echo '<a name="d_:'.$item['id'].'" class="select">';
1153    echo '<img src="'.$src.'" '.$att.' />';
1154    echo '</a>';
1155    echo '</div>';
1156
1157    // read EXIF/IPTC data
1158    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
1159    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
1160                'EXIF.TIFFImageDescription',
1161                'EXIF.TIFFUserComment'));
1162    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
1163    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
1164
1165    // print EXIF/IPTC data
1166    if($t || $d || $k ){
1167        echo '<p>';
1168        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
1169        if($d) echo htmlspecialchars($d).'<br />';
1170        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
1171        echo '</p>';
1172    }
1173    echo '</div>';
1174}
1175
1176/**
1177 * Build link based on the current, adding/rewriting
1178 * parameters
1179 *
1180 * @author Kate Arzamastseva <pshns@ukr.net>
1181 * @param array $params
1182 * @param string $amp - separator
1183 * @return string - link
1184 */
1185function media_managerURL($params=false, $amp='&') {
1186    global $conf;
1187    global $ID;
1188
1189    $url = $_SERVER['REQUEST_URI'];
1190
1191    $urlArray = explode('?', $url, 2);
1192    $gets = @$urlArray[1];
1193    parse_str($gets, $gets);
1194
1195    if ($gets['edit']) $gets['image'] = $gets['edit'];
1196    unset($gets['edit']);
1197    unset($gets['sectok']);
1198    unset($gets['delete']);
1199    unset($gets['rev']);
1200    unset($gets['mediado']);
1201
1202    if ($params) {
1203        foreach ($params as $k => $v) {
1204            $gets[$k] = $v;
1205        }
1206    }
1207    unset($gets['id']);
1208    if ($gets['delete']) {
1209        unset($gets['image']);
1210        unset($gets['tab_details']);
1211    }
1212
1213    return wl($ID,$gets,false,$amp);
1214}
1215
1216/**
1217 * Print the media upload form if permissions are correct
1218 *
1219 * @author Andreas Gohr <andi@splitbrain.org>
1220 * @author Kate Arzamastseva <pshns@ukr.net>
1221 */
1222function media_uploadform($ns, $auth, $fullscreen = false){
1223    global $lang;
1224
1225    if($auth < AUTH_UPLOAD) {
1226        echo '<div class="nothing">'.$lang['media_perm_upload'].'</div>'.NL;
1227        return;
1228    }
1229
1230    $update = false;
1231    $id = '';
1232    if ($auth >= AUTH_DELETE && $fullscreen && $_REQUEST['mediado'] == 'update') {
1233        $update = true;
1234        $id = cleanID($_REQUEST['image']);
1235    }
1236
1237    // The default HTML upload form
1238    $params = array('id'      => 'dw__upload',
1239                    'enctype' => 'multipart/form-data');
1240    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1241    else $params['action'] = media_managerURL(array('tab_files' => 'files'));
1242
1243    $form = new Doku_Form($params);
1244    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
1245    $form->addElement(formSecurityToken());
1246    $form->addHidden('ns', hsc($ns));
1247    $form->addElement(form_makeOpenTag('p'));
1248    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
1249    $form->addElement(form_makeCloseTag('p'));
1250    $form->addElement(form_makeOpenTag('p'));
1251    $form->addElement(form_makeTextField('id', $id, $lang['txt_filename'].':', 'upload__name'));
1252    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
1253    $form->addElement(form_makeCloseTag('p'));
1254
1255    if($auth >= AUTH_DELETE){
1256        $form->addElement(form_makeOpenTag('p'));
1257        $attrs = array();
1258        if ($update) $attrs['checked'] = 'checked';
1259        $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check', $attrs));
1260        $form->addElement(form_makeCloseTag('p'));
1261    }
1262    html_form('upload', $form);
1263
1264    // prepare flashvars for multiupload
1265    $opt = array(
1266            'L_gridname'  => $lang['mu_gridname'] ,
1267            'L_gridsize'  => $lang['mu_gridsize'] ,
1268            'L_gridstat'  => $lang['mu_gridstat'] ,
1269            'L_namespace' => $lang['mu_namespace'] ,
1270            'L_overwrite' => $lang['txt_overwrt'],
1271            'L_browse'    => $lang['mu_browse'],
1272            'L_upload'    => $lang['btn_upload'],
1273            'L_toobig'    => $lang['mu_toobig'],
1274            'L_ready'     => $lang['mu_ready'],
1275            'L_done'      => $lang['mu_done'],
1276            'L_fail'      => $lang['mu_fail'],
1277            'L_authfail'  => $lang['mu_authfail'],
1278            'L_progress'  => $lang['mu_progress'],
1279            'L_filetypes' => $lang['mu_filetypes'],
1280            'L_info'      => $lang['mu_info'],
1281            'L_lasterr'   => $lang['mu_lasterr'],
1282
1283            'O_ns'        => ":$ns",
1284            'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
1285            'O_maxsize'   => php_to_byte(ini_get('upload_max_filesize')),
1286            'O_extensions'=> join('|',array_keys(getMimeTypes())),
1287            'O_overwrite' => ($auth >= AUTH_DELETE),
1288            'O_sectok'    => getSecurityToken(),
1289            'O_authtok'   => auth_createToken(),
1290            );
1291    $var = buildURLparams($opt);
1292    // output the flash uploader
1293    ?>
1294        <div id="dw__flashupload" style="display:none">
1295        <div class="upload"><?php echo $lang['mu_intro']?></div>
1296        <?php echo html_flashobject('multipleUpload.swf','500','190',null,$opt); ?>
1297        </div>
1298        <?php
1299}
1300
1301/**
1302 * Print the search field form
1303 *
1304 * @author Tobias Sarnowski <sarnowski@cosmocode.de>
1305 * @author Kate Arzamastseva <pshns@ukr.net>
1306 */
1307function media_searchform($ns,$query='',$fullscreen=false){
1308    global $lang;
1309
1310    // The default HTML search form
1311    $params = array('id' => 'dw__mediasearch');
1312    if (!$fullscreen) $params['action'] = DOKU_BASE.'lib/exe/mediamanager.php';
1313    else $params['action'] = media_managerURL();
1314    $form = new Doku_Form($params);
1315    if (!$fullscreen) $form->addElement('<div class="upload">' . $lang['mediasearch'] . '</div>');
1316    $form->addElement(formSecurityToken());
1317    $form->addHidden('ns', $ns);
1318    if (!$fullscreen) $form->addHidden('do', 'searchlist');
1319    else $form->addHidden('mediado', 'searchlist');
1320    $form->addElement(form_makeOpenTag('p'));
1321    $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*'))));
1322    $form->addElement(form_makeButton('submit', '', $lang['btn_search']));
1323    $form->addElement(form_makeCloseTag('p'));
1324    html_form('searchmedia', $form);
1325}
1326
1327/**
1328 * Build a tree outline of available media namespaces
1329 *
1330 * @author Andreas Gohr <andi@splitbrain.org>
1331 */
1332function media_nstree($ns){
1333    global $conf;
1334    global $lang;
1335
1336    // currently selected namespace
1337    $ns  = cleanID($ns);
1338    if(empty($ns)){
1339        global $ID;
1340        $ns = dirname(str_replace(':','/',$ID));
1341        if($ns == '.') $ns ='';
1342    }
1343    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1344
1345    $data = array();
1346    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
1347
1348    // wrap a list with the root level around the other namespaces
1349    $item = array( 'level' => 0, 'id' => '',
1350            'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
1351
1352    echo '<ul class="idx">';
1353    echo media_nstree_li($item);
1354    echo media_nstree_item($item);
1355    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
1356    echo '</li>';
1357    echo '</ul>';
1358}
1359
1360/**
1361 * Userfunction for html_buildlist
1362 *
1363 * Prints a media namespace tree item
1364 *
1365 * @author Andreas Gohr <andi@splitbrain.org>
1366 */
1367function media_nstree_item($item){
1368    $pos   = strrpos($item['id'], ':');
1369    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
1370    if(!$item['label']) $item['label'] = $label;
1371
1372    $ret  = '';
1373    if (!($_REQUEST['do'] == 'media'))
1374    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
1375    else $ret .= '<a href="'.media_managerURL(array('ns' => idfilter($item['id']))).'" class="idx_dir">';
1376    $ret .= $item['label'];
1377    $ret .= '</a>';
1378    return $ret;
1379}
1380
1381/**
1382 * Userfunction for html_buildlist
1383 *
1384 * Prints a media namespace tree item opener
1385 *
1386 * @author Andreas Gohr <andi@splitbrain.org>
1387 */
1388function media_nstree_li($item){
1389    $class='media level'.$item['level'];
1390    if($item['open']){
1391        $class .= ' open';
1392        $img   = DOKU_BASE.'lib/images/minus.gif';
1393        $alt   = '&minus;';
1394    }else{
1395        $class .= ' closed';
1396        $img   = DOKU_BASE.'lib/images/plus.gif';
1397        $alt   = '+';
1398    }
1399    // TODO: only deliver an image if it actually has a subtree...
1400    return '<li class="'.$class.'">'.
1401        '<img src="'.$img.'" alt="'.$alt.'" />';
1402}
1403
1404/**
1405 * Resizes the given image to the given size
1406 *
1407 * @author  Andreas Gohr <andi@splitbrain.org>
1408 */
1409function media_resize_image($file, $ext, $w, $h=0){
1410    global $conf;
1411
1412    $info = @getimagesize($file); //get original size
1413    if($info == false) return $file; // that's no image - it's a spaceship!
1414
1415    if(!$h) $h = round(($w * $info[1]) / $info[0]);
1416
1417    // we wont scale up to infinity
1418    if($w > 2000 || $h > 2000) return $file;
1419
1420    //cache
1421    $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
1422    $mtime = @filemtime($local); // 0 if not exists
1423
1424    if( $mtime > filemtime($file) ||
1425            media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
1426            media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
1427        if($conf['fperm']) chmod($local, $conf['fperm']);
1428        return $local;
1429    }
1430    //still here? resizing failed
1431    return $file;
1432}
1433
1434/**
1435 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
1436 * to the wanted size
1437 *
1438 * Crops are centered horizontally but prefer the upper third of an vertical
1439 * image because most pics are more interesting in that area (rule of thirds)
1440 *
1441 * @author  Andreas Gohr <andi@splitbrain.org>
1442 */
1443function media_crop_image($file, $ext, $w, $h=0){
1444    global $conf;
1445
1446    if(!$h) $h = $w;
1447    $info = @getimagesize($file); //get original size
1448    if($info == false) return $file; // that's no image - it's a spaceship!
1449
1450    // calculate crop size
1451    $fr = $info[0]/$info[1];
1452    $tr = $w/$h;
1453    if($tr >= 1){
1454        if($tr > $fr){
1455            $cw = $info[0];
1456            $ch = (int) $info[0]/$tr;
1457        }else{
1458            $cw = (int) $info[1]*$tr;
1459            $ch = $info[1];
1460        }
1461    }else{
1462        if($tr < $fr){
1463            $cw = (int) $info[1]*$tr;
1464            $ch = $info[1];
1465        }else{
1466            $cw = $info[0];
1467            $ch = (int) $info[0]/$tr;
1468        }
1469    }
1470    // calculate crop offset
1471    $cx = (int) ($info[0]-$cw)/2;
1472    $cy = (int) ($info[1]-$ch)/3;
1473
1474    //cache
1475    $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
1476    $mtime = @filemtime($local); // 0 if not exists
1477
1478    if( $mtime > filemtime($file) ||
1479            media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
1480            media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
1481        if($conf['fperm']) chmod($local, $conf['fperm']);
1482        return media_resize_image($local,$ext, $w, $h);
1483    }
1484
1485    //still here? cropping failed
1486    return media_resize_image($file,$ext, $w, $h);
1487}
1488
1489/**
1490 * Download a remote file and return local filename
1491 *
1492 * returns false if download fails. Uses cached file if available and
1493 * wanted
1494 *
1495 * @author  Andreas Gohr <andi@splitbrain.org>
1496 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
1497 */
1498function media_get_from_URL($url,$ext,$cache){
1499    global $conf;
1500
1501    // if no cache or fetchsize just redirect
1502    if ($cache==0)           return false;
1503    if (!$conf['fetchsize']) return false;
1504
1505    $local = getCacheName(strtolower($url),".media.$ext");
1506    $mtime = @filemtime($local); // 0 if not exists
1507
1508    //decide if download needed:
1509    if( ($mtime == 0) ||                           // cache does not exist
1510            ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
1511      ){
1512        if(media_image_download($url,$local)){
1513            return $local;
1514        }else{
1515            return false;
1516        }
1517    }
1518
1519    //if cache exists use it else
1520    if($mtime) return $local;
1521
1522    //else return false
1523    return false;
1524}
1525
1526/**
1527 * Download image files
1528 *
1529 * @author Andreas Gohr <andi@splitbrain.org>
1530 */
1531function media_image_download($url,$file){
1532    global $conf;
1533    $http = new DokuHTTPClient();
1534    $http->max_bodysize = $conf['fetchsize'];
1535    $http->timeout = 25; //max. 25 sec
1536    $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
1537
1538    $data = $http->get($url);
1539    if(!$data) return false;
1540
1541    $fileexists = @file_exists($file);
1542    $fp = @fopen($file,"w");
1543    if(!$fp) return false;
1544    fwrite($fp,$data);
1545    fclose($fp);
1546    if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
1547
1548    // check if it is really an image
1549    $info = @getimagesize($file);
1550    if(!$info){
1551        @unlink($file);
1552        return false;
1553    }
1554
1555    return true;
1556}
1557
1558/**
1559 * resize images using external ImageMagick convert program
1560 *
1561 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
1562 * @author Andreas Gohr <andi@splitbrain.org>
1563 */
1564function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
1565    global $conf;
1566
1567    // check if convert is configured
1568    if(!$conf['im_convert']) return false;
1569
1570    // prepare command
1571    $cmd  = $conf['im_convert'];
1572    $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
1573    if ($ext == 'jpg' || $ext == 'jpeg') {
1574        $cmd .= ' -quality '.$conf['jpg_quality'];
1575    }
1576    $cmd .= " $from $to";
1577
1578    @exec($cmd,$out,$retval);
1579    if ($retval == 0) return true;
1580    return false;
1581}
1582
1583/**
1584 * crop images using external ImageMagick convert program
1585 *
1586 * @author Andreas Gohr <andi@splitbrain.org>
1587 */
1588function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
1589    global $conf;
1590
1591    // check if convert is configured
1592    if(!$conf['im_convert']) return false;
1593
1594    // prepare command
1595    $cmd  = $conf['im_convert'];
1596    $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
1597    if ($ext == 'jpg' || $ext == 'jpeg') {
1598        $cmd .= ' -quality '.$conf['jpg_quality'];
1599    }
1600    $cmd .= " $from $to";
1601
1602    @exec($cmd,$out,$retval);
1603    if ($retval == 0) return true;
1604    return false;
1605}
1606
1607/**
1608 * resize or crop images using PHP's libGD support
1609 *
1610 * @author Andreas Gohr <andi@splitbrain.org>
1611 * @author Sebastian Wienecke <s_wienecke@web.de>
1612 */
1613function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
1614    global $conf;
1615
1616    if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
1617
1618    // check available memory
1619    if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
1620        return false;
1621    }
1622
1623    // create an image of the given filetype
1624    if ($ext == 'jpg' || $ext == 'jpeg'){
1625        if(!function_exists("imagecreatefromjpeg")) return false;
1626        $image = @imagecreatefromjpeg($from);
1627    }elseif($ext == 'png') {
1628        if(!function_exists("imagecreatefrompng")) return false;
1629        $image = @imagecreatefrompng($from);
1630
1631    }elseif($ext == 'gif') {
1632        if(!function_exists("imagecreatefromgif")) return false;
1633        $image = @imagecreatefromgif($from);
1634    }
1635    if(!$image) return false;
1636
1637    if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
1638        $newimg = @imagecreatetruecolor ($to_w, $to_h);
1639    }
1640    if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
1641    if(!$newimg){
1642        imagedestroy($image);
1643        return false;
1644    }
1645
1646    //keep png alpha channel if possible
1647    if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
1648        imagealphablending($newimg, false);
1649        imagesavealpha($newimg,true);
1650    }
1651
1652    //keep gif transparent color if possible
1653    if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
1654        if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
1655            $transcolorindex = @imagecolortransparent($image);
1656            if($transcolorindex >= 0 ) { //transparent color exists
1657                $transcolor = @imagecolorsforindex($image, $transcolorindex);
1658                $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
1659                @imagefill($newimg, 0, 0, $transcolorindex);
1660                @imagecolortransparent($newimg, $transcolorindex);
1661            }else{ //filling with white
1662                $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1663                @imagefill($newimg, 0, 0, $whitecolorindex);
1664            }
1665        }else{ //filling with white
1666            $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
1667            @imagefill($newimg, 0, 0, $whitecolorindex);
1668        }
1669    }
1670
1671    //try resampling first
1672    if(function_exists("imagecopyresampled")){
1673        if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
1674            imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1675        }
1676    }else{
1677        imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
1678    }
1679
1680    $okay = false;
1681    if ($ext == 'jpg' || $ext == 'jpeg'){
1682        if(!function_exists('imagejpeg')){
1683            $okay = false;
1684        }else{
1685            $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1686        }
1687    }elseif($ext == 'png') {
1688        if(!function_exists('imagepng')){
1689            $okay = false;
1690        }else{
1691            $okay =  imagepng($newimg, $to);
1692        }
1693    }elseif($ext == 'gif') {
1694        if(!function_exists('imagegif')){
1695            $okay = false;
1696        }else{
1697            $okay = imagegif($newimg, $to);
1698        }
1699    }
1700
1701    // destroy GD image ressources
1702    if($image) imagedestroy($image);
1703    if($newimg) imagedestroy($newimg);
1704
1705    return $okay;
1706}
1707
1708/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
1709