Dotclear

source: inc/core/class.dc.media.php @ 2098:71c521832a9e

Revision 2098:71c521832a9e, 30.6 KB checked in by franck <carnet.franck.paul@…>, 12 years ago (diff)

Add parent and child directories of potential destination folder's list in media-item.php, (dirty) fixes #1390.

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

Sites map