Dotclear

source: inc/core/class.dc.media.php @ 2768:9309864ed407

Revision 2768:9309864ed407, 34.2 KB checked in by franck <carnet.franck.paul@…>, 11 years ago (diff)

Cope with given dimensions for video, bugfix (HTML5 audio and video)

RevLine 
[0]1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
[1179]6# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
[0]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
[407]26     protected $postmedia;
[0]27     protected $file_sort = 'name-asc';
[2566]28
[0]29     protected $file_handler = array(); ///< <b>array</b> Array of callbacks
[2566]30
[0]31     public $thumb_tp = '%s/.%s_%s.jpg';     ///< <b>string</b> Thumbnail file pattern
[1381]32     public $thumb_tp_alpha = '%s/.%s_%s.png'; ///< <b>string</b> Thumbnail file pattern (with alpha layer)
[2566]33
[0]34     /**
35     <b>array</b> Tubmnail sizes:
36     - m: medium image
37     - s: small image
38     - t: thumbnail image
39     - sq: square image
40     */
[2566]41     public $thumb_sizes = array(
[0]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     );
[2566]47
[0]48     public $icon_img = 'images/media/%s.png';    ///< <b>string</b> Icon file pattern
[2566]49
[0]50     /**
51     Object constructor.
[2566]52
[0]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;
[407]60          $this->postmedia = new dcPostMedia($core);
[2566]61
[0]62          if ($this->core->blog == null) {
63               throw new Exception(__('No blog defined.'));
64          }
[2566]65
[0]66          $this->table = $this->core->prefix.'media';
67          $root = $this->core->blog->public_path;
[2566]68
[0]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          }
[2566]74
[0]75          if (!is_dir($root)) {
[1705]76               # Check public directory
77               if ( $core->auth->isSuperAdmin() ) {
[1708]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)."));
[1705]79               } else {
[1708]80                    throw new Exception(__("There is no writable root directory for the media manager. You should contact your administrator."));
[1705]81               }
[0]82          }
[2566]83
[0]84          $this->type = $type;
[2566]85
[0]86          parent::__construct($root,$root_url);
87          $this->chdir('');
[2566]88
[0]89          $this->path = $this->core->blog->settings->system->public_path;
[2566]90
[0]91          $this->addExclusion(DC_RC_PATH);
92          $this->addExclusion(dirname(__FILE__).'/../');
[2566]93
[0]94          $this->exclude_pattern = $core->blog->settings->system->media_exclusion;
[2566]95
[0]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'));
[2566]100
[0]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'));
[2566]104
[0]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'));
[2566]108
[0]109          $this->addFileHandler('image/jpeg','create',array($this,'imageMetaCreate'));
[2566]110
[2]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'));
[2566]114
[3]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'));
[2566]118
[0]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);
[2566]123
[0]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]);
[2566]129
[0]130          # --BEHAVIOR-- coreMediaConstruct
[2566]131          $this->core->callBehavior('coreMediaConstruct',$this);
[0]132     }
[2566]133
[0]134     /**
135     Changes working directory.
[2566]136
[0]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     }
[2566]144
[0]145     /**
146     Adds a new file handler for a given media type and event.
[2566]147
[0]148     Available events are:
149     - create: file creation
150     - update: file update
151     - remove: file deletion
[2566]152
[0]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     }
[2566]163
[0]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);
[2566]171
[0]172               foreach ($this->file_handler[$type][$event] as $f)
173               {
174                    call_user_func_array($f,$args);
175               }
176          }
177     }
[2566]178
[0]179     /**
180     Returns HTML breadCrumb for media manager navigation.
[2566]181
[0]182     @param    href      <b>string</b>       URL pattern
[505]183     @param    last      <b>string</b>       Last item pattern
[0]184     @return   <b>string</b> HTML code
185     */
[505]186     public function breadCrumb($href,$last='')
[0]187     {
188          $res = '';
189          if ($this->relpwd && $this->relpwd != '.') {
190               $pwd = '';
[505]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                    }
[0]200               }
201          }
202          return $res;
[2566]203
[0]204     }
[2566]205
[0]206     protected function fileRecord($rs)
207     {
208          if ($rs->isEmpty()) { return null; }
[2566]209
[0]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);
[2566]213
[0]214               if ($this->type && $f->type_prefix != $this->type) {
215                    return null;
216               }
[2566]217
[0]218               $meta = @simplexml_load_string($rs->media_meta);
[2566]219
[0]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);
[2566]228
[0]229               $f->media_image = false;
[2566]230
[0]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               }
[2566]236
[0]237               $type_prefix = explode('/',$f->type);
238               $type_prefix = $type_prefix[0];
[2566]239
[0]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               }
[2566]299
[0]300               $f->media_type = $f->media_icon;
301               $f->media_icon = sprintf($this->icon_img,$f->media_icon);
[2566]302
[0]303               # Thumbnails
304               $f->media_thumb = array();
305               $p = path::info($f->relname);
[1677]306
[1381]307               $alpha = ($p['extension'] == 'png') || ($p['extension'] == 'PNG');
[1677]308
[1381]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');
[2566]311
[0]312               # Cleaner URLs
313               $thumb_url = preg_replace('#\./#','/',$thumb_url);
314               $thumb_url = preg_replace('#(?<!:)/+#','/',$thumb_url);
[1677]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               }
[2566]323
[0]324               foreach ($this->thumb_sizes as $suffix => $s) {
325                    if (file_exists(sprintf($thumb,$suffix))) {
326                         $f->media_thumb[$suffix] = sprintf($thumb_url,$suffix);
[1677]327                    } elseif ($alpha && file_exists(sprintf($thumb_alt,$suffix))) {
328                         $f->media_thumb[$suffix] = sprintf($thumb_url_alt,$suffix);
[0]329                    }
330               }
[2566]331
[0]332               if (isset($f->media_thumb['sq']) && $f->media_type == 'image') {
333                    $f->media_icon = $f->media_thumb['sq'];
334               }
[2566]335
[0]336               return $f;
337          }
[2566]338
[0]339          return null;
340     }
[2566]341
342
[0]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     }
[2566]349
[0]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          }
[2566]370
[0]371     }
[2098]372
373     /**
374     Gets current working directory content (using filesystem)
375
376     */
377     public function getFSDir()
378     {
379          parent::getDir();
380     }
381
[0]382     /**
[2566]383     Gets current working directory content.
384
[0]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          }
[2566]392
[0]393          $media_dir = $this->relpwd ? $this->relpwd : '.';
[2566]394
[0]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)."' ";
[2566]401
[0]402          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
403          {
404               $strReq .= 'AND (media_private <> 1 ';
[2566]405
[0]406               if ($this->core->auth->userID()) {
407                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
408               }
409               $strReq .= ') ';
410          }
[2566]411
[0]412          $rs = $this->con->select($strReq);
[2566]413
[0]414          parent::getDir();
[2566]415
[0]416          $f_res = array();
417          $p_dir = $this->dir;
[2566]418
[0]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          }
[2566]428
[0]429          $f_reg = array();
[2566]430
[0]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               }
[2566]437
[0]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                         {
[2566]444                              # That media is duplicated in the database,
[0]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          }
[2566]470
[0]471          $this->dir['files'] = $f_res;
472          foreach ($this->dir['dirs'] as $k => $v) {
[1855]473               $v->media_icon = sprintf($this->icon_img,($v->parent ? 'folder-up' : 'folder'));
[0]474          }
[2566]475
[0]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     }
[2566]490
[0]491     /**
492     Gets file by its id. Returns a filteItem object.
[2566]493
[0]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.' ';
[2566]506
[0]507          if (!$this->core->auth->check('media_admin',$this->core->blog->id))
508          {
509               $strReq .= 'AND (media_private <> 1 ';
[2566]510
[0]511               if ($this->core->auth->userID()) {
512                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
513               }
514               $strReq .= ') ';
515          }
[2566]516
[0]517          $rs = $this->con->select($strReq);
518          return $this->fileRecord($rs);
519     }
[2566]520
[0]521     /**
522     Returns media items attached to a blog post. Result is an array containing
523     fileItems objects.
[2566]524
[0]525     @param    post_id   <b>integer</b>      Post ID
526     @param    media_id  <b>integer</b>      Optionnal media ID
[1280]527     @return   <b>array</b> Array of fileItems
[0]528     */
[1280]529     public function getPostMedia($post_id,$media_id=null)
[0]530     {
[407]531          $params = array(
532               'post_id' => $post_id,
533               'media_path' => $this->path
534          );
[0]535          if ($media_id) {
[407]536               $params['media_id'] = (integer) $media_id;
[0]537          }
[407]538          $rs = $this->postmedia->getPostMedia($params);
[2566]539
[0]540          $res = array();
[2566]541
[0]542          while ($rs->fetch()) {
543               $f = $this->fileRecord($rs);
544               if ($f !== null) {
[1280]545                    $res[] = $f;
[0]546               }
547          }
[2566]548
[1280]549          return $res;
[0]550     }
[2566]551
[0]552     /**
[407]553     @deprecated since version 2.4
554     @see dcPostMedia::addPostMedia
[0]555     */
556     public function addPostMedia($post_id,$media_id)
557     {
[407]558          $this->postmedia->addPostMedia($post_id,$media_id);
[0]559     }
[2566]560
[0]561     /**
[407]562     @deprecated since version 2.4
563     @see dcPostMedia::removePostMedia
[0]564     */
565     public function removePostMedia($post_id,$media_id)
566     {
[407]567          $this->postmedia->removePostMedia($post_id,$media_id,"attachment");
[0]568     }
[2566]569
[0]570     /**
571     Rebuilds database items collection. Optional <var>$pwd</var> parameter is
572     the path where to start rebuild.
[2566]573
[0]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          }
[2566]581
[0]582          $this->chdir($pwd);
583          parent::getDir();
[2566]584
[0]585          $dir = $this->dir;
[2566]586
[0]587          foreach ($dir['dirs'] as $d) {
588               if (!$d->parent) {
589                    $this->rebuild($d->relname,false);
590               }
591          }
[2566]592
[0]593          foreach ($dir['files'] as $f) {
594               $this->chdir(dirname($f->relname));
595               $this->createFile($f->basename);
596          }
[2566]597
[0]598          $this->rebuildDB($pwd);
599     }
[2566]600
[0]601     protected function rebuildDB($pwd)
602     {
603          $media_dir = $pwd ? $pwd : '.';
[2566]604
[0]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)."' ";
[2566]610
[0]611          $rs = $this->con->select($strReq);
[2566]612
[0]613          $delReq = 'DELETE FROM '.$this->table.' '.
614                    'WHERE media_id IN (%s) ';
615          $del_ids = array();
[2566]616
[0]617          while ($rs->fetch())
618          {
619               if (!is_file($this->root.'/'.$rs->media_file)) {
620                    $del_ids[] = (integer) $rs->media_id;
621               }
622          }
[2566]623
[0]624          if (!empty($del_ids)) {
625               $this->con->execute(sprintf($delReq,implode(',',$del_ids)));
626          }
627     }
[2566]628
[0]629     public function makeDir($d)
630     {
631          $d = files::tidyFileName($d);
632          parent::makeDir($d);
633     }
[2566]634
[0]635     /**
636     Creates or updates a file in database. Returns new media ID or false if
637     file does not exist.
[2566]638
[0]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          }
[2566]650
[0]651          $file = $this->pwd.'/'.$name;
652          if (!file_exists($file)) {
653               return false;
654          }
[2566]655
[0]656          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$name) : path::clean($name);
657          $media_type = files::getMimeType($name);
[2566]658
[0]659          $cur = $this->con->openCursor($this->table);
[2566]660
[0]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)."' ";
[2566]665
[0]666          $rs = $this->con->select($strReq);
[2566]667
[0]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;
[2566]675
[0]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');
[2566]683
[0]684                    $cur->media_title = !$title ? (string) $name : (string) $title;
685                    $cur->media_private = (integer) (boolean) $private;
[2566]686
[0]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                    }
[2566]692
[0]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;
[2566]710
[0]711               $cur->media_upddt = date('Y-m-d H:i:s');
[2566]712
[0]713               $cur->update('WHERE media_id = '.$media_id);
714          }
[2566]715
[0]716          $this->callFileHandler($media_type,'create',$cur,$name,$media_id,$force);
[2566]717
[0]718          return $media_id;
719     }
[2566]720
[0]721     /**
722     Updates a file in database.
[2566]723
[0]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          }
[2566]732
[0]733          $id = (integer) $file->media_id;
[2566]734
[0]735          if (!$id) {
736               throw new Exception('No file ID');
737          }
[2566]738
[0]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          }
[2566]743
[0]744          $cur = $this->con->openCursor($this->table);
[2566]745
[0]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          }
[2566]751
[0]752          if ($file->relname != $newFile->relname) {
753               $newFile->file = $this->root.'/'.$newFile->relname;
[2566]754
[0]755               if ($this->isFileExclude($newFile->relname)) {
756                    throw new Exception(__('This file is not allowed.'));
757               }
[2566]758
[0]759               if (file_exists($newFile->file)) {
760                    throw new Exception(__('New file already exists.'));
761               }
[2566]762
[0]763               $this->moveFile($file->relname,$newFile->relname);
[2566]764
[0]765               $cur->media_file = (string) $newFile->relname;
766               $cur->media_dir = (string) dirname($newFile->relname);
767          }
[2566]768
[0]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;
[2566]773
[0]774          $cur->update('WHERE media_id = '.$id);
[2566]775
[0]776          $this->callFileHandler($file->type,'update',$file,$newFile);
777     }
[2566]778
[0]779     /**
780     Uploads a file.
[2566]781
[0]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          }
[2566]792
[0]793          $name = files::tidyFileName($name);
[2566]794
[0]795          parent::uploadFile($tmp,$name,$overwrite);
[2566]796
[0]797          return $this->createFile($name,$title,$private);
798     }
[2566]799
[0]800     /**
801     Creates a file from binary content.
[2566]802
[0]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          }
[2566]811
[0]812          $name = files::tidyFileName($name);
[2566]813
[0]814          parent::uploadBits($name,$bits);
[2566]815
[0]816          return $this->createFile($name,null,null);
817     }
[2566]818
[0]819     /**
820     Removes a file.
[2566]821
[0]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          }
[2566]829
[0]830          $media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$f) : path::clean($f);
[2566]831
[0]832          $strReq = 'DELETE FROM '.$this->table.' '.
833                    "WHERE media_path = '".$this->con->escape($this->path)."' ".
834                    "AND media_file = '".$this->con->escape($media_file)."' ";
[2566]835
[0]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          }
[2566]840
[0]841          $this->con->execute($strReq);
[2566]842
[0]843          if ($this->con->changes() == 0) {
844               throw new Exception(__('File does not exist in the database.'));
845          }
[2566]846
[0]847          parent::removeFile($f);
[2566]848
[0]849          $this->callFileHandler(files::getMimeType($media_file),'remove',$f);
850     }
[1103]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 : '.';
[2566]863
[1103]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))
[1123]871                    $dir[] = ($rs->media_dir == '.' ? '' : $rs->media_dir);
[1103]872          }
[2566]873
[1103]874          return $dir;
875     }
[2566]876
[0]877     /**
878     Extract zip file in current location
[2566]879
[0]880     @param    f         <b>fileRecord</b>   fileRecord object
881     */
882     public function inflateZipFile($f,$create_dir=true)
883     {
884          $zip = new fileUnzip($f->file);
[705]885          $zip->setExcludePattern($this->exclude_pattern);
[0]886          $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
[2566]887
[0]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               }
[2566]898
[0]899               if (is_dir($f->dir.'/'.$destination)) {
[2566]900                    throw new Exception(sprintf(__('Extract destination directory %s already exists.'),dirname($f->relname).'/'.$destination));
[0]901               }
902          }
903          else
904          {
905               $target = $f->dir;
906               $destination = '';
907          }
[2566]908
[0]909          $zip->unzipAll($target);
910          $zip->close();
911          return dirname($f->relname).'/'.$destination;
912     }
[2566]913
[0]914     /**
915     Returns zip file content
[2566]916
[0]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     }
[2]927
928     /**
929     Calls file handlers registered for recreate event
[2566]930
[2]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     }
[2566]938
[0]939     /* Image handlers
940     ------------------------------------------------------- */
[3]941     public function imageThumbCreate($cur,$f,$force=true)
[0]942     {
943          $file = $this->pwd.'/'.$f;
[2566]944
[0]945          if (!file_exists($file)) {
946               return false;
947          }
[2566]948
[0]949          $p = path::info($file);
[1381]950          $alpha = ($p['extension'] == 'png') || ($p['extension'] == 'PNG');
951          $thumb = sprintf(($alpha ? $this->thumb_tp_alpha : $this->thumb_tp),$p['dirname'],$p['base'],'%s');
[2566]952
[0]953          try
954          {
955               $img = new imageTools();
956               $img->loadImage($file);
[2566]957
[0]958               $w = $img->getW();
959               $h = $img->getH();
[2566]960
[0]961               if ($force) $this->imageThumbRemove($f);
[2566]962
[0]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                    {
[909]968                         $rate = ($s[0] < 100 ? 95 : ($s[0] < 600 ? 90 : 85));
[0]969                         $img->resize($s[0],$s[0],$s[1]);
[1381]970                         $img->output(($alpha ? 'png' : 'jpeg'),$thumb_file,$rate);
[1120]971                         $img->loadImage($file);
[0]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     }
[2566]983
[397]984     protected function imageThumbUpdate($file,$newFile)
[0]985     {
986          if ($file->relname != $newFile->relname)
987          {
988               $p = path::info($file->relname);
[1381]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');
[2566]991
[0]992               $p = path::info($newFile->relname);
[1381]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');
[2566]995
[0]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     }
[2566]1003
[2659]1004     public function imageThumbRemove($f)
[0]1005     {
1006          $p = path::info($f);
[1381]1007          $alpha = ($p['extension'] == 'png') || ($p['extension'] == 'PNG');
1008          $thumb = sprintf(($alpha ? $this->thumb_tp_alpha : $this->thumb_tp),'',$p['base'],'%s');
[2566]1009
[0]1010          foreach ($this->thumb_sizes as $suffix => $s) {
1011               try {
1012                    parent::removeFile(sprintf($thumb,$suffix));
1013               } catch (Exception $e) {}
1014          }
1015     }
[2566]1016
[0]1017     protected function imageMetaCreate($cur,$f,$id)
1018     {
1019          $file = $this->pwd.'/'.$f;
[2566]1020
[0]1021          if (!file_exists($file)) {
1022               return false;
1023          }
[2566]1024
[0]1025          $xml = new xmlTag('meta');
1026          $meta = imageMeta::readMeta($file);
1027          $xml->insertNode($meta);
[2566]1028
[0]1029          $c = $this->core->con->openCursor($this->table);
1030          $c->media_meta = $xml->toXML();
[2566]1031
[0]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          }
[2566]1038
[0]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          }
[2566]1048
[0]1049          $c->update('WHERE media_id = '.$id);
1050     }
[2566]1051
[0]1052     /**
[2767]1053     Returns HTML code for audio player (HTML5 and if possible fallback Flash player)
1054
1055     @param  type   <b>string</b>       audio mime type
1056     @param    url       <b>string</b>       audio URL to play
1057     @param    player    <b>string</b>       Player URL (flash player fallback)
1058     @param    args <b>array</b>        Player parameters (flash player fallback)
1059     @return   <b>string</b>
1060     */
1061     public static function audioPlayer($type,$url,$player=null,$args=null)
1062     {
1063          $audio =
[2768]1064               '<audio controls preload="auto">'.
1065               '<source src="'.$url.'">';
[2767]1066
1067          if ($type == 'audio/mpeg3') {
1068               // Include Flash player fallback
1069               if (!$player) {
1070                    $player = 'player_mp3.swf';
1071               }
1072
1073               if (!is_array($args))
1074               {
1075                    $args = array(
1076                         'showvolume' => 1,
1077                         'loadingcolor' => 'ff9900',
1078                         'bgcolor1' => 'eeeeee',
1079                         'bgcolor2' => 'cccccc',
1080                         'buttoncolor' => '0066cc',
1081                         'buttonovercolor' => 'ff9900',
1082                         'slidercolor1' => 'cccccc',
1083                         'slidercolor2' => '999999',
1084                         'sliderovercolor' => '0066cc'
1085                    );
1086               }
1087
1088               $args['mp3'] = $url;
1089
1090               if (empty($args['width'])) {
1091                    $args['width'] = 200;
1092               }
1093               if (empty($args['height'])) {
1094                    $args['height'] = 20;
1095               }
1096
1097               $vars = array();
1098               foreach ($args as $k => $v) {
1099                    $vars[] = $k.'='.$v;
1100               }
1101
1102               $audio .=
1103                    '<object type="application/x-shockwave-flash" '.
1104                    'data="'.$player.'" '.
1105                    'width="'.$args['width'].'" height="'.$args['height'].'">'.
1106                    '<param name="movie" value="'.$player.'" />'.
1107                    '<param name="wmode" value="transparent" />'.
1108                    '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1109                    __('Embedded Audio Player').
[2768]1110                    '</object>';
[2767]1111          }
1112
1113          $audio .=
[2768]1114               '</audio>';
[2767]1115
1116          return $audio;
1117     }
1118
1119     /**
1120     Returns HTML code for video player (HTML5 and if possible fallback Flash player)
1121
1122     @param  type   <b>string</b>       video mime type
1123     @param    url       <b>string</b>       video URL to play
1124     @param    player    <b>string</b>       Player URL (flash player fallback)
1125     @param    args <b>array</b>        Player parameters (flash player fallback)
1126     @return   <b>string</b>
1127     */
1128     public static function videoPlayer($type,$url,$player=null,$args=null)
1129     {
1130          $video = '';
[2768]1131
1132          // Cope with width and height, if given
1133          $width = 400;
1134          $height = 300;
1135          if (is_array($args)) {
1136               if (!empty($args['width']) && $args['width']) {
1137                    $width = (int) $args['width'];
1138               }
1139               if (!empty($args['height']) && $args['height']) {
1140                    $height = (int) $args['height'];
1141               }
1142          }
1143
[2767]1144          if ($type != 'video/x-flv') {
1145               $video =
[2768]1146                    '<video controls preload="auto"'.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'>'.
1147                    '<source src="'.$url.'">';
[2767]1148          }
1149
1150          if ($type == 'video/x-flv' || $type == 'video/mp4' || $type == 'video/x-m4v')
1151          {
1152               // Include Flash player fallback
1153               if (!$player) {
1154                    $player = 'player_flv.swf';
1155               }
1156
1157               if (!is_array($args))
1158               {
1159                    $args = array(
1160                         'margin' => 1,
1161                         'showvolume' => 1,
1162                         'showtime' => 1,
1163                         'showfullscreen' => 1,
1164                         'buttonovercolor' => 'ff9900',
1165                         'slidercolor1' => 'cccccc',
1166                         'slidercolor2' => '999999',
1167                         'sliderovercolor' => '0066cc'
1168                    );
1169               }
1170
1171               $args['flv'] = $url;
1172
1173               if (empty($args['width'])) {
1174                    $args['width'] = 400;
1175               }
1176               if (empty($args['height'])) {
1177                    $args['height'] = 300;
1178               }
1179
1180               $vars = array();
1181               foreach ($args as $k => $v) {
1182                    $vars[] = $k.'='.$v;
1183               }
1184
1185               $video .=
1186                    '<object type="application/x-shockwave-flash" '.
1187                    'data="'.$player.'" '.
1188                    'width="'.$args['width'].'" height="'.$args['height'].'">'.
1189                    '<param name="movie" value="'.$player.'" />'.
1190                    '<param name="wmode" value="transparent" />'.
1191                    '<param name="allowFullScreen" value="true" />'.
1192                    '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1193                    __('Embedded Video Player').
[2768]1194                    '</object>';
[2767]1195          }
1196
1197          if ($type != 'video/x-flv') {
1198               $video .=
[2768]1199                    '</video>';
[2767]1200          }
1201
1202          return $video;
1203     }
1204
1205     /**
[0]1206     Returns HTML code for MP3 player
[2566]1207
[0]1208     @param    url       <b>string</b>       MP3 URL to play
1209     @param    player    <b>string</b>       Player URL
1210     @param    args      <b>array</b>        Player parameters
1211     @return   <b>string</b>
1212     */
1213     public static function mp3player($url,$player=null,$args=null)
1214     {
1215          if (!$player) {
1216               $player = 'player_mp3.swf';
1217          }
[2566]1218
[0]1219          if (!is_array($args))
1220          {
1221               $args = array(
1222                    'showvolume' => 1,
1223                    'loadingcolor' => 'ff9900',
1224                    'bgcolor1' => 'eeeeee',
1225                    'bgcolor2' => 'cccccc',
1226                    'buttoncolor' => '0066cc',
1227                    'buttonovercolor' => 'ff9900',
1228                    'slidercolor1' => 'cccccc',
1229                    'slidercolor2' => '999999',
1230                    'sliderovercolor' => '0066cc'
1231               );
1232          }
[2566]1233
[0]1234          $args['mp3'] = $url;
[2566]1235
[0]1236          if (empty($args['width'])) {
1237               $args['width'] = 200;
1238          }
1239          if (empty($args['height'])) {
1240               $args['height'] = 20;
1241          }
[2566]1242
[0]1243          $vars = array();
1244          foreach ($args as $k => $v) {
1245               $vars[] = $k.'='.$v;
1246          }
[2566]1247
[0]1248          return
[2763]1249          '<audio controls preload="auto">'.
1250          '<source src="'.$url.'" type="audio/mpeg">'.
[0]1251          '<object type="application/x-shockwave-flash" '.
1252          'data="'.$player.'" '.
1253          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1254          '<param name="movie" value="'.$player.'" />'.
1255          '<param name="wmode" value="transparent" />'.
1256          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1257          __('Embedded Audio Player').
[2763]1258          '</object>'.
1259          '</audio>';
[0]1260     }
[2566]1261
[2767]1262     /**
1263     Returns HTML code for FLV player
1264
1265     @param    url       <b>string</b>       FLV URL to play
1266     @param    player    <b>string</b>       Player URL
1267     @param    args      <b>array</b>        Player parameters
1268     @return   <b>string</b>
1269     */
[0]1270     public static function flvplayer($url,$player=null,$args=null)
1271     {
1272          if (!$player) {
1273               $player = 'player_flv.swf';
1274          }
[2566]1275
[0]1276          if (!is_array($args))
1277          {
1278               $args = array(
1279                    'margin' => 1,
1280                    'showvolume' => 1,
1281                    'showtime' => 1,
1282                    'showfullscreen' => 1,
1283                    'buttonovercolor' => 'ff9900',
1284                    'slidercolor1' => 'cccccc',
1285                    'slidercolor2' => '999999',
1286                    'sliderovercolor' => '0066cc'
1287               );
1288          }
[2566]1289
[0]1290          $args['flv'] = $url;
[2566]1291
[0]1292          if (empty($args['width'])) {
1293               $args['width'] = 400;
1294          }
1295          if (empty($args['height'])) {
1296               $args['height'] = 300;
1297          }
[2566]1298
[0]1299          $vars = array();
1300          foreach ($args as $k => $v) {
1301               $vars[] = $k.'='.$v;
1302          }
[2566]1303
[0]1304          return
1305          '<object type="application/x-shockwave-flash" '.
1306          'data="'.$player.'" '.
1307          'width="'.$args['width'].'" height="'.$args['height'].'">'.
1308          '<param name="movie" value="'.$player.'" />'.
1309          '<param name="wmode" value="transparent" />'.
1310          '<param name="allowFullScreen" value="true" />'.
1311          '<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
1312          __('Embedded Video Player').
1313          '</object>';
1314     }
1315}
Note: See TracBrowser for help on using the repository browser.

Sites map