public static function populateFromAsset(AssetFileModel $asset) { if ($asset->kind === 'json' && strpos($asset->filename, EmbeddedAssetsPlugin::getFileNamePrefix(), 0) === 0) { try { $url = $asset->getUrl(); if (!UrlHelper::isAbsoluteUrl($url)) { $protocol = craft()->request->isSecureConnection() ? 'https' : 'http'; $url = UrlHelper::getUrlWithProtocol($url, $protocol); } // See http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php $rawData = @file_get_contents($url); if ($rawData) { $data = JsonHelper::decode($rawData); if ($data['__embeddedasset__']) { unset($data['__embeddedasset__']); $embed = new EmbeddedAssetsModel(); $embed->id = $asset->id; foreach ($data as $key => $value) { $embed->{$key} = $value; } return $embed; } } } catch (\Exception $e) { return null; } } return null; }
/** * Generate a URL for a given Assets file in a Source Type. * * @param BaseAssetSourceType $sourceType * @param AssetFileModel $file * * @return string */ public static function generateUrl(BaseAssetSourceType $sourceType, AssetFileModel $file) { $baseUrl = $sourceType->getBaseUrl(); $folderPath = $file->getFolder()->path; $fileName = $file->filename; $appendix = static::getUrlAppendix($sourceType, $file); return $baseUrl . $folderPath . $fileName . $appendix; }
/** * Magic getter * * @param string $name * @return mixed */ function __get($name) { // Is it a transform handle? $transform = craft()->assetTransforms->getTransformByHandle($name); if ($transform) { // Duplicate this model and set it to that transform $model = new AssetFileModel(); // Can't just use getAttributes() here because we'll get thrown into an infinite loop. foreach ($this->attributeNames() as $attributeName) { $model->setAttribute($attributeName, parent::getAttribute($attributeName)); } $model->setTransform($transform); return $model; } else { return parent::__get($name); } }
/** * Get paths for a local asset * * @param AssetFileModel $image */ private function _getPathsForLocalAsset(AssetFileModel $image) { $assetSourcePath = craft()->config->parseEnvironmentString($image->getSource()->settings['url']); if (strrpos($assetSourcePath, 'http') !== false) { $parsedUrl = parse_url($assetSourcePath); $assetSourcePath = $parsedUrl['path']; } $hashPath = craft()->imager->getSetting('hashPath'); if ($hashPath) { $targetFolder = '/' . md5($assetSourcePath . $image->getFolder()->path) . '/'; } else { $targetFolder = $assetSourcePath . $image->getFolder()->path; } $this->sourcePath = ImagerService::fixSlashes(craft()->config->parseEnvironmentString($image->getSource()->settings['path']) . $image->getFolder()->path); $this->targetPath = ImagerService::fixSlashes(craft()->imager->getSetting('imagerSystemPath') . $targetFolder) . $image->id . '/'; $this->targetUrl = craft()->imager->getSetting('imagerUrl') . ImagerService::fixSlashes($targetFolder, true) . $image->id . '/'; $this->sourceFilename = $this->targetFilename = $image->filename; }
/** * Magic getter * * @param string $name * * @throws \Exception * @return mixed */ public function __get($name) { // Run through the BaseModel/CModel stuff first try { return parent::__get($name); } catch (\Exception $e) { // Is $name a transform handle? $transform = craft()->assetTransforms->getTransformByHandle($name); if ($transform) { // Duplicate this model and set it to that transform $model = new AssetFileModel(); // Can't just use getAttributes() here because we'll get thrown into an infinite loop. foreach ($this->attributeNames() as $attributeName) { $model->setAttribute($attributeName, parent::getAttribute($attributeName)); } $model->setContent($this->getContent()); $model->setTransform($transform); return $model; } // Fine, throw the exception throw $e; } }
/** * @inheritDoc IElementType::populateElementModel() * * @param array $row * * @return array */ public function populateElementModel($row) { return AssetFileModel::populateModel($row); }
/** * Finalize a file transfer between sources for the provided file. * * @param AssetFileModel $file The assetFileModel representing the file we're finalizing the transfer for. * * @return null */ public function finalizeTransfer(AssetFileModel $file) { $this->deleteSourceFile($file->getPath()); }
/** * Saves the record for an asset. * * @param AssetFileModel $file * * @throws \Exception * @return bool */ public function storeFile(AssetFileModel $file) { $isNewFile = !$file->id; if (!$isNewFile) { $fileRecord = AssetFileRecord::model()->findById($file->id); if (!$fileRecord) { throw new Exception(Craft::t("No asset exists with the ID “{id}”.", array('id' => $file->id))); } } else { $fileRecord = new AssetFileRecord(); } $fileRecord->sourceId = $file->sourceId; $fileRecord->folderId = $file->folderId; $fileRecord->filename = $file->filename; $fileRecord->kind = $file->kind; $fileRecord->size = $file->size; $fileRecord->width = $file->width; $fileRecord->height = $file->height; $fileRecord->dateModified = $file->dateModified; $fileRecord->validate(); $file->addErrors($fileRecord->getErrors()); if ($file->hasErrors()) { return false; } if ($isNewFile && !$file->getContent()->title) { // Give it a default title based on the file name $file->getContent()->title = str_replace('_', ' ', IOHelper::getFileName($file->filename, false)); } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Fire an 'onBeforeSaveAsset' event $event = new Event($this, array('asset' => $file, 'isNewAsset' => $isNewFile)); $this->onBeforeSaveAsset($event); // Is the event giving us the go-ahead? if ($event->performAction) { // Save the element $success = craft()->elements->saveElement($file, false); // If it didn't work, rollback the transaction in case something changed in onBeforeSaveAsset if (!$success) { if ($transaction !== null) { $transaction->rollback(); } return false; } // Now that we have an element ID, save it on the other stuff if ($isNewFile) { $fileRecord->id = $file->id; } // Save the file row $fileRecord->save(false); } else { $success = false; } // Commit the transaction regardless of whether we saved the asset, in case something changed // in onBeforeSaveAsset if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } if ($success) { // Fire an 'onSaveAsset' event $this->onSaveAsset(new Event($this, array('asset' => $file, 'isNewAsset' => $isNewFile))); if ($this->hasEventHandler('onSaveFileContent')) { // Fire an 'onSaveFileContent' event (deprecated) $this->onSaveFileContent(new Event($this, array('file' => $file))); } } return $success; }
/** * Copy a transform for a file from source location to target location. * * @param AssetFileModel $file * @param $source * @param $target * @return mixed */ public function copyTransform(AssetFileModel $file, $source, $target) { $fileFolder = $file->getFolder(); $basePath = $this->_getSourceFileSystemPath() . $fileFolder->fullPath; IOHelper::copyFile($basePath . $source . '/' . $file->filename, $basePath . $target . '/' . $file->filename); }
/** * Get a file's system path. * * @param AssetFileModel $file * * @return string */ private function _getFileSystemPath(AssetFileModel $file) { $folder = $file->getFolder(); $fileSourceType = craft()->assetSources->getSourceTypeById($file->sourceId); return $this->getSourceFileSystemPath($fileSourceType) . $folder->path . $file->filename; }
/** * Return the thumbnail extension for a file. * * @param AssetFileModel $file * * @return string */ private function _getThumbExtension(AssetFileModel $file) { // For non-web-safe formats we go with jpg. if (!in_array(mb_strtolower(IOHelper::getExtension($file->filename)), ImageHelper::getWebSafeFormats())) { if ($file->getExtension() == 'svg' && craft()->images->isImagick()) { return 'png'; } return 'jpg'; } else { return $file->getExtension(); } }
/** * Return true if a transform exists at the location for a file. * * @param AssetFileModel $file * @param $location * @return mixed */ public function transformExists(AssetFileModel $file, $location) { return (bool) $this->_getObjectInfo($this->_getPathPrefix() . $file->getFolder()->fullPath . $location . '/' . $file->filename); }
/** * Returns an array of all embedded assets thumbnails, indexed by the asset file models ID. * This method is used to inject the asset thumbnails into the CP front-end. Since embedded asset files are stored * as JSON files, there's no supported way of setting the thumbnail on the front-end for these files. The * alternative is to pass a list of these thumbnails to the front-end, and use JS to patch them on-top of the * elements system. * * @return array */ private function _getThumbnails() { // TODO Redo this using the elements API so it's not depending on the DB schema // Escape for using in LIKE clause // See: http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder $prefix = strtr(self::getFileNamePrefix(), array('%' => '\\%', '_' => '\\_')); $results = craft()->db->createCommand()->select('assetfiles.*')->from('assetfiles assetfiles')->where(array('like', 'assetfiles.filename', $prefix . '%.json'))->queryAll(); $assets = AssetFileModel::populateModels($results, 'id'); $thumbnails = array(); foreach ($assets as $id => $asset) { $embed = craft()->embeddedAssets->getEmbeddedAsset($asset); if ($embed) { $thumbnails[$id] = $embed->thumbnailUrl; } } return $thumbnails; }
/** * Gets a file by its asset. * * @param AssetFileModel $asset * * @return string */ protected function getAssetFile(AssetFileModel $asset) { // Check if we have this filenname cached already if (!isset($this->assets[$asset->id])) { // Get asset source $source = $asset->getSource(); // Get asset source type $sourceType = $source->getSourceType(); // Get asset file $this->assets[$asset->id] = $sourceType->getLocalCopy($asset); } return $this->assets[$asset->id]; }
/** * Get a file's S3 path. * * @param AssetFileModel $file * * @return string */ private function _getRackspacePath(AssetFileModel $file) { $folder = $file->getFolder(); return $this->_getPathPrefix() . $folder->path . $file->filename; }
/** * Get URL for a file. * * @param AssetFileModel $file * @param $transform * @return string */ public function getUrlForFile(AssetFileModel $file, $transform = null) { $returnPlaceholder = false; if (!$transform || !in_array(IOHelper::getExtension($file->filename), ImageHelper::getAcceptedExtensions())) { $sourceType = craft()->assetSources->getSourceTypeById($file->sourceId); $base = $sourceType->getBaseUrl(); return $base . $file->getFolder()->fullPath . $file->filename; } // Get the transform index model $existingTransformData = craft()->assetTransforms->getTransformIndex($file, $transform); // Does the file actually exist? if ($existingTransformData->fileExists) { return craft()->assetTransforms->getUrlforTransformByFile($file, $transform); } else { // File doesn't exist yet - load the TransformLoader and set the placeholder URL flag $placeholderUrl = UrlHelper::getResourceUrl('images/blank.gif'); if (!$this->_includedTransformLoader) { $entityPlaceholderUrl = htmlspecialchars($placeholderUrl, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); $spinnerUrl = UrlHelper::getResourceurl('images/spinner_transform.gif'); $actionUrl = UrlHelper::getActionUrl('assets/generateTransform'); craft()->templates->includeJsResource('js/TransformLoader.js'); craft()->templates->includeJs('new TransformLoader(' . JsonHelper::encode($placeholderUrl) . ', ' . JsonHelper::encode($entityPlaceholderUrl) . ', ' . JsonHelper::encode($spinnerUrl) . ', ' . JsonHelper::encode($actionUrl) . ');'); $this->_includedTransformLoader = true; } return $placeholderUrl . '#' . $existingTransformData->id; } }
/** * Get a file's system path. * * @param AssetFileModel $file * * @return string */ private function _getFileSystemPath(AssetFileModel $file) { $fileSourceType = craft()->assetSources->getSourceTypeById($file->sourceId); return $this->getSourceFileSystemPath($fileSourceType) . $file->getPath(); }
/** * @param AssetFileModel $asset * * @return string */ protected function getAssetFilePath(AssetFileModel $asset) { return $asset->getSource()->getSourceType()->getBasePath() . $asset->getFolder()->path . $asset->filename; }
/** * Get a file's S3 path. * * @param AssetFileModel $file * @param $settings The source settings to use. * * @return string */ private function _getS3Path(AssetFileModel $file, $settings = null) { return $this->_getPathPrefix($settings) . $file->getPath(); }
/** * Saves the record for an asset. * * @param AssetFileModel $file * * @throws \Exception * @return bool */ public function storeFile(AssetFileModel $file) { $isNewFile = !$file->id; if (!$isNewFile) { $fileRecord = AssetFileRecord::model()->findById($file->id); if (!$fileRecord) { throw new Exception(Craft::t("No asset exists with the ID “{id}”", array('id' => $file->id))); } } else { $fileRecord = new AssetFileRecord(); } $fileRecord->sourceId = $file->sourceId; $fileRecord->folderId = $file->folderId; $fileRecord->filename = $file->filename; $fileRecord->kind = $file->kind; $fileRecord->size = $file->size; $fileRecord->width = $file->width; $fileRecord->height = $file->height; $fileRecord->dateModified = $file->dateModified; $fileRecord->validate(); $file->addErrors($fileRecord->getErrors()); if ($file->hasErrors()) { return false; } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if ($isNewFile && !$file->getContent()->title) { // Give it a default title based on the file name $file->getContent()->title = str_replace('_', ' ', IOHelper::getFileName($file->filename, false)); } // Fire an 'onBeforeSaveAsset' event $this->onBeforeSaveAsset(new Event($this, array('asset' => $file, 'isNewAsset' => $isNewFile))); // Save the element if (craft()->elements->saveElement($file, false)) { // Now that we have an element ID, save it on the other stuff if ($isNewFile) { $fileRecord->id = $file->id; } // Save the file row $fileRecord->save(false); if ($transaction !== null) { $transaction->commit(); } } else { return false; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } // If we've made it here, everything has been successful so far. // Fire an 'onSaveAsset' event $this->onSaveAsset(new Event($this, array('asset' => $file))); if ($this->hasEventHandler('onSaveFileContent')) { // Fire an 'onSaveFileContent' event (deprecated) $this->onSaveFileContent(new Event($this, array('file' => $file))); } return true; }
/** * {@inheritdoc} BaseModel::defineAttributes() * * @return array */ protected function defineAttributes() { return array_merge(parent::defineAttributes(), array('handle' => AttributeType::String, 'settings' => AttributeType::Mixed)); }
public function readAssetFile(AssetFileModel $asset) { $url = $asset->getUrl(); if (!UrlHelper::isAbsoluteUrl($url)) { $protocol = craft()->request->isSecureConnection() ? 'https' : 'http'; $url = UrlHelper::getUrlWithProtocol($url, $protocol); } return $this->_readExternalFile($url); }
/** * Return true if a transform exists at the location for a file. * * @param AssetFileModel $file * @param $location * @return mixed */ public function transformExists(AssetFileModel $file, $location) { $this->_prepareForRequests(); return (bool) @$this->_s3->getObjectInfo($this->getSettings()->bucket, $this->_getPathPrefix() . $file->getFolder()->fullPath . $location . '/' . $file->filename); }
/** * Create the 2x image. * * @param \Craft\AssetFileModel $image * @param \Craft\AssetTransformModel $transform * @return string $markup */ protected function create2xImage(AssetFileModel $image, AssetTransformModel $transform) { // Grab sizes as int. $originalWidth = (int) $image->getWidth(false); $transformWidth = (int) $transform->width; $transformHeight = (int) $transform->height; // Set transform params, uses params set in Craft. $params = ['mode' => $transform->mode, 'width' => $transformWidth * 2, 'height' => $transformHeight * 2, 'quality' => $transform->quality, 'position' => $transform->position]; // Markup for the specified transform. $markup = $image->getUrl($transform->handle); // If original width is bigger than the 2x size for the specified transform, add the srcset. if ($originalWidth >= $transformWidth * 2) { $markup .= '" srcset="' . $image->getUrl($params) . ' 2x'; } return $markup; }
/** * Return the thumbnail extension for a file. * * @param AssetFileModel $file * * @return string */ private function _getThumbExtension(AssetFileModel $file) { // For non-web-safe formats we go with jpg. if (!in_array(IOHelper::getExtension($file->filename), ImageHelper::getWebSafeFormats())) { return 'jpg'; } else { return $file->getExtension(); } }
/** * Finalize a file transfer between sources for the provided file. * * @param AssetFileModel $file The assetFileModel representing the file we're finalizing the transfer for. * * @return null */ public function finalizeTransfer(AssetFileModel $file) { $this->deleteSourceFile($file->getFolder()->path . $file->filename); }
/** * Get URL for a transform by File Model and transform. * * @param AssetFileModel $file * @param $transform * @return string */ public function getUrlforTransformByFile($file, $transform) { // Create URL to the image $sourceType = craft()->assetSources->getSourceTypeById($file->sourceId); $baseUrl = $sourceType->getBaseUrl(); $folderPath = $baseUrl . $file->getFolder()->fullPath; $transformPath = $this->getTransformSubpath($transform); return $folderPath . $transformPath . $file->filename; }
/** * Get a file's S3 path. * * @param AssetFileModel $file * @param $settings The source settings to use. * * @return string */ private function _getS3Path(AssetFileModel $file, $settings = null) { $folder = $file->getFolder(); return $this->_getPathPrefix($settings) . $folder->path . $file->filename; }
/** * Get a file's Rackspace path. * * @param AssetFileModel $file * * @return string */ private function _getRackspacePath(AssetFileModel $file) { return $this->_getPathPrefix() . $file->getPath(); }