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