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