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