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