[ Index ]
 

Code source de LifeType 1.2.4

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/class/gallery/dao/ -> galleryresources.class.php (source)

   1  <?php
   2  
   3      /**
   4       * \defgroup Gallery
   5       *
   6       * The pLog Gallery module encapsulates all the logic necessary for:
   7       *
   8       * - Dealing with files and their places in disk
   9       * - Dealing with albums, which are virtual groups of disks
  10       * - Automatic generation of thumbnails and medium-sized thumbnails, according to our configuration
  11       * - Automatic extraction of metadata from a set of supported formats. This is achieved
  12       * via the getID3 library.
  13       */
  14  
  15      lt_include( PLOG_CLASS_PATH."class/dao/model.class.php" );
  16      lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresource.class.php" );
  17      lt_include( PLOG_CLASS_PATH."class/gallery/galleryconstants.php" );
  18      lt_include( PLOG_CLASS_PATH.'class/dao/daocacheconstants.properties.php' );
  19  
  20      /**
  21       * \ingroup Gallery
  22       * 
  23       * database access for GalleryResource objects. Provides methods for adding, retrieving, updating and removing
  24       * resources from the database
  25       *
  26       * @see Model
  27       * @see GalleryResource 
  28       */
  29      class GalleryResources extends Model
  30      {
  31          var $albums;
  32  
  33          /**
  34           * maps extensions to resource types
  35           */
  36         var $_extensionToType = Array(
  37             "jpg" => GALLERY_RESOURCE_IMAGE,
  38          "jpeg" => GALLERY_RESOURCE_IMAGE,
  39          "png" => GALLERY_RESOURCE_IMAGE,
  40          "gif" => GALLERY_RESOURCE_IMAGE,
  41          "bmp" => GALLERY_RESOURCE_IMAGE,
  42          "mp3" => GALLERY_RESOURCE_SOUND,
  43          "mp2" => GALLERY_RESOURCE_SOUND,
  44          "wav" => GALLERY_RESOURCE_SOUND,
  45          "au" => GALLERY_RESOURCE_SOUND,
  46          "aac" => GALLERY_RESOURCE_SOUND,
  47          "mp4" => GALLERY_RESOURCE_SOUND,
  48          "m4a" => GALLERY_RESOURCE_SOUND,
  49          "aac" => GALLERY_RESOURCE_SOUND,
  50          "m4p" => GALLERY_RESOURCE_SOUND,
  51          "wma" => GALLERY_RESOURCE_SOUND,
  52          "ogg" => GALLERY_RESOURCE_SOUND,
  53          "mod" => GALLERY_RESOURCE_SOUND,
  54          "mid" => GALLERY_RESOURCE_SOUND,
  55          "midi" => GALLERY_RESOURCE_SOUND,
  56          "avi" => GALLERY_RESOURCE_VIDEO,
  57          "mpg" => GALLERY_RESOURCE_VIDEO,
  58          "mpeg" => GALLERY_RESOURCE_VIDEO,
  59          "wmv" => GALLERY_RESOURCE_VIDEO,
  60          //"asf" => GALLERY_RESOURCE_VIDEO,
  61          "mov" => GALLERY_RESOURCE_VIDEO,
  62          "divx" => GALLERY_RESOURCE_VIDEO,
  63          "rm" => GALLERY_RESOURCE_VIDEO,
  64          "swf" => GALLERY_RESOURCE_VIDEO,
  65          "flv" => GALLERY_RESOURCE_VIDEO,
  66          "qt" => GALLERY_RESOURCE_VIDEO,
  67          "pdf" => GALLERY_RESOURCE_DOCUMENT,
  68          "zip" => GALLERY_RESOURCE_ZIP
  69         );
  70  
  71      	function GalleryResources()
  72          {
  73              $this->Model();            
  74              $this->table = $this->getPrefix()."gallery_resources";
  75          }
  76  
  77          /**
  78           * Fetches GalleryResource objects from the database
  79           *
  80           * @param resourceId The id of the resource we'd like to fetch
  81           * @param ownerId Optional, the id of the owner
  82           * @param albumId Optional, the id of the album to which this resoruce should belong
  83           * @return Returns a GalleryResource object representing the resource
  84           */
  85          function getResource( $resourceId, $ownerId = -1, $albumId = -1 )
  86          {
  87              $resource = $this->get( "id", $resourceId, CACHE_RESOURCES );
  88  
  89              if( !$resource )            
  90                  return false;
  91              if( !$this->check( $resource, $ownerId, $albumId ))
  92                  return false;
  93  
  94              return $resource;
  95          }
  96          
  97          /**
  98           * given a resource id, tries to find the next one in the sequence
  99           *
 100           * @param resource A GalleryResource object that represents the resource whose next
 101           * object we'd like to load
 102           * @return Returns a GalleryResource object representing the next resource, or false
 103           * if there was no next resource
 104           */         
 105  		function getNextResource( $resource )
 106          {        
 107              $prefix = $this->getPrefix();
 108              $albumId = $resource->getAlbumId();
 109              $date = $resource->getDate();
 110              $id = $resource->getId();
 111              $query = "SELECT id, owner_id, album_id, description,
 112                               date, flags, resource_type, file_path, file_name,
 113                               metadata, thumbnail_format, properties, file_size
 114                        FROM {$prefix}gallery_resources 
 115                        WHERE album_id = '$albumId' AND date >= '$date' AND id > $id
 116                        ORDER BY date ASC,id ASC LIMIT 1";
 117  
 118              $result = $this->Execute( $query );
 119              
 120              if( !$result )
 121                  return false;
 122              if( $result->RecordCount() == 0 ){
 123                  $result->Close();
 124                  return false;
 125              }
 126                  
 127              $row = $result->FetchRow();
 128              $result->Close();
 129              $resource = $this->mapRow( $row );
 130              
 131              $this->_cache->setData( $resource->getId(), CACHE_RESOURCES, $resource );
 132              $this->_cache->setData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME, $resource );            
 133              
 134              return $resource;
 135          }
 136  
 137          /**
 138           * given a resource id, tries to find the previus one in the sequence
 139           *
 140           * @param resource A GalleryResource object that represents the resource whose next
 141           * object we'd like to load
 142           * @return Returns a GalleryResource object representing the previous resource, or false
 143           * if there was no previous resource
 144           */                 
 145  		function getPreviousResource( $resource )
 146          {
 147              $prefix = $this->getPrefix();
 148              $albumId = $resource->getAlbumId();
 149              $date = $resource->getDate();
 150              $id = $resource->getId();
 151              $query = "SELECT id, owner_id, album_id, description,
 152                               date, flags, resource_type, file_path, file_name,
 153                               metadata, thumbnail_format, properties, file_size
 154                        FROM {$prefix}gallery_resources 
 155                        WHERE album_id = '$albumId' AND date <= '$date' AND id < $id
 156                        ORDER BY date DESC,id DESC LIMIT 1";
 157  
 158              $result = $this->Execute( $query );
 159              
 160              if( !$result )
 161                  return false;
 162              if( $result->RecordCount() == 0 ){
 163                  $result->Close();
 164                  return false;
 165              }
 166                  
 167              $row = $result->FetchRow();
 168              $result->Close();
 169              $resource = $this->mapRow( $row );
 170              
 171              $this->_cache->setData( $resource->getId(), CACHE_RESOURCES, $resource );
 172              $this->_cache->setData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME, $resource );            
 173              
 174              return $resource;        
 175          }
 176  
 177          /**
 178           * Returns all the resources that belong to a blog
 179           *
 180           * @param blogId The blog to which the resources belong, use -1 to indicate any blog/owner
 181           * @param albumId Filters by album
 182           * @param page
 183           * @param itemsPerPage
 184           * @param searchTerms
 185           * @return Returns an array of GalleryResource objects with all
 186           * the resources that match the given conditions, or empty
 187           * if none could be found.
 188           */
 189          function getUserResources( $ownerId, 
 190                                     $albumId = GALLERY_NO_ALBUM, 
 191                                     $resourceType = GALLERY_RESOURCE_ANY,
 192                                     $searchTerms = "",
 193                                     $page = DEFAULT_PAGING_ENABLED, 
 194                                     $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
 195          {
 196  
 197              $resources = Array();
 198              $query = "SELECT id FROM ".$this->getPrefix()."gallery_resources WHERE "; 
 199              if( $ownerId != -1 )
 200                  $query .= " owner_id = '".Db::qstr($ownerId)."' AND";
 201              if( $albumId != GALLERY_NO_ALBUM )
 202                  $query .= " album_id = '".Db::qstr($albumId)."' AND";
 203              if( $resourceType != GALLERY_RESOURCE_ANY )
 204                  $query .= " resource_type = '".Db::qstr($resourceType)."' AND";
 205              if( $searchTerms != "" )
 206                  $query .= " (".$this->getSearchConditions( $searchTerms ).")";
 207              
 208                  // just in case if for any reason the string ends with "AND"
 209              $query = trim( $query );
 210              if( substr( $query, -3, 3 ) == "AND" )
 211                  $query = substr( $query, 0, strlen( $query ) - 3 );
 212              
 213              $result = $this->Execute( $query, $page, $itemsPerPage );
 214              if( !$result )
 215                  return $resources;
 216              
 217              while( $row = $result->FetchRow()) {
 218                      // use the primary key to retrieve the items via the cache
 219                  $resources[] = $resource = $this->get( "id", $row["id"], CACHE_RESOURCES );
 220              }
 221              
 222              return $resources;
 223          }
 224          
 225          /**
 226           * @private
 227           */
 228          function check( $resource, 
 229                          $ownerId = -1, 
 230                          $albumId = GALLERY_NO_ALBUM, 
 231                          $resourceType = GALLERY_RESOURCE_ANY )
 232          {
 233              if( $ownerId != -1 && $ownerId != '_all_' ) {
 234                  if( $resource->getOwnerId() != $ownerId ) {
 235                      return false;
 236                  }
 237              }
 238              if( $albumId != GALLERY_NO_ALBUM ) {
 239                     if( $resource->getAlbumId() != $albumId ) {
 240                         return false;
 241                  }
 242                 }
 243                 if( $resourceType != GALLERY_RESOURCE_ANY ) {        
 244                     if( $resource->getResourceType() != $resourceType )
 245                         return false;
 246                 }
 247              
 248                 return( true );
 249          }
 250          
 251          /**
 252           * returns the number of items given certain conditions
 253           *
 254           * @param ownerId The id of the user whose amount of albums we'd like to check
 255           * @param albumId Optional, the id of the album, in case we'd only like to know the number of resources in a certain album.
 256           * use the constant GALLERY_NO_ALBUM to disable this parameter
 257           * @param resourceType An additional filter parameter, so that we can only count a certain type of resources.
 258           * Defaults to the constant GALLERY_RESOURCE_ANY
 259           * @param searchTerms
 260           * @see getUserResources
 261           * @return the total number of items
 262           */
 263  		function getNumUserResources( $ownerId, $albumId = GALLERY_NO_ALBUM, $resourceType = GALLERY_RESOURCE_ANY, $searchTerms = "" )
 264          {
 265              $prefix = $this->getPrefix();
 266              $table  = "{$prefix}gallery_resources";
 267              
 268              $cond = "";
 269              if( $ownerId != -1 )
 270                  $cond = "owner_id = '".Db::qstr( $ownerId )."'";
 271              else
 272                  $cond = "owner_id = owner_id ";
 273              
 274              if( $albumId > GALLERY_NO_ALBUM )
 275                  $cond .= "AND album_id = '".Db::qstr($albumId)."'";
 276              if( $resourceType > GALLERY_RESOURCE_ANY )
 277                  $cond .= " AND resource_type = '".Db::qstr($resourceType)."'";
 278              if( $searchTerms != "" ) {
 279                  $searchParams = $this->getSearchConditions( $searchTerms );
 280                  $cond .= " AND (".$searchParams.")";
 281              }
 282  
 283                  // return the number of items
 284              return( $this->getNumItems( $table, $cond ));
 285          }
 286  
 287          /**
 288           * Adds a row related to a resource to the database. You should usually use
 289           * GalleryResources::addResource() or GalleryResources::addResourceFromDisk(), which are more
 290           * suitable and will do most of the job for you.
 291           *
 292           * @param ownerId
 293           * @param albumId
 294           * @param description
 295           * @param flags
 296           * @param resourceType
 297           * @param filePath
 298           * @param fileName
 299           * @param metadata
 300           * @return a valid resource id or false otherwise
 301           * @see addResource
 302           */
 303  		function addResourceToDatabase( $ownerId, $albumId, $description, $flags, $resourceType, 
 304                                              $filePath, $fileName, $metadata )
 305          {
 306              // prepare the metadata to be stored in the db
 307              $fileSize = $metadata["filesize"];
 308              $serMetadata = Db::qstr( serialize($metadata));
 309              // get the correct thumbnail format
 310              lt_include( PLOG_CLASS_PATH."class/config/config.class.php" );
 311              $config =& Config::getConfig();
 312              $thumbnailFormat = $config->getValue( "thumbnail_format" );
 313              // prepare some other stuff
 314              lt_include( PLOG_CLASS_PATH."class/data/textfilter.class.php" );            
 315              $tf = new Textfilter();
 316              $normalizedDescription = $tf->normalizeText( $description );
 317              $properties = serialize( array() );
 318              
 319              // check if there already is a file with the same name stored
 320              $duplicated = $this->isDuplicatedFileName( $fileName );
 321  
 322              // finally put the query together and execute it
 323              $query = "INSERT INTO ".$this->getPrefix()."gallery_resources(
 324                            owner_id, album_id, description, flags, resource_type,
 325                            file_path, file_name, file_size, metadata, thumbnail_format, normalized_description, properties) 
 326                            VALUES (
 327                            $ownerId, $albumId, '".Db::qstr($description)."', $flags, $resourceType,
 328                            '$filePath', '".Db::qstr($fileName)."', '$fileSize', '$serMetadata', '$thumbnailFormat',
 329                    '".Db::qstr($normalizedDescription)."', '$properties');";
 330                            
 331              $result = $this->Execute( $query );
 332  
 333              // check the return result
 334              if( !$result )
 335                  return GALLERY_ERROR_ADDING_RESOURCE;        
 336  
 337              // get the id that was given to the record
 338              $resourceId = $this->_db->Insert_ID();
 339  
 340              // check if we have two resources with the same filename now
 341              // check if there already exists a file with the same name
 342              //
 343              // if that's the case, then we should rename the one we just
 344              // added with some random prefix, to make it different from the
 345              // other one...
 346              if( $duplicated ) {
 347                  $query = "UPDATE ".$this->getPrefix()."gallery_resources
 348                            SET file_name = '$resourceId-$fileName'
 349                            WHERE id = $resourceId";
 350  
 351                  $this->Execute( $query );
 352              }
 353              
 354              // clear our own caches
 355              $this->_cache->removeData( $resourceId, CACHE_RESOURCES );
 356              $this->_cache->removeData( $ownerId, CACHE_RESOURCES_USER );
 357              $this->_cache->removeData( $fileName, CACHE_RESOURCES_BY_NAME );            
 358          
 359              return $resourceId;    
 360          }    
 361          
 362          /**
 363           * @private
 364           * @param fileName
 365           * @param metadata
 366           */
 367  		function _getResourceType( $fileName, &$metadata )
 368          {
 369                // find out the right resource type based on the extension
 370              // get the resource type
 371              $fileParts = explode( ".", $fileName );
 372              $fileExt = strtolower($fileParts[count($fileParts)-1]);
 373              
 374              //asf need special working
 375              if ("asf" == $fileExt ){             
 376                  if (!($metadata["audio"]["codec"]))                            
 377                      $resourceType = GALLERY_RESOURCE_SOUND;
 378                  else 
 379                      $resourceType = GALLERY_RESOURCE_VIDEO;
 380               }           
 381                else {
 382                  if( array_key_exists( $fileExt, $this->_extensionToType ))
 383                          $resourceType = $this->_extensionToType[ $fileExt ];
 384                   else
 385                      $resourceType = GALLERY_RESOURCE_UNKNOWN;
 386              }
 387              
 388              return( $resourceType );                    
 389          }
 390  
 391          /**
 392           * adds a resource to the database. This method requires a FileUpload parameter and it
 393           * will take care of processing the upload file and so on. If the file is already in disk and we'd
 394           * like to add it, please check GalleryResources::addResourceFromDisk()
 395           * This method will also take care of extracting the metadata from the file and generating the
 396           * thumbnail in the required format, according to our configuration.
 397           *
 398           * @param ownerId
 399           * @param albumId
 400           * @param description
 401           * @param upload A FileUpload object
 402           * @see FileUpload
 403           * @see GalleryResources::addResourceFromDisk()
 404           * @return It will return one of the following constants:
 405           * - GALLERY_ERROR_RESOURCE_TOO_BIG
 406           * - GALLERY_ERROR_RESOURCE_FORBIDDEN_EXTENSION
 407           * - GALLERY_ERROR_QUOTA_EXCEEDED
 408           * - GALLERY_ERROR_ADDING_RESOURCE
 409           * - GALLERY_ERROR_UPLOADS_NOT_ENABLED
 410           * or the identifier of the resource that was just added if the operation succeeded.
 411           */
 412          function addResource( $ownerId, $albumId, $description, $upload )
 413          {
 414              // check if quotas are enabled, and if this file would make us go
 415              // over the quota
 416              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcequotas.class.php" );            
 417              if( GalleryResourceQuotas::isBlogOverResourceQuota( $ownerId, $upload->getSize())) {
 418                  return GALLERY_ERROR_QUOTA_EXCEEDED;
 419              }
 420              
 421              // first of all, validate the file using the
 422              // upload validator class. It can return
 423              // UPLOAD_VALIDATOR_ERROR_UPLOAD_TOO_BIG (-1)
 424              // or
 425              // UPLOAD_VALIDATOR_ERROR_FORBIDDEN_EXTENSION (-2)
 426              // in case the file is not valid.
 427              lt_include( PLOG_CLASS_PATH."class/data/validator/uploadvalidator.class.php" );            
 428              $uploadValidator = new UploadValidator();
 429              $error = $uploadValidator->validate( $upload );
 430              if( $error < 0 )
 431                  return $error;
 432              
 433              // get the metadata
 434              lt_include( PLOG_CLASS_PATH."class/gallery/getid3/getid3.php" );            
 435              $getId3 = new GetID3();
 436              $metadata = $getId3->analyze( $upload->getTmpName());
 437  
 438              // nifty helper method from the getid3 package
 439              getid3_lib::CopyTagsToComments($metadata);
 440  
 441              $resourceType = $this->_getResourceType( $upload->getFileName(), $metadata );
 442              
 443              // set the flags
 444              $flags = 0;
 445              if( $resourceType == GALLERY_RESOURCE_IMAGE )
 446                  $flags = $flags|GALLERY_RESOURCE_PREVIEW_AVAILABLE;
 447                  
 448              $info = $this->_filterMetadata( $metadata, $resourceType );  
 449                
 450              // add the record to the database
 451              $fileName = $upload->getFileName();
 452              $duplicated = $this->isDuplicatedFilename( $fileName );
 453              $filePath = "";
 454              $resourceId = $this->addResourceToDatabase( $ownerId, $albumId, $description, $flags, $resourceType, $filePath, $fileName, $info );
 455              if( !$resourceId )
 456                  return false;
 457                                  
 458              if( $duplicated ) {
 459                  $upload->setFileName( $resourceId."-".$upload->getFileName());
 460              }
 461              
 462              // and finally move the file to the right place in disk
 463              // move the file to disk
 464              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );            
 465              $storage = new GalleryResourceStorage();
 466              $resFile = $storage->storeUpload( $resourceId, $ownerId, $upload );
 467              
 468              // if the file cannot be read, we will also remove the record from the
 469              // database so that we don't screw up
 470              $fileReadable = File::isReadable( $resFile );
 471              
 472              if( !$resFile || $resFile < 0 || !$fileReadable ) {
 473                  // if something went wrong, we should not keep the record in the db
 474                  $query = "DELETE FROM ".$this->getPrefix()."gallery_resources WHERE id = $resourceId";
 475                  $this->Execute( $query );
 476                  return $resFile;
 477              }
 478  
 479              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );            
 480              $albums = new GalleryAlbums();
 481              $album = $albums->getAlbum( $albumId );
 482              $album->setNumResources( $album->getNumResources() + 1 );
 483              $albums->updateAlbum( $album );            
 484              
 485              // and finally, we can generate the thumbnail only if the file is an image, of course :)
 486              if( $resourceType == GALLERY_RESOURCE_IMAGE ) {
 487                  lt_include( PLOG_CLASS_PATH."class/gallery/resizers/gallerythumbnailgenerator.class.php" );
 488  
 489                  lt_include( PLOG_CLASS_PATH."class/config/config.class.php" );
 490                  $config =& Config::getConfig();
 491                  
 492                  $imgWidth = $info["video"]["resolution_x"];
 493                  $imgHeight = $info["video"]["resolution_y"];
 494      
 495                  $previewHeight = $config->getValue( "thumbnail_height", GALLERY_DEFAULT_THUMBNAIL_HEIGHT );
 496                  $previewWidth  = $config->getValue( "thumbnail_width", GALLERY_DEFAULT_THUMBNAIL_WIDTH );
 497                  $thumbHeight = ( $imgHeight > $previewHeight ? $previewHeight : $imgHeight );
 498                  $thumbWidth = ( $imgWidth > $previewWidth ? $previewWidth : $imgWidth );
 499                  GalleryThumbnailGenerator::generateResourceThumbnail( $resFile, $resourceId, $ownerId, $thumbHeight, $thumbWidth );                
 500  
 501                  $medPreviewHeight = $config->getValue( "medium_size_thumbnail_height", GALLERY_DEFAULT_MEDIUM_SIZE_THUMBNAIL_HEIGHT );
 502                  $medPreviewWidth  = $config->getValue( "medium_size_thumbnail_width", GALLERY_DEFAULT_MEDIUM_SIZE_THUMBNAIL_WIDTH );
 503                  $thumbHeight = ( $imgHeight > $medPreviewHeight ? $medPreviewHeight : $imgHeight );
 504                  $thumbWidth = ( $imgWidth > $medPreviewWidth ? $medPreviewWidth : $imgWidth );                
 505                  GalleryThumbnailGenerator::generateResourceMediumSizeThumbnail( $resFile, $resourceId, $ownerId, $thumbHeight, $thumbWidth );
 506  
 507                  // call this method only if the settings are right and the image is bigger than the final size(s)
 508                  $finalPreviewHeight = $config->getValue( "final_size_thumbnail_height", 0 );
 509                  $finalPreviewWidth  = $config->getValue( "final_size_thumbnail_width", 0 );
 510                  
 511                  if( $finalPreviewHeight > 0 )
 512                      if( $imgHeight < $finalPreviewHeight )
 513                          $finalPreviewHeight = $imgHeight;
 514                          
 515                  if( $finalPreviewWidth > 0 )
 516                      if( $imgWidth < $finalPreviewWidth )
 517                          $finalPreviewWidth = $imgWidth;
 518                  
 519                  if( $finalPreviewHeight != 0 && $finalPreviewWidth != 0 ) {
 520                      GalleryThumbnailGenerator::generateResourceFinalSizeThumbnail( $resFile, $resourceId, $ownerId, $finalPreviewHeight, $finalPreviewWidth );
 521                      // we have to recalculate the metadata because the image could be different... This is a bit cumbersome
 522                      // and repeats code. We know, thanks.
 523                      $getId3 = new GetID3();
 524                      $metadata = $getId3->analyze( $resFile );
 525                      getid3_lib::CopyTagsToComments($metadata);            
 526                      $info = $this->_filterMetadata( $metadata, $resourceType );
 527                      // and finally update the resource again        
 528                      $resource = $this->getResource( $resourceId );
 529                      $resource->setMetadata( $info );            
 530                      $this->updateResource( $resource );                    
 531                  }
 532              }
 533              
 534              // return the id of the resource we just added
 535              return $resourceId;
 536          }
 537          
 538          /**
 539           * @private
 540           * Returns an array with only those bits of metadata as generate by getid3 that
 541           * we'd like to keep, instead of one huge array
 542           *
 543           * @param metadata
 544           * @param resourceType
 545           */
 546          function _filterMetadata( &$metadata, $resourceType ) 
 547          {
 548              $info = Array();
 549              if( isset( $metadata["md5_file"] ))
 550                  $info["md5_file"] = $metadata["md5_file"];
 551              else
 552                  $info["md5_file"] = "";
 553  
 554              if( isset( $metadata["md5_data"] ))
 555                  $info["md5_data"] = $metadata["md5_data"];
 556              else
 557                  $info["md5_data"] = "";
 558              
 559              if( isset( $metadata["filesize"] ))
 560                  $info["filesize"]= $metadata["filesize"];
 561              else
 562                  $info["filesize"] = 0;
 563                  
 564              if( isset( $metadata["fileformat"] ))
 565                  $info["fileformat"] = $metadata["fileformat"];             
 566              else
 567                  $metadata["fileformat"] = "";
 568  
 569              if( isset( $metadata["comments"] ))
 570                  $info["comments"] = $metadata["comments"];
 571              else
 572                  $info["comments"] = 0;
 573                          
 574              if($resourceType == GALLERY_RESOURCE_IMAGE){
 575                  if( isset( $metadata["video"] )) $info["video"] = $metadata["video"];
 576                  if( isset( $metadata["jpg"] )) {
 577                      $info["jpg"]["exif"]["FILE"] = $metadata["jpg"]["exif"]["FILE"];
 578                      $info["jpg"]["exif"]["COMPUTED"] = $metadata["jpg"]["exif"]["COMPUTED"];
 579                      if(isset( $metadata["jpg"]["exif"]["IFD0"] )) $info["jpg"]["exif"]["IFD0"] = $metadata["jpg"]["exif"]["IFD0"];
 580                      $metadata["jpg"]["exif"]["EXIF"]["MakerNote"] = "";
 581                      $info["jpg"]["exif"]["EXIF"] = $metadata["jpg"]["exif"]["EXIF"];
 582                  }
 583               }  
 584               else  if($resourceType == GALLERY_RESOURCE_SOUND){
 585                  $info["audio"] = $metadata["audio"];
 586                  $info["playtime_string"] = $metadata["playtime_string"];
 587                  $info["playtime_seconds"] = $metadata["playtime_seconds"];
 588               }   
 589               else  if($resourceType == GALLERY_RESOURCE_VIDEO){
 590                  $info["video"] = $metadata["video"];
 591                  $info["audio"] = $metadata["audio"];
 592                  $info["playtime_seconds"] = $metadata["playtime_seconds"];                
 593                  $info["playtime_string"] = $metadata["playtime_string"];                
 594               }
 595               else if( $resourceType == GALLERY_RESOURCE_ZIP ) {
 596                  $info["zip"]["compressed_size"] = $metadata["zip"]["compressed_size"];
 597                  $info["zip"]["uncompressed_size"] = $metadata["zip"]["uncompressed_size"];
 598                  $info["zip"]["entries_count"] = $metadata["zip"]["entries_count"];
 599                  $info["zip"]["compression_method"] = $metadata["zip"]["compression_method"];
 600                  $info["zip"]["compression_speed"] = $metadata["zip"]["compression_speed"];
 601               }
 602               
 603               return( $info );            
 604          }
 605          
 606          /**
 607           * adds a resource to the gallery when the resource is already stored on disk, instead of
 608           * it coming from an upload as it usually happens. This method is better than 
 609           * GalleryResources::addResource() when instead of dealing with uploaded files, the file
 610           * is already in disk and all that is left to do is to add it to the database.
 611           *
 612           * @param ownerId
 613           * @param albumId
 614           * @param description
 615           * @param fullFilePath The real path where the file is stored. This is expected to be
 616           * its final and permanent destination
 617           * @return It will return one of the following constants:
 618           * - GALLERY_ERROR_RESOURCE_TOO_BIG
 619           * - GALLERY_ERROR_RESOURCE_FORBIDDEN_EXTENSION
 620           * - GALLERY_ERROR_QUOTA_EXCEEDED
 621           * - GALLERY_ERROR_ADDING_RESOURCE
 622           * - GALLERY_ERROR_UPLOADS_NOT_ENABLED
 623           * or the identifier of the resource that was just added if the operation succeeded.
 624           */
 625          function addResourceFromDisk( $ownerId, $albumId, $description, $fullFilePath )
 626          {
 627              // check if quotas are enabled, and if this file would make us go
 628              // over the quota
 629              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcequotas.class.php" );            
 630              if( GalleryResourceQuotas::isBlogOverResourceQuota( $ownerId, File::getSize( $fullFilePath ))) {
 631                  return GALLERY_ERROR_QUOTA_EXCEEDED;
 632              }
 633              
 634              // get the metadata
 635              lt_include( PLOG_CLASS_PATH."class/gallery/getid3/getid3.php" );            
 636              $getId3 = new GetID3();
 637              $metadata = $getId3->analyze( $fullFilePath );
 638              // nifty helper method from the getid3 package
 639              getid3_lib::CopyTagsToComments($metadata);                      
 640      
 641              $resourceType = $this->_getResourceType( $fullFilePath, $metadata );
 642              $info = $this->_filterMetadata( $metadata, $resourceType );                    
 643                  
 644              // set the flags
 645              $flags = 0;
 646              if( $resourceType == GALLERY_RESOURCE_IMAGE )
 647                  $flags = $flags|GALLERY_RESOURCE_PREVIEW_AVAILABLE;
 648      
 649              // add the record to the database
 650              $fileName = basename( $fullFilePath );
 651              $duplicated = $this->isDuplicatedFilename( $fileName );
 652              $filePath = "";
 653          
 654              $resourceId = $this->addResourceToDatabase( $ownerId, $albumId, $description, $flags, $resourceType, $filePath, $fileName, $info );
 655              if( !$resourceId )
 656                  return false;
 657  
 658              if( $duplicated ) {
 659                  //
 660                  // :TODO:
 661                  // ugly...
 662                  //
 663                  $newFilePath = dirname( $fullFilePath)."/".$resourceId."-".basename( $fullFilePath );                
 664                  File::rename( $fullFilePath, $newFilePath );
 665                  $fullFilePath = $newFilePath;
 666              }
 667      
 668              // and finally move the file to the right place in disk
 669              // move the file to disk
 670              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );            
 671              $storage = new GalleryResourceStorage();
 672              $resFile = $storage->storeFile( $resourceId, 
 673                                              $ownerId, 
 674                                              $fullFilePath,
 675                                              RESOURCE_STORAGE_STORE_MOVE );
 676              
 677              // if the file cannot be read, we will also remove the record from the
 678              // database so that we don't screw up
 679              $fileReadable = File::isReadable( $resFile );
 680              if( !$resFile || $resFile < 0 || !$fileReadable ) {
 681                  // if something went wrong, we should not keep the record in the db
 682                  $query = "DELETE FROM ".$this->getPrefix()."gallery_resources
 683                            WHERE id = $resourceId";
 684      
 685                  $this->Execute( $query );
 686                  
 687                  return $resFile;
 688              }
 689      
 690              // and finally, we can generate the thumbnail only if the file is an image, of course :)
 691              if( $resourceType == GALLERY_RESOURCE_IMAGE ) {
 692                  lt_include( PLOG_CLASS_PATH."class/gallery/resizers/gallerythumbnailgenerator.class.php" );            
 693                  GalleryThumbnailGenerator::generateResourceThumbnail( $resFile, $resourceId, $ownerId );
 694                  GalleryThumbnailGenerator::generateResourceMediumSizeThumbnail( $resFile, $resourceId, $ownerId );
 695                  // call this method only if the settings are right
 696                  lt_include( PLOG_CLASS_PATH."class/config/config.class.php" );
 697                  $config =& Config::getConfig();
 698                  $previewHeight = $config->getValue( "final_size_thumbnail_height", 0 );
 699                  $previewWidth  = $config->getValue( "final_size_thumbnail_width", 0 );                
 700                  if( $previewHeight != 0 && $previewWidth != 0 ) {
 701                      GalleryThumbnailGenerator::generateResourceFinalSizeThumbnail( $resFile, $resourceId, $ownerId );
 702                      // we have to recalculate the metadata because the image could be different... This is a bit cumbersome
 703                      // and repeats code. We know, thanks.
 704                      $getId3 = new GetID3();
 705                      $metadata = $getId3->analyze( $resFile );
 706                      getid3_lib::CopyTagsToComments($metadata);            
 707                      $info = $this->_filterMetadata( $metadata, $resourceType );
 708                      // and finally update the resource again    
 709                      $resource = $this->getResource( $resourceId );
 710                      $resource->setMetadata( $info );            
 711                      $this->updateResource( $resource );                    
 712                  }
 713              }
 714              
 715              // return the id of the resource we just added
 716              return $resourceId;        
 717          }
 718  
 719          /**
 720           * retrieves a resource, given its filename and its owner
 721           *
 722           * @param ownerId
 723           * @param fileName
 724           * @return Returns a GalleryResource object containing the given resource
 725           * or false if the resource doesn't exist.
 726           */
 727          function getResourceFile( $ownerId, $fileName, $albumId = -1 )
 728          {
 729              $resource = $this->get( "file_name", $fileName, CACHE_RESOURCES_BY_NAME );
 730              if( !$resource )
 731                  return false;
 732                  
 733              if( $resource->getOwnerId() != $ownerId )
 734                  return false;
 735              if( $albumId != -1 )
 736                  if( $resource->getAlbumId() != $albumId )
 737                      return false;
 738                      
 739              return( $resource );
 740          }
 741  
 742          /**
 743           * updates a resource in the database.
 744           *
 745           * @param resource A GalleryResource object with the information of the
 746           * resource we'd like to update.
 747           * @return Returns true if successful or false otherwise
 748           */
 749          function updateResource( $resource ) 
 750          {
 751              // loads the previous version of this object
 752              $prevVersion = $this->getResource( $resource->getId());                
 753          
 754              if( $result = $this->update( $resource )) {
 755                  // if update ok, reset the caches
 756                  $this->_cache->removeData( $resource->getId(), CACHE_RESOURCES );
 757                  $this->_cache->removeData( $resource->getOwnerId(), CACHE_RESOURCES_USER );
 758                  $this->_cache->removeData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME );
 759                  // and update the album counters... must substract 1 from the previous album
 760                  // and must add one to the new album
 761                  $albums = new GalleryAlbums();
 762                  $album = $resource->getAlbum();
 763                  $album->setNumResources( $album->getNumResources() + 1 );
 764                  $albums->updateAlbum( $album );
 765                  
 766                  // update the counters of the previous album
 767                  $prevAlbum = $prevVersion->getAlbum();
 768                  $prevAlbum->setNumResources( $prevAlbum->getNumResources() - 1 );
 769                  $albums->updateAlbum( $prevAlbum );        
 770              }
 771              
 772              return( $result );
 773          }
 774  
 775          /**
 776           * removes a resource from the database and disk
 777           *
 778           * @param resourceId The identifier of the resource we'd like to remove
 779           * @param ownerId Identifier of the owner of the resource. Optional.
 780           * @return Returns true if resource deleted ok or false otherwise.
 781           */
 782          function deleteResource( $resourceId, $ownerId = -1 )
 783          {
 784              // first, get information about the resource
 785              $resource = $this->getResource( $resourceId, $ownerId );
 786              
 787              if( empty( $resource ) )
 788                  return false;
 789   
 790               if( $ownerId > -1 )
 791                   if( $resource->getOwnerId() != $ownerId )
 792                         return false;                 
 793              
 794              $this->delete( "id", $resourceId );
 795              $this->_cache->removeData( $resource->getId(), CACHE_RESOURCES );
 796              $this->_cache->removeData( $resource->getOwnerId(), CACHE_RESOURCES_USER );
 797              $this->_cache->removeData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME );
 798              // update the counters
 799              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
 800              $albums = new GalleryAlbums();
 801              $album = $resource->getAlbum();
 802              $album->setNumResources( $album->getNumResources() - 1 );
 803              $albums->updateAlbum( $album );        
 804              // proceed and remove the file from disk
 805              lt_include( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );
 806              $storage = new GalleryResourceStorage();
 807              return $storage->remove( $resource );                
 808          }
 809  
 810          /**
 811           * Removes all the resource from the given ownerId
 812           *
 813           * @param ownerId The blog identifier
 814           */
 815          function deleteUserResources( $ownerId )
 816          {
 817              $userResources = $this->getUserResources( $ownerId, 
 818                                                           GALLERY_NO_ALBUM, 
 819                                                           GALLERY_RESOURCE_ANY,
 820                                                           "",
 821                                                           -1);
 822  
 823              // remove resources belong to the owner one by one
 824              foreach( $userResources as $resource ) {
 825                  $this->deleteResource( $resource->getId(), $resource->getOwnerId() );
 826              }
 827  
 828              return true;
 829          }
 830  
 831          /**
 832           * returns true if the given filename already exists in the db
 833           *
 834           * @param fileName
 835           * @return true if the filename already exists or false otherwise
 836           */
 837          function isDuplicatedFilename( $fileName )
 838          {
 839              $query = "SELECT COUNT(id) AS total FROM ".$this->getPrefix()."gallery_resources
 840                        WHERE file_name = '".Db::qstr($fileName)."'";
 841  
 842              $result = $this->Execute( $query );
 843  
 844              $row = $result->FetchRow();
 845  
 846              if( $row["total"] == 0 )
 847                  $result = false;
 848              else
 849                  $result = true;
 850  
 851              return( $result );
 852          }
 853          
 854          /**
 855           * @see Model::getSearchConditions()
 856           */
 857  		function getSearchConditions( $searchTerms )
 858          {
 859              $query = "file_name LIKE '%".Db::qstr( $searchTerms )."%'";
 860              
 861              // search the text via the existing FULLTEXT index
 862              $db =& Db::getDb();
 863              if( $db->isFullTextSupported()) {            
 864                  $query .= " OR MATCH(normalized_description) AGAINST ('".Db::qstr($searchTerms)."')";    
 865              }
 866              else {
 867                  $query .= " OR normalized_description LIKE '%".Db::qstr( $searchTerms )."%'";
 868              }
 869              
 870              return( $query );
 871          }
 872          
 873          /**
 874           * @private
 875           */
 876          function mapRow( $row )
 877          {
 878              $res = new GalleryResource( $row["owner_id"],
 879                                          $row["album_id"],
 880                                          $row["description"],
 881                                          $row["flags"],
 882                                          $row["resource_type"],
 883                                          $row["file_path"],
 884                                          $row["file_name"],
 885                                          unserialize($row["metadata"]),
 886                                          $row["date"],
 887                                          $row["thumbnail_format"],
 888                                          unserialize($row["properties"]),
 889                                          $row["id"] );
 890  
 891              $res->setFileSize( $row["file_size"] );
 892  
 893               return $res;
 894          }
 895      }
 896  ?>


Généré le : Mon Nov 26 21:04:15 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics