Dotclear

source: inc/core/class.dc.media.php @ 40:67e32341a65d

Revision 40:67e32341a65d, 29.0 KB checked in by Dsls <dsls@…>, 14 years ago (diff)

Removed duplicate mediaFireRecreateEvent function

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2010 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 $table_ref;    ///< <b>string</b> Post-media relation table name
26     protected $type;         ///< <b>string</b> Media type filter
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         
60          if ($this->core->blog == null) {
61               throw new Exception(__('No blog defined.'));
62          }
63         
64          $this->table = $this->core->prefix.'media';
65          $this->table_ref = $this->core->prefix.'post_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          $post_id = (integer) $post_id;
497         
498          $strReq =
499          'SELECT media_file, M.media_id, media_path, media_title, media_meta, media_dt, '.
500          'media_creadt, media_upddt, media_private, user_id '.
501          'FROM '.$this->table.' M '.
502          'INNER JOIN '.$this->table_ref.' PM ON (M.media_id = PM.media_id) '.
503          "WHERE media_path = '".$this->path."' ".
504          'AND post_id = '.$post_id.' ';
505         
506          if ($media_id) {
507               $strReq .= 'AND M.media_id = '.(integer) $media_id.' ';
508          }
509         
510          $rs = $this->con->select($strReq);
511         
512          $res = array();
513         
514          while ($rs->fetch()) {
515               $f = $this->fileRecord($rs);
516               if ($f !== null) {
517                    $res[] = $f;
518               }
519          }
520         
521          return $res;
522     }
523     
524     /**
525     Attaches a media to a post.
526     
527     @param    post_id   <b>integer</b>      Post ID
528     @param    media_id  <b>integer</b>      Optionnal media ID
529     */
530     public function addPostMedia($post_id,$media_id)
531     {
532          $post_id = (integer) $post_id;
533          $media_id = (integer) $media_id;
534         
535          $f = $this->getPostMedia($post_id,$media_id);
536         
537          if (!empty($f)) {
538               return;
539          }
540         
541          $cur = $this->con->openCursor($this->table_ref);
542          $cur->post_id = $post_id;
543          $cur->media_id = $media_id;
544         
545          $cur->insert();
546          $this->core->blog->triggerBlog();
547     }
548     
549     /**
550     Detaches a media from a post.
551     
552     @param    post_id   <b>integer</b>      Post ID
553     @param    media_id  <b>integer</b>      Optionnal media ID
554     */
555     public function removePostMedia($post_id,$media_id)
556     {
557          $post_id = (integer) $post_id;
558          $media_id = (integer) $media_id;
559         
560          $strReq = 'DELETE FROM '.$this->table_ref.' '.
561                    'WHERE post_id = '.$post_id.' '.
562                    'AND media_id = '.$media_id.' ';
563         
564          $this->con->execute($strReq);
565          $this->core->blog->triggerBlog();
566     }
567     
568     /**
569     Rebuilds database items collection. Optional <var>$pwd</var> parameter is
570     the path where to start rebuild.
571     
572     @param    pwd       <b>string</b>       Directory to rebuild
573     */
574     public function rebuild($pwd='')
575     {
576          if (!$this->core->auth->isSuperAdmin()) {
577               throw new Exception(__('You are not a super administrator.'));
578          }
579         
580          $this->chdir($pwd);
581          parent::getDir();
582         
583          $dir = $this->dir;
584         
585          foreach ($dir['dirs'] as $d) {
586               if (!$d->parent) {
587                    $this->rebuild($d->relname,false);
588               }
589          }
590         
591          foreach ($dir['files'] as $f) {
592               $this->chdir(dirname($f->relname));
593               $this->createFile($f->basename);
594          }
595         
596          $this->rebuildDB($pwd);
597     }
598     
599     protected function rebuildDB($pwd)
600     {
601          $media_dir = $pwd ? $pwd : '.';
602         
603          $strReq =
604          'SELECT media_file, media_id '.
605          'FROM '.$this->table.' '.
606          "WHERE media_path = '".$this->path."' ".
607          "AND media_dir = '".$this->con->escape($media_dir)."' ";
608         
609          $rs = $this->con->select($strReq);
610         
611          $delReq = 'DELETE FROM '.$this->table.' '.
612                    'WHERE media_id IN (%s) ';
613          $del_ids = array();
614         
615          while ($rs->fetch())
616          {
617               if (!is_file($this->root.'/'.$rs->media_file)) {
618                    $del_ids[] = (integer) $rs->media_id;
619               }
620          }
621         
622          if (!empty($del_ids)) {
623               $this->con->execute(sprintf($delReq,implode(',',$del_ids)));
624          }
625     }
626     
627     public function makeDir($d)
628     {
629          $d = files::tidyFileName($d);
630          parent::makeDir($d);
631     }
632     
633     /**
634     Creates or updates a file in database. Returns new media ID or false if
635     file does not exist.
636     
637     @param    name      <b>string</b>       File name (relative to working directory)
638     @param    title     <b>string</b>       File title
639     @param    private   <b>boolean</b>      File is private
640     @param    dt        <b>string</b>       File date
641     @return   <b>integer</b> New media ID
642     */
643     public function createFile($name,$title=null,$private=false,$dt=null,$force=true)
644     {
645          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
646               throw new Exception(__('Permission denied.'));
647          }
648         
649          $file = $this->pwd.'/'.$name;
650          if (!file_exists($file)) {
651               return false;
652          }
653         
654          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$name) : path::clean($name);
655          $media_type = files::getMimeType($name);
656         
657          $cur = $this->con->openCursor($this->table);
658         
659          $strReq = 'SELECT media_id '.
660                    'FROM '.$this->table.' '.
661                    "WHERE media_path = '".$this->con->escape($this->path)."' ".
662                    "AND media_file = '".$this->con->escape($media_file)."' ";
663         
664          $rs = $this->con->select($strReq);
665         
666          if ($rs->isEmpty())
667          {
668               $this->con->writeLock($this->table);
669               try
670               {
671                    $rs = $this->con->select('SELECT MAX(media_id) FROM '.$this->table);
672                    $media_id = (integer) $rs->f(0) + 1;
673                   
674                    $cur->media_id = $media_id;
675                    $cur->user_id = (string) $this->core->auth->userID();
676                    $cur->media_path = (string) $this->path;
677                    $cur->media_file = (string) $media_file;
678                    $cur->media_dir = (string) dirname($media_file);
679                    $cur->media_creadt = date('Y-m-d H:i:s');
680                    $cur->media_upddt = date('Y-m-d H:i:s');
681                   
682                    $cur->media_title = !$title ? (string) $name : (string) $title;
683                    $cur->media_private = (integer) (boolean) $private;
684                   
685                    if ($dt) {
686                         $cur->media_dt = (string) $dt;
687                    } else {
688                         $cur->media_dt = strftime('%Y-%m-%d %H:%M:%S',filemtime($file));
689                    }
690                   
691                    try {
692                         $cur->insert();
693                    } catch (Exception $e) {
694                         @unlink($name);
695                         throw $e;
696                    }
697                    $this->con->unlock();
698               }
699               catch (Exception $e)
700               {
701                    $this->con->unlock();
702                    throw $e;
703               }
704          }
705          else
706          {
707               $media_id = (integer) $rs->media_id;
708               
709               $cur->media_upddt = date('Y-m-d H:i:s');
710               
711               $cur->update('WHERE media_id = '.$media_id);
712          }
713         
714          $this->callFileHandler($media_type,'create',$cur,$name,$media_id,$force);
715         
716          return $media_id;
717     }
718     
719     /**
720     Updates a file in database.
721     
722     @param    file      <b>fileItem</b>     Current fileItem object
723     @param    newFile   <b>fileItem</b>     New fileItem object
724     */
725     public function updateFile($file,$newFile)
726     {
727          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
728               throw new Exception(__('Permission denied.'));
729          }
730         
731          $id = (integer) $file->media_id;
732         
733          if (!$id) {
734               throw new Exception('No file ID');
735          }
736         
737          if (!$this->core->auth->check('media_admin',$this->core->blog->id)
738          && $this->core->auth->userID() != $file->media_user) {
739               throw new Exception(__('You are not the file owner.'));
740          }
741         
742          $cur = $this->con->openCursor($this->table);
743         
744          # We need to tidy newFile basename. If dir isn't empty, concat to basename
745          $newFile->relname = files::tidyFileName($newFile->basename);
746          if ($newFile->dir) {
747               $newFile->relname = $newFile->dir.'/'.$newFile->relname;
748          }
749         
750          if ($file->relname != $newFile->relname) {
751               $newFile->file = $this->root.'/'.$newFile->relname;
752               
753               if ($this->isFileExclude($newFile->relname)) {
754                    throw new Exception(__('This file is not allowed.'));
755               }
756               
757               if (file_exists($newFile->file)) {
758                    throw new Exception(__('New file already exists.'));
759               }
760               
761               $this->moveFile($file->relname,$newFile->relname);
762               
763               $cur->media_file = (string) $newFile->relname;
764               $cur->media_dir = (string) dirname($newFile->relname);
765          }
766         
767          $cur->media_title = (string) $newFile->media_title;
768          $cur->media_dt = (string) $newFile->media_dtstr;
769          $cur->media_upddt = date('Y-m-d H:i:s');
770          $cur->media_private = (integer) $newFile->media_priv;
771         
772          $cur->update('WHERE media_id = '.$id);
773         
774          $this->callFileHandler($file->type,'update',$file,$newFile);
775     }
776     
777     /**
778     Uploads a file.
779     
780     @param    tmp       <b>string</b>       Full path of temporary uploaded file
781     @param    name      <b>string</b>       File name (relative to working directory)
782     @param    title     <b>string</b>       File title
783     @param    private   <b>boolean</b>      File is private
784     */
785     public function uploadFile($tmp,$name,$title=null,$private=false,$overwrite=false)
786     {
787          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
788               throw new Exception(__('Permission denied.'));
789          }
790         
791          $name = files::tidyFileName($name);
792         
793          parent::uploadFile($tmp,$name,$overwrite);
794         
795          return $this->createFile($name,$title,$private);
796     }
797     
798     /**
799     Creates a file from binary content.
800     
801     @param    name      <b>string</b>       File name (relative to working directory)
802     @param    bits      <b>string</b>       Binary file content
803     */
804     public function uploadBits($name,$bits)
805     {
806          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
807               throw new Exception(__('Permission denied.'));
808          }
809         
810          $name = files::tidyFileName($name);
811         
812          parent::uploadBits($name,$bits);
813         
814          return $this->createFile($name,null,null);
815     }
816     
817     /**
818     Removes a file.
819     
820     @param    f         <b>fileItem</b>     fileItem object
821     */
822     public function removeFile($f)
823     {
824          if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
825               throw new Exception(__('Permission denied.'));
826          }
827         
828          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$f) : path::clean($f);
829         
830          $strReq = 'DELETE FROM '.$this->table.' '.
831                    "WHERE media_path = '".$this->con->escape($this->path)."' ".
832                    "AND media_file = '".$this->con->escape($media_file)."' ";
833         
834          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
835          {
836               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."'";
837          }
838         
839          $this->con->execute($strReq);
840         
841          if ($this->con->changes() == 0) {
842               throw new Exception(__('File does not exist in the database.'));
843          }
844         
845          parent::removeFile($f);
846         
847          $this->callFileHandler(files::getMimeType($media_file),'remove',$f);
848     }
849     
850     /**
851     Extract zip file in current location
852     
853     @param    f         <b>fileRecord</b>   fileRecord object
854     */
855     public function inflateZipFile($f,$create_dir=true)
856     {
857          $zip = new fileUnzip($f->file);
858          $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
859         
860          if ($create_dir)
861          {
862               $zip_root_dir = $zip->getRootDir();
863               if ($zip_root_dir != false) {
864                    $destination = $zip_root_dir;
865                    $target = $f->dir;
866               } else {
867                    $destination = preg_replace('/\.([^.]+)$/','',$f->basename);
868                    $target = $f->dir.'/'.$destination;
869               }
870               
871               if (is_dir($f->dir.'/'.$destination)) {
872                    throw new Exception(sprintf(__('Extract destination directory %s already exists.'),dirname($f->relname).'/'.$destination)); 
873               }
874          }
875          else
876          {
877               $target = $f->dir;
878               $destination = '';
879          }
880         
881          $zip->unzipAll($target);
882          $zip->close();
883          return dirname($f->relname).'/'.$destination;
884     }
885     
886     /**
887     Returns zip file content
888     
889     @param    f         <b>fileRecord</b>   fileRecord object
890     @return <b>array</b>
891     */
892     public function getZipContent($f)
893     {
894          $zip = new fileUnzip($f->file);
895          $list = $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
896          $zip->close();
897          return $list;
898     }
899
900     /**
901     Calls file handlers registered for recreate event
902     
903     @param    f    <b>fileItem</b>     fileItem object
904     */
905     public function mediaFireRecreateEvent($f)
906     {
907          $media_type = files::getMimeType($f->basename);
908          $this->callFileHandler($media_type,'recreate',null,$f->basename); // Args list to be completed as necessary (Franck)
909     }
910     
911     /* Image handlers
912     ------------------------------------------------------- */
913     public function imageThumbCreate($cur,$f,$force=true)
914     {
915          $file = $this->pwd.'/'.$f;
916         
917          if (!file_exists($file)) {
918               return false;
919          }
920         
921          $p = path::info($file);
922          $thumb = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
923         
924          try
925          {
926               $img = new imageTools();
927               $img->loadImage($file);
928               
929               $w = $img->getW();
930               $h = $img->getH();
931               
932               if ($force) $this->imageThumbRemove($f);
933               
934               foreach ($this->thumb_sizes as $suffix => $s) {
935                    $thumb_file = sprintf($thumb,$suffix);
936                    if (!file_exists($thumb_file) && $s[0] > 0 &&
937                         ($suffix == 'sq' || $w > $s[0] || $h > $s[0]))
938                    {
939                         $img->resize($s[0],$s[0],$s[1]);
940                         $img->output('jpeg',$thumb_file,80);
941                    }
942               }
943               $img->close();
944          }
945          catch (Exception $e)
946          {
947               if ($cur === null) { # Called only if cursor is null (public call)
948                    throw $e;
949               }
950          }
951     }
952     
953     protected function imageThumbUpdate(&$file,&$newFile)
954     {
955          if ($file->relname != $newFile->relname)
956          {
957               $p = path::info($file->relname);
958               $thumb_old = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
959               
960               $p = path::info($newFile->relname);
961               $thumb_new = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
962               
963               foreach ($this->thumb_sizes as $suffix => $s) {
964                    try {
965                         parent::moveFile(sprintf($thumb_old,$suffix),sprintf($thumb_new,$suffix));
966                    } catch (Exception $e) {}
967               }
968          }
969     }
970     
971     protected function imageThumbRemove($f)
972     {
973          $p = path::info($f);
974          $thumb = sprintf($this->thumb_tp,'',$p['base'],'%s');
975         
976          foreach ($this->thumb_sizes as $suffix => $s) {
977               try {
978                    parent::removeFile(sprintf($thumb,$suffix));
979               } catch (Exception $e) {}
980          }
981     }
982     
983     protected function imageMetaCreate($cur,$f,$id)
984     {
985          $file = $this->pwd.'/'.$f;
986         
987          if (!file_exists($file)) {
988               return false;
989          }
990         
991          $xml = new xmlTag('meta');
992          $meta = imageMeta::readMeta($file);
993          $xml->insertNode($meta);
994         
995          $c = $this->core->con->openCursor($this->table);
996          $c->media_meta = $xml->toXML();
997         
998          if ($cur->media_title !== null && $cur->media_title == basename($cur->media_file))
999          {
1000               if ($meta['Title']) {
1001                    $c->media_title = $meta['Title'];
1002               }
1003          }
1004         
1005          if ($meta['DateTimeOriginal'] && $cur->media_dt === '')
1006          {
1007               # We set picture time to user timezone
1008               $media_ts = strtotime($meta['DateTimeOriginal']);
1009               if ($media_ts !== false) {
1010                    $o = dt::getTimeOffset($this->core->auth->getInfo('user_tz'),$media_ts);
1011                    $c->media_dt = dt::str('%Y-%m-%d %H:%M:%S',$media_ts+$o);
1012               }
1013          }
1014         
1015          $c->update('WHERE media_id = '.$id);
1016     }
1017     
1018     /**
1019     Returns HTML code for MP3 player
1020     
1021     @param    url       <b>string</b>       MP3 URL to play
1022     @param    player    <b>string</b>       Player URL
1023     @param    args      <b>array</b>        Player parameters
1024     @return   <b>string</b>
1025     */
1026     public static function mp3player($url,$player=null,$args=null)
1027     {
1028          if (!$player) {
1029               $player = 'player_mp3.swf';
1030          }
1031         
1032          if (!is_array($args))
1033          {
1034               $args = array(
1035                    'showvolume' => 1,
1036                    'loadingcolor' => 'ff9900',
1037                    'bgcolor1' => 'eeeeee',
1038                    'bgcolor2' => 'cccccc',
1039                    'buttoncolor' => '0066cc',
1040                    'buttonovercolor' => 'ff9900',
1041                    'slidercolor1' => 'cccccc',
1042                    'slidercolor2' => '999999',
1043                    'sliderovercolor' => '0066cc'
1044               );
1045          }
1046         
1047          $args['mp3'] = $url;
1048         
1049          if (empty($args['width'])) {
1050               $args['width'] = 200;
1051          }
1052          if (empty($args['height'])) {
1053               $args['height'] = 20;
1054          }
1055         
1056          $vars = array();
1057          foreach ($args as $k => $v) {
1058               $vars[] = $k.'='.$v;
1059          }
1060         
1061          return
1062          '<object type="application/x-shockwave-flash" '.
1063          'data="'.$player.'" '.
1064          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1065          '<param name="movie" value="'.$player.'" />'.
1066          '<param name="wmode" value="transparent" />'.
1067          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1068          __('Embedded Audio Player').
1069          '</object>';
1070     }
1071     
1072     public static function flvplayer($url,$player=null,$args=null)
1073     {
1074          if (!$player) {
1075               $player = 'player_flv.swf';
1076          }
1077         
1078          if (!is_array($args))
1079          {
1080               $args = array(
1081                    'margin' => 1,
1082                    'showvolume' => 1,
1083                    'showtime' => 1,
1084                    'showfullscreen' => 1,
1085                    'buttonovercolor' => 'ff9900',
1086                    'slidercolor1' => 'cccccc',
1087                    'slidercolor2' => '999999',
1088                    'sliderovercolor' => '0066cc'
1089               );
1090          }
1091         
1092          $args['flv'] = $url;
1093         
1094          if (empty($args['width'])) {
1095               $args['width'] = 400;
1096          }
1097          if (empty($args['height'])) {
1098               $args['height'] = 300;
1099          }
1100         
1101          $vars = array();
1102          foreach ($args as $k => $v) {
1103               $vars[] = $k.'='.$v;
1104          }
1105         
1106          return
1107          '<object type="application/x-shockwave-flash" '.
1108          'data="'.$player.'" '.
1109          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1110          '<param name="movie" value="'.$player.'" />'.
1111          '<param name="wmode" value="transparent" />'.
1112          '<param name="allowFullScreen" value="true" />'.
1113          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1114          __('Embedded Video Player').
1115          '</object>';
1116     }
1117}
1118?>
Note: See TracBrowser for help on using the repository browser.

Sites map