xref: /dokuwiki/inc/media.php (revision f6d35a79a4686ef537d04abbd1705c410beb53ca)
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");
11require_once(DOKU_INC.'inc/html.php');
12require_once(DOKU_INC.'inc/search.php');
13require_once(DOKU_INC.'inc/JpegMeta.php');
14
15/**
16 * Lists pages which currently use a media file selected for deletion
17 *
18 * References uses the same visual as search results and share
19 * their CSS tags except pagenames won't be links.
20 *
21 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
22 */
23function media_filesinuse($data,$id){
24    global $lang;
25    echo '<h1>'.$lang['reference'].' <code>'.hsc(noNS($id)).'</code></h1>';
26    echo '<p>'.hsc($lang['ref_inuse']).'</p>';
27
28    $hidden=0; //count of hits without read permission
29    foreach($data as $row){
30        if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
31            echo '<div class="search_result">';
32            echo '<span class="mediaref_ref">'.hsc($row).'</span>';
33            echo '</div>';
34        }else
35        $hidden++;
36    }
37    if ($hidden){
38      print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
39    }
40}
41
42/**
43 * Handles the saving of image meta data
44 *
45 * @author Andreas Gohr <andi@splitbrain.org>
46 */
47function media_metasave($id,$auth,$data){
48    if($auth < AUTH_UPLOAD) return false;
49    if(!checkSecurityToken()) return false;
50    global $lang;
51    global $conf;
52    $src = mediaFN($id);
53
54    $meta = new JpegMeta($src);
55    $meta->_parseAll();
56
57    foreach($data as $key => $val){
58        $val=trim($val);
59        if(empty($val)){
60            $meta->deleteField($key);
61        }else{
62            $meta->setField($key,$val);
63        }
64    }
65
66    if($meta->save()){
67        if($conf['fperm']) chmod($src, $conf['fperm']);
68        msg($lang['metasaveok'],1);
69        return $id;
70    }else{
71        msg($lang['metasaveerr'],-1);
72        return false;
73    }
74}
75
76/**
77 * Display the form to edit image meta data
78 *
79 * @author Andreas Gohr <andi@splitbrain.org>
80 */
81function media_metaform($id,$auth){
82    if($auth < AUTH_UPLOAD) return false;
83    global $lang;
84
85    // load the field descriptions
86    static $fields = null;
87    if(is_null($fields)){
88        include(DOKU_CONF.'mediameta.php');
89        if(@file_exists(DOKU_CONF.'mediameta.local.php')){
90            include(DOKU_CONF.'mediameta.local.php');
91        }
92    }
93
94    $src = mediaFN($id);
95
96    // output
97    echo '<h1>'.hsc(noNS($id)).'</h1>'.NL;
98    echo '<form action="'.DOKU_BASE.'lib/exe/mediamanager.php" accept-charset="utf-8" method="post" class="meta">'.NL;
99    formSecurityToken();
100    foreach($fields as $key => $field){
101        // get current value
102        $tags = array($field[0]);
103        if(is_array($field[3])) $tags = array_merge($tags,$field[3]);
104        $value = tpl_img_getTag($tags,'',$src);
105        $value = cleanText($value);
106
107        // prepare attributes
108        $p = array();
109        $p['class'] = 'edit';
110        $p['id']    = 'meta__'.$key;
111        $p['name']  = 'meta['.$field[0].']';
112
113        // put label
114        echo '<div class="metafield">';
115        echo '<label for="meta__'.$key.'">';
116        echo ($lang[$field[1]]) ? $lang[$field[1]] : $field[1];
117        echo ':</label>';
118
119        // put input field
120        if($field[2] == 'text'){
121            $p['value'] = $value;
122            $p['type']  = 'text';
123            $att = buildAttributes($p);
124            echo "<input $att/>".NL;
125        }else{
126            $att = buildAttributes($p);
127            echo "<textarea $att rows=\"6\" cols=\"50\">".formText($value).'</textarea>'.NL;
128        }
129        echo '</div>'.NL;
130    }
131    echo '<div class="buttons">'.NL;
132    echo '<input type="hidden" name="img" value="'.hsc($id).'" />'.NL;
133    echo '<input name="do[save]" type="submit" value="'.$lang['btn_save'].
134         '" title="'.$lang['btn_save'].' [S]" accesskey="s" class="button" />'.NL;
135    echo '<input name="do[cancel]" type="submit" value="'.$lang['btn_cancel'].
136         '" title="'.$lang['btn_cancel'].' [C]" accesskey="c" class="button" />'.NL;
137    echo '</div>'.NL;
138    echo '</form>'.NL;
139}
140
141
142/**
143 * Handles media file deletions
144 *
145 * If configured, checks for media references before deletion
146 *
147 * @author Andreas Gohr <andi@splitbrain.org>
148 * @return mixed false on error, true on delete or array with refs
149 */
150function media_delete($id,$auth){
151    if($auth < AUTH_DELETE) return false;
152    if(!checkSecurityToken()) return false;
153    global $conf;
154    global $lang;
155
156    // check for references if needed
157    $mediareferences = array();
158    if($conf['refcheck']){
159        require_once(DOKU_INC.'inc/fulltext.php');
160        $mediareferences = ft_mediause($id,$conf['refshow']);
161    }
162
163    if(!count($mediareferences)){
164        $file = mediaFN($id);
165
166        // trigger an event - MEDIA_DELETE_FILE
167        $data['name'] = basename($file);
168        $data['path'] = $file;
169        $data['size'] = (@file_exists($file)) ? filesize($file) : 0;
170        $evt = new Doku_Event('MEDIA_DELETE_FILE',$data);
171        if ($evt->advise_before()) {
172            if(@unlink($file)){
173                msg(str_replace('%s',noNS($id),$lang['deletesucc']),1);
174                $del = io_sweepNS($id,'mediadir');
175                if($del){
176                    // current namespace was removed. redirecting to root ns passing msg along
177                    header('Location: '.DOKU_URL.'lib/exe/mediamanager.php?msg1='.
178                            rawurlencode(str_replace('%s',noNS($id),$lang['deletesucc'])));
179                    exit;
180                }
181                return true;
182            }
183        }
184        $evt->advise_after();
185        unset($evt);
186
187        //something went wrong
188        msg(str_replace('%s',$file,$lang['deletefail']),-1);
189        return false;
190    }elseif(!$conf['refshow']){
191        msg(str_replace('%s',noNS($id),$lang['mediainuse']),0);
192        return false;
193    }
194
195    return $mediareferences;
196}
197
198/**
199 * Handles media file uploads
200 *
201 * This generates an action event and delegates to _media_upload_action().
202 * Action plugins are allowed to pre/postprocess the uploaded file.
203 * (The triggered event is preventable.)
204 *
205 * Event data:
206 * $data[0]     fn_tmp: the temporary file name (read from $_FILES)
207 * $data[1]     fn: the file name of the uploaded file
208 * $data[2]     id: the future directory id of the uploaded file
209 * $data[3]     imime: the mimetype of the uploaded file
210 *
211 * @triggers MEDIA_UPLOAD_FINISH
212 * @author Andreas Gohr <andi@splitbrain.org>
213 * @author Michael Klier <chi@chimeric.de>
214 * @return mixed false on error, id of the new file on success
215 */
216function media_upload($ns,$auth){
217    if($auth < AUTH_UPLOAD) return false;
218    if(!checkSecurityToken()) return false;
219    require_once(DOKU_INC.'inc/confutils.php');
220    global $lang;
221    global $conf;
222
223    // get file and id
224    $id   = $_POST['id'];
225    $file = $_FILES['upload'];
226    if(empty($id)) $id = $file['name'];
227
228    // check for data
229    if(!@filesize($file['tmp_name'])){
230        msg('No data uploaded. Disk full?',-1);
231        return false;
232    }
233
234    // check extensions
235    list($fext,$fmime,$dl) = mimetype($file['name']);
236    list($iext,$imime,$dl) = mimetype($id);
237    if($fext && !$iext){
238        // no extension specified in id - read original one
239        $id   .= '.'.$fext;
240        $imime = $fmime;
241    }elseif($fext && $fext != $iext){
242        // extension was changed, print warning
243        msg(sprintf($lang['mediaextchange'],$fext,$iext));
244    }
245
246    // get filename
247    $id   = cleanID($ns.':'.$id,false,true);
248    $fn   = mediaFN($id);
249
250    // get filetype regexp
251    $types = array_keys(getMimeTypes());
252    $types = array_map(create_function('$q','return preg_quote($q,"/");'),$types);
253    $regex = join('|',$types);
254
255    // because a temp file was created already
256    if(preg_match('/\.('.$regex.')$/i',$fn)){
257        //check for overwrite
258        if(@file_exists($fn) && (!$_REQUEST['ow'] || $auth < AUTH_DELETE)){
259            msg($lang['uploadexist'],0);
260            return false;
261        }
262        // check for valid content
263        $ok = media_contentcheck($file['tmp_name'],$imime);
264        if($ok == -1){
265            msg(sprintf($lang['uploadbadcontent'],".$iext"),-1);
266            return false;
267        }elseif($ok == -2){
268            msg($lang['uploadspam'],-1);
269            return false;
270        }elseif($ok == -3){
271            msg($lang['uploadxss'],-1);
272            return false;
273        }
274
275        // prepare event data
276        $data[0] = $file['tmp_name'];
277        $data[1] = $fn;
278        $data[2] = $id;
279        $data[3] = $imime;
280
281        // trigger event
282        return trigger_event('MEDIA_UPLOAD_FINISH', $data, '_media_upload_action', true);
283
284    }else{
285        msg($lang['uploadwrong'],-1);
286    }
287    return false;
288}
289
290/**
291 * Callback adapter for media_upload_finish()
292 * @author Michael Klier <chi@chimeric.de>
293 */
294function _media_upload_action($data) {
295    // fixme do further sanity tests of given data?
296    if(is_array($data) && count($data)===4) {
297        return media_upload_finish($data[0], $data[1], $data[2], $data[3]);
298    } else {
299        return false; //callback error
300    }
301}
302
303/**
304 * Saves an uploaded media file
305 *
306 * @author Andreas Gohr <andi@splitbrain.org>
307 * @author Michael Klier <chi@chimeric.de>
308 */
309function media_upload_finish($fn_tmp, $fn, $id, $imime) {
310    global $conf;
311    global $lang;
312
313    // prepare directory
314    io_createNamespace($id, 'media');
315
316    if(move_uploaded_file($fn_tmp, $fn)) {
317        // Set the correct permission here.
318        // Always chmod media because they may be saved with different permissions than expected from the php umask.
319        // (Should normally chmod to $conf['fperm'] only if $conf['fperm'] is set.)
320        chmod($fn, $conf['fmode']);
321        msg($lang['uploadsucc'],1);
322        media_notify($id,$fn,$imime);
323        return $id;
324    }else{
325        msg($lang['uploadfail'],-1);
326    }
327}
328
329/**
330 * This function checks if the uploaded content is really what the
331 * mimetype says it is. We also do spam checking for text types here.
332 *
333 * We need to do this stuff because we can not rely on the browser
334 * to do this check correctly. Yes, IE is broken as usual.
335 *
336 * @author Andreas Gohr <andi@splitbrain.org>
337 * @link   http://www.splitbrain.org/blog/2007-02/12-internet_explorer_facilitates_cross_site_scripting
338 * @fixme  check all 26 magic IE filetypes here?
339 */
340function media_contentcheck($file,$mime){
341    global $conf;
342    if($conf['iexssprotect']){
343        $fh = @fopen($file, 'rb');
344        if($fh){
345            $bytes = fread($fh, 256);
346            fclose($fh);
347            if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i',$bytes)){
348                return -3;
349            }
350        }
351    }
352    if(substr($mime,0,6) == 'image/'){
353        $info = @getimagesize($file);
354        if($mime == 'image/gif' && $info[2] != 1){
355            return -1;
356        }elseif($mime == 'image/jpeg' && $info[2] != 2){
357            return -1;
358        }elseif($mime == 'image/png' && $info[2] != 3){
359            return -1;
360        }
361        # fixme maybe check other images types as well
362    }elseif(substr($mime,0,5) == 'text/'){
363        global $TEXT;
364        $TEXT = io_readFile($file);
365        if(checkwordblock()){
366            return -2;
367        }
368    }
369    return 0;
370}
371
372/**
373 * Send a notify mail on uploads
374 *
375 * @author Andreas Gohr <andi@splitbrain.org>
376 */
377function media_notify($id,$file,$mime){
378    global $lang;
379    global $conf;
380    if(empty($conf['notify'])) return; //notify enabled?
381
382    $text = rawLocale('uploadmail');
383    $text = str_replace('@DATE@',strftime($conf['dformat']),$text);
384    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
385    $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text);
386    $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text);
387    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
388    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
389    $text = str_replace('@MIME@',$mime,$text);
390    $text = str_replace('@MEDIA@',ml($id,'',true,'&',true),$text);
391    $text = str_replace('@SIZE@',filesize_h(filesize($file)),$text);
392
393    $from = $conf['mailfrom'];
394    $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
395    $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
396    $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
397
398    $subject = '['.$conf['title'].'] '.$lang['mail_upload'].' '.$id;
399
400    mail_send($conf['notify'],$subject,$text,$from);
401}
402
403/**
404 * List all files in a given Media namespace
405 */
406function media_filelist($ns,$auth=null,$jump=''){
407    global $conf;
408    global $lang;
409    $ns = cleanID($ns);
410
411    // check auth our self if not given (needed for ajax calls)
412    if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
413
414    echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
415
416    if($auth < AUTH_READ){
417        // FIXME: print permission warning here instead?
418        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
419        return;
420    }
421
422    media_uploadform($ns, $auth);
423
424    $dir = utf8_encodeFN(str_replace(':','/',$ns));
425    $data = array();
426    search($data,$conf['mediadir'],'search_media',array('showmsg'=>true),$dir);
427
428    if(!count($data)){
429        echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
430        return;
431    }
432
433    foreach($data as $item){
434        media_printfile($item,$auth,$jump);
435    }
436}
437
438/**
439 * Print action links for a file depending on filetype
440 * and available permissions
441 *
442 * @todo contains inline javascript
443 */
444function media_fileactions($item,$auth){
445    global $lang;
446
447    // view button
448    $link = ml($item['id'],'',true);
449    echo ' <a href="'.$link.'" target="_blank"><img src="'.DOKU_BASE.'lib/images/magnifier.png" '.
450         'alt="'.$lang['mediaview'].'" title="'.$lang['mediaview'].'" class="btn" /></a>';
451
452
453    // no further actions if not writable
454    if(!$item['writable']) return;
455
456    // delete button
457    if($auth >= AUTH_DELETE){
458        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?delete='.rawurlencode($item['id']).
459             '&amp;sectok='.getSecurityToken().'" class="btn_media_delete" title="'.$item['id'].'">'.
460             '<img src="'.DOKU_BASE.'lib/images/trash.png" alt="'.$lang['btn_delete'].'" '.
461             'title="'.$lang['btn_delete'].'" class="btn" /></a>';
462    }
463
464    // edit button
465    if($auth >= AUTH_UPLOAD && $item['isimg'] && $item['meta']->getField('File.Mime') == 'image/jpeg'){
466        echo ' <a href="'.DOKU_BASE.'lib/exe/mediamanager.php?edit='.rawurlencode($item['id']).'">'.
467             '<img src="'.DOKU_BASE.'lib/images/pencil.png" alt="'.$lang['metaedit'].'" '.
468             'title="'.$lang['metaedit'].'" class="btn" /></a>';
469    }
470
471}
472
473/**
474 * Formats and prints one file in the list
475 */
476function media_printfile($item,$auth,$jump){
477    global $lang;
478    global $conf;
479
480    // Prepare zebra coloring
481    // I always wanted to use this variable name :-D
482    static $twibble = 1;
483    $twibble *= -1;
484    $zebra = ($twibble == -1) ? 'odd' : 'even';
485
486    // Automatically jump to recent action
487    if($jump == $item['id']) {
488        $jump = ' id="scroll__here" ';
489    }else{
490        $jump = '';
491    }
492
493    // Prepare fileicons
494    list($ext,$mime,$dl) = mimetype($item['file']);
495    $class = preg_replace('/[^_\-a-z0-9]+/i','_',$ext);
496    $class = 'select mediafile mf_'.$class;
497
498    // Prepare filename
499    $file = utf8_decodeFN($item['file']);
500
501    // Prepare info
502    $info = '';
503    if($item['isimg']){
504        $info .= (int) $item['meta']->getField('File.Width');
505        $info .= '&#215;';
506        $info .= (int) $item['meta']->getField('File.Height');
507        $info .= ' ';
508    }
509    $info .= '<i>'.strftime($conf['dformat'],$item['mtime']).'</i>';
510    $info .= ' ';
511    $info .= filesize_h($item['size']);
512
513    // ouput
514    echo '<div class="'.$zebra.'"'.$jump.'>'.NL;
515    echo '<a name="h_'.$item['id'].'" class="'.$class.'">'.$file.'</a> ';
516    echo '<span class="info">('.$info.')</span>'.NL;
517    media_fileactions($item,$auth);
518    echo '<div class="example" id="ex_'.str_replace(':','_',$item['id']).'">';
519    echo $lang['mediausage'].' <code>{{:'.$item['id'].'}}</code>';
520    echo '</div>';
521    if($item['isimg']) media_printimgdetail($item);
522    echo '<div class="clearer"></div>'.NL;
523    echo '</div>'.NL;
524}
525
526/**
527 * Prints a thumbnail and metainfos
528 */
529function media_printimgdetail($item){
530    // prepare thumbnail
531    $w = (int) $item['meta']->getField('File.Width');
532    $h = (int) $item['meta']->getField('File.Height');
533    if($w>120 || $h>120){
534        $ratio = $item['meta']->getResizeRatio(120);
535        $w = floor($w * $ratio);
536        $h = floor($h * $ratio);
537    }
538    $src = ml($item['id'],array('w'=>$w,'h'=>$h));
539    $p = array();
540    $p['width']  = $w;
541    $p['height'] = $h;
542    $p['alt']    = $item['id'];
543    $p['class']  = 'thumb';
544    $att = buildAttributes($p);
545
546    // output
547    echo '<div class="detail">';
548    echo '<div class="thumb">';
549    echo '<a name="d_'.$item['id'].'" class="select">';
550    echo '<img src="'.$src.'" '.$att.' />';
551    echo '</a>';
552    echo '</div>';
553
554    // read EXIF/IPTC data
555    $t = $item['meta']->getField(array('IPTC.Headline','xmp.dc:title'));
556    $d = $item['meta']->getField(array('IPTC.Caption','EXIF.UserComment',
557                                       'EXIF.TIFFImageDescription',
558                                       'EXIF.TIFFUserComment'));
559    if(utf8_strlen($d) > 250) $d = utf8_substr($d,0,250).'...';
560    $k = $item['meta']->getField(array('IPTC.Keywords','IPTC.Category','xmp.dc:subject'));
561
562    // print EXIF/IPTC data
563    if($t || $d || $k ){
564        echo '<p>';
565        if($t) echo '<strong>'.htmlspecialchars($t).'</strong><br />';
566        if($d) echo htmlspecialchars($d).'<br />';
567        if($t) echo '<em>'.htmlspecialchars($k).'</em>';
568        echo '</p>';
569    }
570    echo '</div>';
571}
572
573/**
574 * Print the media upload form if permissions are correct
575 *
576 * @author Andreas Gohr <andi@splitbrain.org>
577 */
578function media_uploadform($ns, $auth){
579    global $lang;
580
581    if($auth < AUTH_UPLOAD) return; //fixme print info on missing permissions?
582
583    // The default HTML upload form
584    $form = new Doku_Form('dw__upload', DOKU_BASE.'lib/exe/mediamanager.php', false, 'multipart/form-data');
585    $form->addElement('<div class="upload">' . $lang['mediaupload'] . '</div>');
586    $form->addElement(formSecurityToken());
587    $form->addHidden('ns', hsc($ns));
588    $form->addElement(form_makeOpenTag('p'));
589    $form->addElement(form_makeFileField('upload', $lang['txt_upload'].':', 'upload__file'));
590    $form->addElement(form_makeCloseTag('p'));
591    $form->addElement(form_makeOpenTag('p'));
592    $form->addElement(form_makeTextField('id', '', $lang['txt_filename'].':', 'upload__name'));
593    $form->addElement(form_makeButton('submit', '', $lang['btn_upload']));
594    $form->addElement(form_makeCloseTag('p'));
595
596    if($auth >= AUTH_DELETE){
597      $form->addElement(form_makeOpenTag('p'));
598      $form->addElement(form_makeCheckboxField('ow', 1, $lang['txt_overwrt'], 'dw__ow', 'check'));
599      $form->addElement(form_makeCloseTag('p'));
600    }
601    html_form('upload', $form);
602
603    // prepare flashvars for multiupload
604    $opt = array(
605        'L_gridname'  => $lang['mu_gridname'] ,
606        'L_gridsize'  => $lang['mu_gridsize'] ,
607        'L_gridstat'  => $lang['mu_gridstat'] ,
608        'L_namespace' => $lang['mu_namespace'] ,
609        'L_overwrite' => $lang['txt_overwrt'],
610        'L_browse'    => $lang['mu_browse'],
611        'L_upload'    => $lang['btn_upload'],
612        'L_toobig'    => $lang['mu_toobig'],
613        'L_ready'     => $lang['mu_ready'],
614        'L_done'      => $lang['mu_done'],
615        'L_fail'      => $lang['mu_fail'],
616        'L_authfail'  => $lang['mu_authfail'],
617        'L_progress'  => $lang['mu_progress'],
618        'L_filetypes' => $lang['mu_filetypes'],
619
620        'O_ns'        => ":$ns",
621        'O_backend'   => 'mediamanager.php?'.session_name().'='.session_id(),
622        'O_size'      => php_to_byte(ini_get('upload_max_filesize')),
623        'O_extensions'=> join('|',array_keys(getMimeTypes())),
624        'O_overwrite' => ($auth >= AUTH_DELETE),
625        'O_sectok'    => getSecurityToken(),
626        'O_authtok'   => auth_createToken(),
627    );
628    $var = buildURLparams($opt);
629    // output the flash uploader
630    ?>
631    <div id="dw__flashupload" style="display:none">
632    <div class="upload"><?php echo $lang['mu_intro']?></div>
633    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"
634        codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
635        <param name="movie" value="multipleUpload.swf?t=<?php echo time()?>" />
636        <param name="quality" value="high" />
637        <param name="bgcolor" value="#ffffff" />
638        <param name="FlashVars" value="<?php echo $var?>" />
639        <embed src="multipleUpload.swf?t=<?php echo time()?>" quality="high" bgcolor="#ffffff"
640            width="100%" height="100%" name="fileUpload" align="middle"
641            play="true" loop="false" quality="high" FlashVars="<?php echo $var?>"
642            allowScriptAccess="sameDomain"
643            type="application/x-shockwave-flash"
644            pluginspage="http://www.macromedia.com/go/getflashplayer">
645        </embed>
646    </object>
647    </div>
648    <?php
649}
650
651/**
652 * Build a tree outline of available media namespaces
653 *
654 * @author Andreas Gohr <andi@splitbrain.org>
655 */
656function media_nstree($ns){
657    global $conf;
658    global $lang;
659
660    // currently selected namespace
661    $ns  = cleanID($ns);
662    if(empty($ns)){
663        $ns = dirname(str_replace(':','/',$ID));
664        if($ns == '.') $ns ='';
665    }
666    $ns  = utf8_encodeFN(str_replace(':','/',$ns));
667
668    $data = array();
669    search($data,$conf['mediadir'],'search_index',array('ns' => $ns, 'nofiles' => true));
670
671    // wrap a list with the root level around the other namespaces
672    $item = array( 'level' => 0, 'id' => '',
673                   'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
674
675    echo '<ul class="idx">';
676    echo media_nstree_li($item);
677    echo media_nstree_item($item);
678    echo html_buildlist($data,'idx','media_nstree_item','media_nstree_li');
679    echo '</li>';
680    echo '</ul>';
681}
682
683/**
684 * Userfunction for html_buildlist
685 *
686 * Prints a media namespace tree item
687 *
688 * @author Andreas Gohr <andi@splitbrain.org>
689 */
690function media_nstree_item($item){
691    $pos   = strrpos($item['id'], ':');
692    $label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
693    if(!$item['label']) $item['label'] = $label;
694
695    $ret  = '';
696    $ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
697    $ret .= $item['label'];
698    $ret .= '</a>';
699    return $ret;
700}
701
702/**
703 * Userfunction for html_buildlist
704 *
705 * Prints a media namespace tree item opener
706 *
707 * @author Andreas Gohr <andi@splitbrain.org>
708 */
709function media_nstree_li($item){
710    $class='media level'.$item['level'];
711    if($item['open']){
712        $class .= ' open';
713        $img   = DOKU_BASE.'lib/images/minus.gif';
714        $alt   = '&minus;';
715    }else{
716        $class .= ' closed';
717        $img   = DOKU_BASE.'lib/images/plus.gif';
718        $alt   = '+';
719    }
720    return '<li class="'.$class.'">'.
721           '<img src="'.$img.'" alt="'.$alt.'" />';
722}
723
724/**
725 * Resizes the given image to the given size
726 *
727 * @author  Andreas Gohr <andi@splitbrain.org>
728 */
729function media_resize_image($file, $ext, $w, $h=0){
730  global $conf;
731
732  $info = @getimagesize($file); //get original size
733  if($info == false) return $file; // that's no image - it's a spaceship!
734
735  if(!$h) $h = round(($w * $info[1]) / $info[0]);
736
737  // we wont scale up to infinity
738  if($w > 2000 || $h > 2000) return $file;
739
740  //cache
741  $local = getCacheName($file,'.media.'.$w.'x'.$h.'.'.$ext);
742  $mtime = @filemtime($local); // 0 if not exists
743
744  if( $mtime > filemtime($file) ||
745      media_resize_imageIM($ext,$file,$info[0],$info[1],$local,$w,$h) ||
746      media_resize_imageGD($ext,$file,$info[0],$info[1],$local,$w,$h) ){
747    if($conf['fperm']) chmod($local, $conf['fperm']);
748    return $local;
749  }
750  //still here? resizing failed
751  return $file;
752}
753
754/**
755 * Crops the given image to the wanted ratio, then calls media_resize_image to scale it
756 * to the wanted size
757 *
758 * Crops are centered horizontally but prefer the upper third of an vertical
759 * image because most pics are more interesting in that area (rule of thirds)
760 *
761 * @author  Andreas Gohr <andi@splitbrain.org>
762 */
763function media_crop_image($file, $ext, $w, $h=0){
764  global $conf;
765
766  if(!$h) $h = $w;
767  $info = @getimagesize($file); //get original size
768  if($info == false) return $file; // that's no image - it's a spaceship!
769
770  // calculate crop size
771  $fr = $info[0]/$info[1];
772  $tr = $w/$h;
773  if($tr >= 1){
774    if($tr > $fr){
775        $cw = $info[0];
776        $ch = (int) $info[0]/$tr;
777    }else{
778        $cw = (int) $info[1]*$tr;
779        $ch = $info[1];
780    }
781  }else{
782    if($tr < $fr){
783        $cw = (int) $info[1]*$tr;
784        $ch = $info[1];
785    }else{
786        $cw = $info[0];
787        $ch = (int) $info[0]/$tr;
788    }
789  }
790  // calculate crop offset
791  $cx = (int) ($info[0]-$cw)/2;
792  $cy = (int) ($info[1]-$ch)/3;
793
794  //cache
795  $local = getCacheName($file,'.media.'.$cw.'x'.$ch.'.crop.'.$ext);
796  $mtime = @filemtime($local); // 0 if not exists
797
798  if( $mtime > filemtime($file) ||
799      media_crop_imageIM($ext,$file,$info[0],$info[1],$local,$cw,$ch,$cx,$cy) ||
800      media_resize_imageGD($ext,$file,$cw,$ch,$local,$cw,$ch,$cx,$cy) ){
801    if($conf['fperm']) chmod($local, $conf['fperm']);
802    return media_resize_image($local,$ext, $w, $h);
803  }
804
805  //still here? cropping failed
806  return media_resize_image($file,$ext, $w, $h);
807}
808
809/**
810 * Download a remote file and return local filename
811 *
812 * returns false if download fails. Uses cached file if available and
813 * wanted
814 *
815 * @author  Andreas Gohr <andi@splitbrain.org>
816 * @author  Pavel Vitis <Pavel.Vitis@seznam.cz>
817 */
818function media_get_from_URL($url,$ext,$cache){
819  global $conf;
820
821  // if no cache or fetchsize just redirect
822  if ($cache==0)           return false;
823  if (!$conf['fetchsize']) return false;
824
825  $local = getCacheName(strtolower($url),".media.$ext");
826  $mtime = @filemtime($local); // 0 if not exists
827
828  //decide if download needed:
829  if( ($mtime == 0) ||                           // cache does not exist
830      ($cache != -1 && $mtime < time()-$cache)   // 'recache' and cache has expired
831    ){
832      if(media_image_download($url,$local)){
833        return $local;
834      }else{
835        return false;
836      }
837  }
838
839  //if cache exists use it else
840  if($mtime) return $local;
841
842  //else return false
843  return false;
844}
845
846/**
847 * Download image files
848 *
849 * @author Andreas Gohr <andi@splitbrain.org>
850 */
851function media_image_download($url,$file){
852  global $conf;
853  $http = new DokuHTTPClient();
854  $http->max_bodysize = $conf['fetchsize'];
855  $http->timeout = 25; //max. 25 sec
856  $http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
857
858  $data = $http->get($url);
859  if(!$data) return false;
860
861  $fileexists = @file_exists($file);
862  $fp = @fopen($file,"w");
863  if(!$fp) return false;
864  fwrite($fp,$data);
865  fclose($fp);
866  if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
867
868  // check if it is really an image
869  $info = @getimagesize($file);
870  if(!$info){
871    @unlink($file);
872    return false;
873  }
874
875  return true;
876}
877
878/**
879 * resize images using external ImageMagick convert program
880 *
881 * @author Pavel Vitis <Pavel.Vitis@seznam.cz>
882 * @author Andreas Gohr <andi@splitbrain.org>
883 */
884function media_resize_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h){
885  global $conf;
886
887  // check if convert is configured
888  if(!$conf['im_convert']) return false;
889
890  // prepare command
891  $cmd  = $conf['im_convert'];
892  $cmd .= ' -resize '.$to_w.'x'.$to_h.'!';
893  if ($ext == 'jpg' || $ext == 'jpeg') {
894      $cmd .= ' -quality '.$conf['jpg_quality'];
895  }
896  $cmd .= " $from $to";
897
898  @exec($cmd,$out,$retval);
899  if ($retval == 0) return true;
900  return false;
901}
902
903/**
904 * crop images using external ImageMagick convert program
905 *
906 * @author Andreas Gohr <andi@splitbrain.org>
907 */
908function media_crop_imageIM($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x,$ofs_y){
909  global $conf;
910
911  // check if convert is configured
912  if(!$conf['im_convert']) return false;
913
914  // prepare command
915  $cmd  = $conf['im_convert'];
916  $cmd .= ' -crop '.$to_w.'x'.$to_h.'+'.$ofs_x.'+'.$ofs_y;
917  if ($ext == 'jpg' || $ext == 'jpeg') {
918      $cmd .= ' -quality '.$conf['jpg_quality'];
919  }
920  $cmd .= " $from $to";
921
922  @exec($cmd,$out,$retval);
923  if ($retval == 0) return true;
924  return false;
925}
926
927/**
928 * resize or crop images using PHP's libGD support
929 *
930 * @author Andreas Gohr <andi@splitbrain.org>
931 * @author Sebastian Wienecke <s_wienecke@web.de>
932 */
933function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=0,$ofs_y=0){
934  global $conf;
935
936  if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
937
938  // check available memory
939  if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
940    return false;
941  }
942
943  // create an image of the given filetype
944  if ($ext == 'jpg' || $ext == 'jpeg'){
945    if(!function_exists("imagecreatefromjpeg")) return false;
946    $image = @imagecreatefromjpeg($from);
947  }elseif($ext == 'png') {
948    if(!function_exists("imagecreatefrompng")) return false;
949    $image = @imagecreatefrompng($from);
950
951  }elseif($ext == 'gif') {
952    if(!function_exists("imagecreatefromgif")) return false;
953    $image = @imagecreatefromgif($from);
954  }
955  if(!$image) return false;
956
957  if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
958    $newimg = @imagecreatetruecolor ($to_w, $to_h);
959  }
960  if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
961  if(!$newimg){
962    imagedestroy($image);
963    return false;
964  }
965
966  //keep png alpha channel if possible
967  if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
968    imagealphablending($newimg, false);
969    imagesavealpha($newimg,true);
970  }
971
972  //keep gif transparent color if possible
973  if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
974    if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
975      $transcolorindex = @imagecolortransparent($image);
976      if($transcolorindex >= 0 ) { //transparent color exists
977        $transcolor = @imagecolorsforindex($image, $transcolorindex);
978        $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']);
979        @imagefill($newimg, 0, 0, $transcolorindex);
980        @imagecolortransparent($newimg, $transcolorindex);
981      }else{ //filling with white
982        $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
983        @imagefill($newimg, 0, 0, $whitecolorindex);
984      }
985    }else{ //filling with white
986      $whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
987      @imagefill($newimg, 0, 0, $whitecolorindex);
988    }
989  }
990
991  //try resampling first
992  if(function_exists("imagecopyresampled")){
993    if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
994      imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
995    }
996  }else{
997    imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
998  }
999
1000  $okay = false;
1001  if ($ext == 'jpg' || $ext == 'jpeg'){
1002    if(!function_exists('imagejpeg')){
1003      $okay = false;
1004    }else{
1005      $okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
1006    }
1007  }elseif($ext == 'png') {
1008    if(!function_exists('imagepng')){
1009      $okay = false;
1010    }else{
1011      $okay =  imagepng($newimg, $to);
1012    }
1013  }elseif($ext == 'gif') {
1014    if(!function_exists('imagegif')){
1015      $okay = false;
1016    }else{
1017      $okay = imagegif($newimg, $to);
1018    }
1019  }
1020
1021  // destroy GD image ressources
1022  if($image) imagedestroy($image);
1023  if($newimg) imagedestroy($newimg);
1024
1025  return $okay;
1026}
1027
1028