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