Dotclear

source: inc/core/class.dc.media.php @ 407:eb5bd0f66932

Revision 407:eb5bd0f66932, 28.1 KB checked in by Dsls <dsls@…>, 14 years ago (diff)
  • Re-enabled blank post_type required by media.php in class dcBlog
  • Attachments are now handled by a plugins/attachments/_admin.php
  • Added core dcPostMedia multi-purpose class, and 'link_type' in post_media table
  • Added new behavior : tplIfConditions, to enable to add new attributes to tpl:XXXIf tags
  • Moved tpl:SysIf has_tag attribute to Tags plugin
Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_RC_PATH')) { return; }
13
14/**
15@ingroup DC_CORE
16@brief Dotclear media manage
17
18This class handles Dotclear media items.
19*/
20class dcMedia extends filemanager
21{
22     protected $core;         ///< <b>dcCore</b> dcCore instance
23     protected $con;          ///< <b>connection</b> Database connection
24     protected $table;        ///< <b>string</b> Media table name
25     protected $type;         ///< <b>string</b> Media type filter
26     protected $postmedia;
27     protected $file_sort = 'name-asc';
28     
29     protected $file_handler = array(); ///< <b>array</b> Array of callbacks
30     
31     public $thumb_tp = '%s/.%s_%s.jpg';     ///< <b>string</b> Thumbnail file pattern
32     
33     /**
34     <b>array</b> Tubmnail sizes:
35     - m: medium image
36     - s: small image
37     - t: thumbnail image
38     - sq: square image
39     */
40     public $thumb_sizes = array( 
41          'm' => array(448,'ratio','medium'),
42          's' => array(240,'ratio','small'),
43          't' => array(100,'ratio','thumbnail'),
44          'sq' => array(48,'crop','square')
45     );
46     
47     public $icon_img = 'images/media/%s.png';    ///< <b>string</b> Icon file pattern
48     
49     /**
50     Object constructor.
51     
52     @param    core      <b>dcCore</b>       dcCore instance
53     @param    type      <b>string</b>       Media type filter
54     */
55     public function __construct($core,$type='')
56     {
57          $this->core =& $core;
58          $this->con =& $core->con;
59          $this->postmedia = new dcPostMedia($core);
60         
61          if ($this->core->blog == null) {
62               throw new Exception(__('No blog defined.'));
63          }
64         
65          $this->table = $this->core->prefix.'media';
66          $root = $this->core->blog->public_path;
67         
68          if (preg_match('#^http(s)?://#',$this->core->blog->settings->system->public_url)) {
69               $root_url = rawurldecode($this->core->blog->settings->system->public_url);
70          } else {
71               $root_url = rawurldecode($this->core->blog->host.path::clean($this->core->blog->settings->system->public_url));
72          }
73         
74          if (!is_dir($root)) {
75               throw new Exception(sprintf(__('Directory %s does not exist.'),$root));
76          }
77         
78          $this->type = $type;
79         
80          parent::__construct($root,$root_url);
81          $this->chdir('');
82         
83          $this->path = $this->core->blog->settings->system->public_path;
84         
85          $this->addExclusion(DC_RC_PATH);
86          $this->addExclusion(dirname(__FILE__).'/../');
87         
88          $this->exclude_pattern = $core->blog->settings->system->media_exclusion;
89         
90          # Event handlers
91          $this->addFileHandler('image/jpeg','create',array($this,'imageThumbCreate'));
92          $this->addFileHandler('image/png','create',array($this,'imageThumbCreate'));
93          $this->addFileHandler('image/gif','create',array($this,'imageThumbCreate'));
94         
95          $this->addFileHandler('image/png','update',array($this,'imageThumbUpdate'));
96          $this->addFileHandler('image/jpeg','update',array($this,'imageThumbUpdate'));
97          $this->addFileHandler('image/gif','update',array($this,'imageThumbUpdate'));
98         
99          $this->addFileHandler('image/png','remove',array($this,'imageThumbRemove'));
100          $this->addFileHandler('image/jpeg','remove',array($this,'imageThumbRemove'));
101          $this->addFileHandler('image/gif','remove',array($this,'imageThumbRemove'));
102         
103          $this->addFileHandler('image/jpeg','create',array($this,'imageMetaCreate'));
104         
105          $this->addFileHandler('image/jpeg','recreate',array($this,'imageThumbCreate'));
106          $this->addFileHandler('image/png','recreate',array($this,'imageThumbCreate'));
107          $this->addFileHandler('image/gif','recreate',array($this,'imageThumbCreate'));
108         
109          $this->addFileHandler('image/jpeg','recreate',array($this,'imageThumbCreate'));
110          $this->addFileHandler('image/png','recreate',array($this,'imageThumbCreate'));
111          $this->addFileHandler('image/gif','recreate',array($this,'imageThumbCreate'));
112         
113          # Thumbnails sizes
114          $this->thumb_sizes['m'][0] = abs($core->blog->settings->system->media_img_m_size);
115          $this->thumb_sizes['s'][0] = abs($core->blog->settings->system->media_img_s_size);
116          $this->thumb_sizes['t'][0] = abs($core->blog->settings->system->media_img_t_size);
117         
118          # Thumbnails sizes names
119          $this->thumb_sizes['m'][2] = __($this->thumb_sizes['m'][2]);
120          $this->thumb_sizes['s'][2] = __($this->thumb_sizes['s'][2]);
121          $this->thumb_sizes['t'][2] = __($this->thumb_sizes['t'][2]);
122          $this->thumb_sizes['sq'][2] = __($this->thumb_sizes['sq'][2]);
123         
124          # --BEHAVIOR-- coreMediaConstruct
125          $this->core->callBehavior('coreMediaConstruct',$this); 
126     }
127     
128     /**
129     Changes working directory.
130     
131     @param    dir       <b>string</b>       Directory name.
132     */
133     public function chdir($dir)
134     {
135          parent::chdir($dir);
136          $this->relpwd = preg_replace('/^'.preg_quote($this->root,'/').'\/?/','',$this->pwd);
137     }
138     
139     /**
140     Adds a new file handler for a given media type and event.
141     
142     Available events are:
143     - create: file creation
144     - update: file update
145     - remove: file deletion
146     
147     @param    type      <b>string</b>       Media type
148     @param    event     <b>string</b>       Event
149     @param    function  <b>callback</b>
150     */
151     public function addFileHandler($type,$event,$function)
152     {
153          if (is_callable($function)) {
154               $this->file_handler[$type][$event][] = $function;
155          }
156     }
157     
158     protected function callFileHandler($type,$event)
159     {
160          if (!empty($this->file_handler[$type][$event]))
161          {
162               $args = func_get_args();
163               array_shift($args);
164               array_shift($args);
165               
166               foreach ($this->file_handler[$type][$event] as $f)
167               {
168                    call_user_func_array($f,$args);
169               }
170          }
171     }
172     
173     /**
174     Returns HTML breadCrumb for media manager navigation.
175     
176     @param    href      <b>string</b>       URL pattern
177     @return   <b>string</b> HTML code
178     */
179     public function breadCrumb($href)
180     {
181          $res = '';
182          if ($this->relpwd && $this->relpwd != '.') {
183               $pwd = '';
184               foreach (explode('/',$this->relpwd) as $v) {
185                    $pwd .= rawurlencode($v).'/';
186                    $res .= '<a href="'.sprintf($href,$pwd).'">'.$v.'</a> / ';
187               }
188          }
189          return $res;
190         
191     }
192     
193     protected function fileRecord($rs)
194     {
195          if ($rs->isEmpty()) { return null; }
196         
197          if (!$this->isFileExclude($this->root.'/'.$rs->media_file) && is_file($this->root.'/'.$rs->media_file))
198          {
199               $f = new fileItem($this->root.'/'.$rs->media_file,$this->root,$this->root_url);
200               
201               if ($this->type && $f->type_prefix != $this->type) {
202                    return null;
203               }
204               
205               $meta = @simplexml_load_string($rs->media_meta);
206               
207               $f->editable = true;
208               $f->media_id = $rs->media_id;
209               $f->media_title = $rs->media_title;
210               $f->media_meta =  $meta instanceof SimpleXMLElement ? $meta : simplexml_load_string('<meta></meta>');
211               $f->media_user = $rs->user_id;
212               $f->media_priv = (boolean) $rs->media_private;
213               $f->media_dt = strtotime($rs->media_dt);
214               $f->media_dtstr = dt::str('%Y-%m-%d %H:%M',$f->media_dt);
215               
216               $f->media_image = false;
217               
218               if (!$this->core->auth->check('media_admin',$this->core->blog->id)
219               && $this->core->auth->userID() != $f->media_user) {
220                    $f->del = false;
221                    $f->editable = false;
222               }
223               
224               $type_prefix = explode('/',$f->type);
225               $type_prefix = $type_prefix[0];
226               
227               switch ($type_prefix) {
228                    case 'image':
229                         $f->media_image = true;
230                         $f->media_icon = 'image';
231                         break;
232                    case 'audio':
233                         $f->media_icon = 'audio';
234                         break;
235                    case 'text':
236                         $f->media_icon = 'text';
237                         break;
238                    case 'video':
239                         $f->media_icon = 'video';
240                         break;
241                    default:
242                         $f->media_icon = 'blank';
243               }
244               switch ($f->type) {
245                    case 'application/msword':
246                    case 'application/vnd.oasis.opendocument.text':
247                    case 'application/vnd.sun.xml.writer':
248                    case 'application/pdf':
249                    case 'application/postscript':
250                         $f->media_icon = 'document';
251                         break;
252                    case 'application/msexcel':
253                    case 'application/vnd.oasis.opendocument.spreadsheet':
254                    case 'application/vnd.sun.xml.calc':
255                         $f->media_icon = 'spreadsheet';
256                         break;
257                    case 'application/mspowerpoint':
258                    case 'application/vnd.oasis.opendocument.presentation':
259                    case 'application/vnd.sun.xml.impress':
260                         $f->media_icon = 'presentation';
261                         break;
262                    case 'application/x-debian-package':
263                    case 'application/x-bzip':
264                    case 'application/x-gzip':
265                    case 'application/x-java-archive':
266                    case 'application/rar':
267                    case 'application/x-redhat-package-manager':
268                    case 'application/x-tar':
269                    case 'application/x-gtar':
270                    case 'application/zip':
271                         $f->media_icon = 'package';
272                         break;
273                    case 'application/octet-stream':
274                         $f->media_icon = 'executable';
275                         break;
276                    case 'application/x-shockwave-flash':
277                         $f->media_icon = 'video';
278                         break;
279                    case 'application/ogg':
280                         $f->media_icon = 'audio';
281                         break;
282                    case 'text/html':
283                         $f->media_icon = 'html';
284                         break;
285               }
286               
287               $f->media_type = $f->media_icon;
288               $f->media_icon = sprintf($this->icon_img,$f->media_icon);
289               
290               # Thumbnails
291               $f->media_thumb = array();
292               $p = path::info($f->relname);
293               $thumb = sprintf($this->thumb_tp,$this->root.'/'.$p['dirname'],$p['base'],'%s');
294               $thumb_url = sprintf($this->thumb_tp,$this->root_url.$p['dirname'],$p['base'],'%s');
295               
296               # Cleaner URLs
297               $thumb_url = preg_replace('#\./#','/',$thumb_url);
298               $thumb_url = preg_replace('#(?<!:)/+#','/',$thumb_url);
299               
300               foreach ($this->thumb_sizes as $suffix => $s) {
301                    if (file_exists(sprintf($thumb,$suffix))) {
302                         $f->media_thumb[$suffix] = sprintf($thumb_url,$suffix);
303                    }
304               }
305               
306               if (isset($f->media_thumb['sq']) && $f->media_type == 'image') {
307                    $f->media_icon = $f->media_thumb['sq'];
308               }
309               
310               return $f;
311          }
312         
313          return null;
314     }
315     
316     
317     public function setFileSort($type='name')
318     {
319          if (in_array($type,array('name-asc','name-desc','date-asc','date-desc'))) {
320               $this->file_sort = $type;
321          }
322     }
323     
324     protected function sortFileHandler($a,$b)
325     {
326          switch ($this->file_sort)
327          {
328               case 'date-asc':
329                    if ($a->media_dt == $b->media_dt) {
330                         return 0;
331                    }
332                    return ($a->media_dt < $b->media_dt) ? -1 : 1;
333               case 'date-desc':
334                    if ($a->media_dt == $b->media_dt) {
335                         return 0;
336                    }
337                    return ($a->media_dt > $b->media_dt) ? -1 : 1;
338               case 'name-desc':
339                    return strcasecmp($b->basename,$a->basename);
340               case 'name-asc':
341               default:
342                    return strcasecmp($a->basename,$b->basename);
343          }
344         
345     }
346     
347     /**
348     Gets current working directory content.
349     
350     @param    type      <b>string</b>       Media type filter
351     */
352     public function getDir($type=null)
353     {
354          if ($type) {
355               $this->type = $type;
356          }
357         
358          $media_dir = $this->relpwd ? $this->relpwd : '.';
359         
360          $strReq =
361          'SELECT media_file, media_id, media_path, media_title, media_meta, media_dt, '.
362          'media_creadt, media_upddt, media_private, user_id '.
363          'FROM '.$this->table.' '.
364          "WHERE media_path = '".$this->path."' ".
365          "AND media_dir = '".$this->con->escape($media_dir)."' ";
366         
367          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
368          {
369               $strReq .= 'AND (media_private <> 1 ';
370               
371               if ($this->core->auth->userID()) {
372                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
373               }
374               $strReq .= ') ';
375          }
376         
377          $rs = $this->con->select($strReq);
378         
379          parent::getDir();
380         
381          $f_res = array();
382          $p_dir = $this->dir;
383         
384          # If type is set, remove items from p_dir
385          if ($this->type)
386          {
387               foreach ($p_dir['files'] as $k => $f) {
388                    if ($f->type_prefix != $this->type) {
389                         unset($p_dir['files'][$k]);
390                    }
391               }
392          }
393         
394          $f_reg = array();
395         
396          while ($rs->fetch())
397          {
398               # File in subdirectory, forget about it!
399               if (dirname($rs->media_file) != '.' && dirname($rs->media_file) != $this->relpwd) {
400                    continue;
401               }
402               
403               if ($this->inFiles($rs->media_file))
404               {
405                    $f = $this->fileRecord($rs);
406                    if ($f !== null) {
407                         if (isset($f_reg[$rs->media_file]))
408                         {
409                              # That media is duplicated in the database,
410                              # time to do a bit of house cleaning.
411                              $this->con->execute(
412                                   'DELETE FROM '.$this->table.' '.
413                                   "WHERE media_id = ".$this->fileRecord($rs)->media_id
414                              );
415                         } else {
416                              $f_res[] = $this->fileRecord($rs);
417                              $f_reg[$rs->media_file] = 1;
418                         }
419                    }
420               }
421               elseif (!empty($p_dir['files']) && $this->relpwd == '')
422               {
423                    # Physical file does not exist remove it from DB
424                    # Because we don't want to erase everything on
425                    # dotclear upgrade, do it only if there are files
426                    # in directory and directory is root
427                    $this->con->execute(
428                         'DELETE FROM '.$this->table.' '.
429                         "WHERE media_path = '".$this->con->escape($this->path)."' ".
430                         "AND media_file = '".$this->con->escape($rs->media_file)."' "
431                    );
432                    $this->callFileHandler(files::getMimeType($rs->media_file),'remove',$this->pwd.'/'.$rs->media_file);
433               }
434          }
435         
436          $this->dir['files'] = $f_res;
437          foreach ($this->dir['dirs'] as $k => $v) {
438               $v->media_icon = sprintf($this->icon_img,'folder');
439          }
440         
441          # Check files that don't exist in database and create them
442          if ($this->core->auth->check('media,media_admin',$this->core->blog->id))
443          {
444               foreach ($p_dir['files'] as $f)
445               {
446                    if (!isset($f_reg[$f->relname])) {
447                         if (($id = $this->createFile($f->basename,null,false,null,false)) !== false) {
448                              $this->dir['files'][] = $this->getFile($id);
449                         }
450                    }
451               }
452          }
453          usort($this->dir['files'],array($this,'sortFileHandler'));
454     }
455     
456     /**
457     Gets file by its id. Returns a filteItem object.
458     
459     @param    id        <b>integer</b>      File ID
460     @return   <b>fileItem</b>
461     */
462     public function getFile($id)
463     {
464          $strReq =
465          'SELECT media_id, media_path, media_title, '.
466          'media_file, media_meta, media_dt, media_creadt, '.
467          'media_upddt, media_private, user_id '.
468          'FROM '.$this->table.' '.
469          "WHERE media_path = '".$this->path."' ".
470          'AND media_id = '.(integer) $id.' ';
471         
472          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
473          {
474               $strReq .= 'AND (media_private <> 1 ';
475               
476               if ($this->core->auth->userID()) {
477                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
478               }
479               $strReq .= ') ';
480          }
481         
482          $rs = $this->con->select($strReq);
483          return $this->fileRecord($rs);
484     }
485     
486     /**
487     Returns media items attached to a blog post. Result is an array containing
488     fileItems objects.
489     
490     @param    post_id   <b>integer</b>      Post ID
491     @param    media_id  <b>integer</b>      Optionnal media ID
492     @return   <b>array</b> Array of fileItems
493     */
494     public function getPostMedia($post_id,$media_id=null)
495     {
496          $params = array(
497               'post_id' => $post_id,
498               'media_path' => $this->path
499          );
500          if ($media_id) {
501               $params['media_id'] = (integer) $media_id;
502          }
503          $rs = $this->postmedia->getPostMedia($params);
504         
505          $res = array();
506         
507          while ($rs->fetch()) {
508               $f = $this->fileRecord($rs);
509               if ($f !== null) {
510                    $res[] = $f;
511               }
512          }
513         
514          return $res;
515     }
516     
517     /**
518     @deprecated since version 2.4
519     @see dcPostMedia::addPostMedia
520     */
521     public function addPostMedia($post_id,$media_id)
522     {
523          $this->postmedia->addPostMedia($post_id,$media_id);
524     }
525     
526     /**
527     @deprecated since version 2.4
528     @see dcPostMedia::removePostMedia
529     */
530     public function removePostMedia($post_id,$media_id)
531     {
532          $this->postmedia->removePostMedia($post_id,$media_id,"attachment");
533     }
534     
535     /**
536     Rebuilds database items collection. Optional <var>$pwd</var> parameter is
537     the path where to start rebuild.
538     
539     @param    pwd       <b>string</b>       Directory to rebuild
540     */
541     public function rebuild($pwd='')
542     {
543          if (!$this->core->auth->isSuperAdmin()) {
544               throw new Exception(__('You are not a super administrator.'));
545          }
546         
547          $this->chdir($pwd);
548          parent::getDir();
549         
550          $dir = $this->dir;
551         
552          foreach ($dir['dirs'] as $d) {
553               if (!$d->parent) {
554                    $this->rebuild($d->relname,false);
555               }
556          }
557         
558          foreach ($dir['files'] as $f) {
559               $this->chdir(dirname($f->relname));
560               $this->createFile($f->basename);
561          }
562         
563          $this->rebuildDB($pwd);
564     }
565     
566     protected function rebuildDB($pwd)
567     {
568          $media_dir = $pwd ? $pwd : '.';
569         
570          $strReq =
571          'SELECT media_file, media_id '.
572          'FROM '.$this->table.' '.
573          "WHERE media_path = '".$this->path."' ".
574          "AND media_dir = '".$this->con->escape($media_dir)."' ";
575         
576          $rs = $this->con->select($strReq);
577         
578          $delReq = 'DELETE FROM '.$this->table.' '.
579                    'WHERE media_id IN (%s) ';
580          $del_ids = array();
581         
582          while ($rs->fetch())
583          {
584               if (!is_file($this->root.'/'.$rs->media_file)) {
585                    $del_ids[] = (integer) $rs->media_id;
586               }
587          }
588         
589          if (!empty($del_ids)) {
590               $this->con->execute(sprintf($delReq,implode(',',$del_ids)));
591          }
592     }
593     
594     public function makeDir($d)
595     {
596          $d = files::tidyFileName($d);
597          parent::makeDir($d);
598     }
599     
600     /**
601     Creates or updates a file in database. Returns new media ID or false if
602     file does not exist.
603     
604     @param    name      <b>string</b>       File name (relative to working directory)
605     @param    title     <b>string</b>       File title
606     @param    private   <b>boolean</b>      File is private
607     @param    dt        <b>string</b>       File date
608     @return   <b>integer</b> New media ID
609     */
610     public function createFile($name,$title=null,$private=false,$dt=null,$force=true)
611     {
612          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
613               throw new Exception(__('Permission denied.'));
614          }
615         
616          $file = $this->pwd.'/'.$name;
617          if (!file_exists($file)) {
618               return false;
619          }
620         
621          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$name) : path::clean($name);
622          $media_type = files::getMimeType($name);
623         
624          $cur = $this->con->openCursor($this->table);
625         
626          $strReq = 'SELECT media_id '.
627                    'FROM '.$this->table.' '.
628                    "WHERE media_path = '".$this->con->escape($this->path)."' ".
629                    "AND media_file = '".$this->con->escape($media_file)."' ";
630         
631          $rs = $this->con->select($strReq);
632         
633          if ($rs->isEmpty())
634          {
635               $this->con->writeLock($this->table);
636               try
637               {
638                    $rs = $this->con->select('SELECT MAX(media_id) FROM '.$this->table);
639                    $media_id = (integer) $rs->f(0) + 1;
640                   
641                    $cur->media_id = $media_id;
642                    $cur->user_id = (string) $this->core->auth->userID();
643                    $cur->media_path = (string) $this->path;
644                    $cur->media_file = (string) $media_file;
645                    $cur->media_dir = (string) dirname($media_file);
646                    $cur->media_creadt = date('Y-m-d H:i:s');
647                    $cur->media_upddt = date('Y-m-d H:i:s');
648                   
649                    $cur->media_title = !$title ? (string) $name : (string) $title;
650                    $cur->media_private = (integer) (boolean) $private;
651                   
652                    if ($dt) {
653                         $cur->media_dt = (string) $dt;
654                    } else {
655                         $cur->media_dt = strftime('%Y-%m-%d %H:%M:%S',filemtime($file));
656                    }
657                   
658                    try {
659                         $cur->insert();
660                    } catch (Exception $e) {
661                         @unlink($name);
662                         throw $e;
663                    }
664                    $this->con->unlock();
665               }
666               catch (Exception $e)
667               {
668                    $this->con->unlock();
669                    throw $e;
670               }
671          }
672          else
673          {
674               $media_id = (integer) $rs->media_id;
675               
676               $cur->media_upddt = date('Y-m-d H:i:s');
677               
678               $cur->update('WHERE media_id = '.$media_id);
679          }
680         
681          $this->callFileHandler($media_type,'create',$cur,$name,$media_id,$force);
682         
683          return $media_id;
684     }
685     
686     /**
687     Updates a file in database.
688     
689     @param    file      <b>fileItem</b>     Current fileItem object
690     @param    newFile   <b>fileItem</b>     New fileItem object
691     */
692     public function updateFile($file,$newFile)
693     {
694          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
695               throw new Exception(__('Permission denied.'));
696          }
697         
698          $id = (integer) $file->media_id;
699         
700          if (!$id) {
701               throw new Exception('No file ID');
702          }
703         
704          if (!$this->core->auth->check('media_admin',$this->core->blog->id)
705          && $this->core->auth->userID() != $file->media_user) {
706               throw new Exception(__('You are not the file owner.'));
707          }
708         
709          $cur = $this->con->openCursor($this->table);
710         
711          # We need to tidy newFile basename. If dir isn't empty, concat to basename
712          $newFile->relname = files::tidyFileName($newFile->basename);
713          if ($newFile->dir) {
714               $newFile->relname = $newFile->dir.'/'.$newFile->relname;
715          }
716         
717          if ($file->relname != $newFile->relname) {
718               $newFile->file = $this->root.'/'.$newFile->relname;
719               
720               if ($this->isFileExclude($newFile->relname)) {
721                    throw new Exception(__('This file is not allowed.'));
722               }
723               
724               if (file_exists($newFile->file)) {
725                    throw new Exception(__('New file already exists.'));
726               }
727               
728               $this->moveFile($file->relname,$newFile->relname);
729               
730               $cur->media_file = (string) $newFile->relname;
731               $cur->media_dir = (string) dirname($newFile->relname);
732          }
733         
734          $cur->media_title = (string) $newFile->media_title;
735          $cur->media_dt = (string) $newFile->media_dtstr;
736          $cur->media_upddt = date('Y-m-d H:i:s');
737          $cur->media_private = (integer) $newFile->media_priv;
738         
739          $cur->update('WHERE media_id = '.$id);
740         
741          $this->callFileHandler($file->type,'update',$file,$newFile);
742     }
743     
744     /**
745     Uploads a file.
746     
747     @param    tmp       <b>string</b>       Full path of temporary uploaded file
748     @param    name      <b>string</b>       File name (relative to working directory)
749     @param    title     <b>string</b>       File title
750     @param    private   <b>boolean</b>      File is private
751     */
752     public function uploadFile($tmp,$name,$title=null,$private=false,$overwrite=false)
753     {
754          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
755               throw new Exception(__('Permission denied.'));
756          }
757         
758          $name = files::tidyFileName($name);
759         
760          parent::uploadFile($tmp,$name,$overwrite);
761         
762          return $this->createFile($name,$title,$private);
763     }
764     
765     /**
766     Creates a file from binary content.
767     
768     @param    name      <b>string</b>       File name (relative to working directory)
769     @param    bits      <b>string</b>       Binary file content
770     */
771     public function uploadBits($name,$bits)
772     {
773          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
774               throw new Exception(__('Permission denied.'));
775          }
776         
777          $name = files::tidyFileName($name);
778         
779          parent::uploadBits($name,$bits);
780         
781          return $this->createFile($name,null,null);
782     }
783     
784     /**
785     Removes a file.
786     
787     @param    f         <b>fileItem</b>     fileItem object
788     */
789     public function removeFile($f)
790     {
791          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
792               throw new Exception(__('Permission denied.'));
793          }
794         
795          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$f) : path::clean($f);
796         
797          $strReq = 'DELETE FROM '.$this->table.' '.
798                    "WHERE media_path = '".$this->con->escape($this->path)."' ".
799                    "AND media_file = '".$this->con->escape($media_file)."' ";
800         
801          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
802          {
803               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."'";
804          }
805         
806          $this->con->execute($strReq);
807         
808          if ($this->con->changes() == 0) {
809               throw new Exception(__('File does not exist in the database.'));
810          }
811         
812          parent::removeFile($f);
813         
814          $this->callFileHandler(files::getMimeType($media_file),'remove',$f);
815     }
816     
817     /**
818     Extract zip file in current location
819     
820     @param    f         <b>fileRecord</b>   fileRecord object
821     */
822     public function inflateZipFile($f,$create_dir=true)
823     {
824          $zip = new fileUnzip($f->file);
825          $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
826         
827          if ($create_dir)
828          {
829               $zip_root_dir = $zip->getRootDir();
830               if ($zip_root_dir != false) {
831                    $destination = $zip_root_dir;
832                    $target = $f->dir;
833               } else {
834                    $destination = preg_replace('/\.([^.]+)$/','',$f->basename);
835                    $target = $f->dir.'/'.$destination;
836               }
837               
838               if (is_dir($f->dir.'/'.$destination)) {
839                    throw new Exception(sprintf(__('Extract destination directory %s already exists.'),dirname($f->relname).'/'.$destination)); 
840               }
841          }
842          else
843          {
844               $target = $f->dir;
845               $destination = '';
846          }
847         
848          $zip->unzipAll($target);
849          $zip->close();
850          return dirname($f->relname).'/'.$destination;
851     }
852     
853     /**
854     Returns zip file content
855     
856     @param    f         <b>fileRecord</b>   fileRecord object
857     @return <b>array</b>
858     */
859     public function getZipContent($f)
860     {
861          $zip = new fileUnzip($f->file);
862          $list = $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
863          $zip->close();
864          return $list;
865     }
866
867     /**
868     Calls file handlers registered for recreate event
869     
870     @param    f    <b>fileItem</b>     fileItem object
871     */
872     public function mediaFireRecreateEvent($f)
873     {
874          $media_type = files::getMimeType($f->basename);
875          $this->callFileHandler($media_type,'recreate',null,$f->basename); // Args list to be completed as necessary (Franck)
876     }
877     
878     /* Image handlers
879     ------------------------------------------------------- */
880     public function imageThumbCreate($cur,$f,$force=true)
881     {
882          $file = $this->pwd.'/'.$f;
883         
884          if (!file_exists($file)) {
885               return false;
886          }
887         
888          $p = path::info($file);
889          $thumb = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
890         
891          try
892          {
893               $img = new imageTools();
894               $img->loadImage($file);
895               
896               $w = $img->getW();
897               $h = $img->getH();
898               
899               if ($force) $this->imageThumbRemove($f);
900               
901               foreach ($this->thumb_sizes as $suffix => $s) {
902                    $thumb_file = sprintf($thumb,$suffix);
903                    if (!file_exists($thumb_file) && $s[0] > 0 &&
904                         ($suffix == 'sq' || $w > $s[0] || $h > $s[0]))
905                    {
906                         $img->resize($s[0],$s[0],$s[1]);
907                         $img->output('jpeg',$thumb_file,80);
908                    }
909               }
910               $img->close();
911          }
912          catch (Exception $e)
913          {
914               if ($cur === null) { # Called only if cursor is null (public call)
915                    throw $e;
916               }
917          }
918     }
919     
920     protected function imageThumbUpdate(&$file,&$newFile)
921     {
922          if ($file->relname != $newFile->relname)
923          {
924               $p = path::info($file->relname);
925               $thumb_old = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
926               
927               $p = path::info($newFile->relname);
928               $thumb_new = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
929               
930               foreach ($this->thumb_sizes as $suffix => $s) {
931                    try {
932                         parent::moveFile(sprintf($thumb_old,$suffix),sprintf($thumb_new,$suffix));
933                    } catch (Exception $e) {}
934               }
935          }
936     }
937     
938     protected function imageThumbRemove($f)
939     {
940          $p = path::info($f);
941          $thumb = sprintf($this->thumb_tp,'',$p['base'],'%s');
942         
943          foreach ($this->thumb_sizes as $suffix => $s) {
944               try {
945                    parent::removeFile(sprintf($thumb,$suffix));
946               } catch (Exception $e) {}
947          }
948     }
949     
950     protected function imageMetaCreate($cur,$f,$id)
951     {
952          $file = $this->pwd.'/'.$f;
953         
954          if (!file_exists($file)) {
955               return false;
956          }
957         
958          $xml = new xmlTag('meta');
959          $meta = imageMeta::readMeta($file);
960          $xml->insertNode($meta);
961         
962          $c = $this->core->con->openCursor($this->table);
963          $c->media_meta = $xml->toXML();
964         
965          if ($cur->media_title !== null && $cur->media_title == basename($cur->media_file))
966          {
967               if ($meta['Title']) {
968                    $c->media_title = $meta['Title'];
969               }
970          }
971         
972          if ($meta['DateTimeOriginal'] && $cur->media_dt === '')
973          {
974               # We set picture time to user timezone
975               $media_ts = strtotime($meta['DateTimeOriginal']);
976               if ($media_ts !== false) {
977                    $o = dt::getTimeOffset($this->core->auth->getInfo('user_tz'),$media_ts);
978                    $c->media_dt = dt::str('%Y-%m-%d %H:%M:%S',$media_ts+$o);
979               }
980          }
981         
982          $c->update('WHERE media_id = '.$id);
983     }
984     
985     /**
986     Returns HTML code for MP3 player
987     
988     @param    url       <b>string</b>       MP3 URL to play
989     @param    player    <b>string</b>       Player URL
990     @param    args      <b>array</b>        Player parameters
991     @return   <b>string</b>
992     */
993     public static function mp3player($url,$player=null,$args=null)
994     {
995          if (!$player) {
996               $player = 'player_mp3.swf';
997          }
998         
999          if (!is_array($args))
1000          {
1001               $args = array(
1002                    'showvolume' => 1,
1003                    'loadingcolor' => 'ff9900',
1004                    'bgcolor1' => 'eeeeee',
1005                    'bgcolor2' => 'cccccc',
1006                    'buttoncolor' => '0066cc',
1007                    'buttonovercolor' => 'ff9900',
1008                    'slidercolor1' => 'cccccc',
1009                    'slidercolor2' => '999999',
1010                    'sliderovercolor' => '0066cc'
1011               );
1012          }
1013         
1014          $args['mp3'] = $url;
1015         
1016          if (empty($args['width'])) {
1017               $args['width'] = 200;
1018          }
1019          if (empty($args['height'])) {
1020               $args['height'] = 20;
1021          }
1022         
1023          $vars = array();
1024          foreach ($args as $k => $v) {
1025               $vars[] = $k.'='.$v;
1026          }
1027         
1028          return
1029          '<object type="application/x-shockwave-flash" '.
1030          'data="'.$player.'" '.
1031          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1032          '<param name="movie" value="'.$player.'" />'.
1033          '<param name="wmode" value="transparent" />'.
1034          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1035          __('Embedded Audio Player').
1036          '</object>';
1037     }
1038     
1039     public static function flvplayer($url,$player=null,$args=null)
1040     {
1041          if (!$player) {
1042               $player = 'player_flv.swf';
1043          }
1044         
1045          if (!is_array($args))
1046          {
1047               $args = array(
1048                    'margin' => 1,
1049                    'showvolume' => 1,
1050                    'showtime' => 1,
1051                    'showfullscreen' => 1,
1052                    'buttonovercolor' => 'ff9900',
1053                    'slidercolor1' => 'cccccc',
1054                    'slidercolor2' => '999999',
1055                    'sliderovercolor' => '0066cc'
1056               );
1057          }
1058         
1059          $args['flv'] = $url;
1060         
1061          if (empty($args['width'])) {
1062               $args['width'] = 400;
1063          }
1064          if (empty($args['height'])) {
1065               $args['height'] = 300;
1066          }
1067         
1068          $vars = array();
1069          foreach ($args as $k => $v) {
1070               $vars[] = $k.'='.$v;
1071          }
1072         
1073          return
1074          '<object type="application/x-shockwave-flash" '.
1075          'data="'.$player.'" '.
1076          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1077          '<param name="movie" value="'.$player.'" />'.
1078          '<param name="wmode" value="transparent" />'.
1079          '<param name="allowFullScreen" value="true" />'.
1080          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1081          __('Embedded Video Player').
1082          '</object>';
1083     }
1084}
1085?>
Note: See TracBrowser for help on using the repository browser.

Sites map