/** * Upload a logo for the admin panel. * * @return null */ public function actionUploadLogo() { $this->requireAjaxRequest(); $this->requireAdmin(); // Upload the file and drop it in the temporary folder $file = $_FILES['image-upload']; try { // Make sure a file was uploaded if (!empty($file['name']) && !empty($file['size'])) { $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); $fileName = AssetsHelper::cleanAssetName($file['name']); move_uploaded_file($file['tmp_name'], $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } craft()->images->cleanImage($folderPath . $fileName); $constraint = 500; list($width, $height) = getimagesize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
private function parseSettings() { $settings = SettingItem::hasInterface()->get(); $parsedSettings = array(); foreach ($settings as $setting) { if ($setting->isFile() || $setting->isImage()) { if (Input::has("setting.{$setting->setting_key}")) { $value = Input::get("setting.{$setting->setting_key}"); if (Input::hasFile($setting->setting_key)) { $subFolder = ($setting->isImage() ? "images" : "files") . "/"; $newFilename = uniqid() . "_" . time() . "." . Input::file($setting->setting_key)->getClientOriginalExtension(); $file = Input::file($setting->setting_key); $file->move(AssetsHelper::uploadPath($subFolder), $newFilename); $value = $subFolder . $newFilename; } $parsedSettings[$setting->setting_key] = $value; } } else { if ($setting->isMultipleChoice()) { $parsedSettings[$setting->setting_key] = implode("|||", Input::get("setting.{$setting->setting_key}")); } else { if (Input::has("setting.{$setting->setting_key}")) { $parsedSettings[$setting->setting_key] = Input::get("setting.{$setting->setting_key}"); } else { if (!$setting->isRequired()) { $parsedSettings[$setting->setting_key] = Input::get("setting.{$setting->setting_key}"); } } } } } return $parsedSettings; }
/** * gets the instance via lazy initialization (created on first usage) * * @return self */ public static function getInstance(DocumentParser $modx) { if (null === self::$instance) { self::$instance = new self($modx); } return self::$instance; }
public function __construct($modx, $tv) { $this->modx = $modx; $this->tv = $tv; $this->DLTemplate = \DLTemplate::getInstance($modx); $this->fs = \Helpers\FS::getInstance(); $this->assets = \AssetsHelper::getInstance($modx); }
/** * 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 = AssetsHelper::getUrlAppendix($sourceType, $file); return $baseUrl . $folderPath . $fileName . $appendix; }
public function resize($sourceId, $path, $width, $height) { try { $settings = craft()->imageResizer->getSettings(); $image = craft()->images->loadImage($path); $filename = basename($path); // We can have settings globally, or per asset source. Check! // Our maximum width/height for assets from plugin settings $imageWidth = craft()->imageResizer->getSettingForAssetSource($sourceId, 'imageWidth'); $imageHeight = craft()->imageResizer->getSettingForAssetSource($sourceId, 'imageHeight'); // Allow for overrides passed on-demand $imageWidth = $width ? $width : $imageWidth; $imageHeight = $height ? $height : $imageHeight; // Lets check to see if this image needs resizing. Split into two steps to ensure // proper aspect ratio is preserved and no upscaling occurs. $hasResized = false; if ($image->getWidth() > $imageWidth) { $hasResized = true; $this->_resizeImage($image, $imageWidth, null); } if ($image->getHeight() > $imageHeight) { $hasResized = true; $this->_resizeImage($image, null, $imageHeight); } if ($hasResized) { // Set image quality - but normalise (for PNG)! $image->setQuality(craft()->imageResizer->getImageQuality($filename)); // If we're checking for larger images if ($settings->skipLarger) { // Save this resized image in a temporary location - we need to test filesize difference $tempPath = AssetsHelper::getTempFilePath($filename); $image->saveAs($tempPath); clearstatcache(); // Lets check to see if this resize resulted in a larger file - revert if so. if (filesize($tempPath) < filesize($path)) { $image->saveAs($path); // Its a smaller file - properly save } else { ImageResizerPlugin::log('Did not resize ' . $filename . ' as it would result in a larger file.', LogLevel::Info, true); } // Delete our temp file we test filesize with IOHelper::deleteFile($tempPath, true); } else { $image->saveAs($path); } } return true; } catch (\Exception $e) { ImageResizerPlugin::log($e->getMessage(), LogLevel::Error, true); return false; } }
/** * Upload a logo for the admin panel. * * @return null */ public function actionUploadSiteImage() { $this->requireAjaxRequest(); $this->requireAdmin(); $type = craft()->request->getRequiredPost('type'); if (!in_array($type, $this->_allowedTypes)) { $this->returnErrorJson(Craft::t('That is not an accepted site image type.')); } // Upload the file and drop it in the temporary folder $file = UploadedFile::getInstanceByName('image-upload'); try { // Make sure a file was uploaded if ($file) { $fileName = AssetsHelper::cleanAssetName($file->getName()); if (!ImageHelper::isImageManipulatable($file->getExtensionName())) { throw new Exception(Craft::t('The uploaded file is not an image.')); } $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); move_uploaded_file($file->getTempName(), $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); if (IOHelper::getExtension($fileName) != 'svg') { craft()->images->cleanImage($folderPath . $fileName); } else { craft()->images->loadImage($folderPath . $fileName)->saveAs($folderPath . $fileName); } $constraint = 500; // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
/** * Upload file and process it for mapping. */ public function actionUpload() { // Get import post $import = craft()->request->getRequiredPost('import'); // Get file $file = \CUploadedFile::getInstanceByName('file'); // Is file valid? if (!is_null($file)) { // Is asset source valid? if (isset($import['assetsource']) && !empty($import['assetsource'])) { // Get source $source = craft()->assetSources->getSourceTypeById($import['assetsource']); // Get folder to save to $folderId = craft()->assets->getRootFolderBySourceId($import['assetsource']); // Save file to Craft's temp folder for later use $fileName = AssetsHelper::cleanAssetName($file->name); $filePath = AssetsHelper::getTempFilePath($file->extensionName); $file->saveAs($filePath); // Move the file by source type implementation $response = $source->insertFileByPath($filePath, $folderId, $fileName, true); // Prevent sensitive information leak. Just in case. $response->deleteDataItem('filePath'); // Get file id $fileId = $response->getDataItem('fileId'); // Put vars in model $model = new ImportModel(); $model->filetype = $file->getType(); // Validate filetype if ($model->validate()) { // Get columns $columns = craft()->import->columns($fileId); // Send variables to template and display $this->renderTemplate('import/_map', array('import' => $import, 'file' => $fileId, 'columns' => $columns)); } else { // Not validated, show error craft()->userSession->setError(Craft::t('This filetype is not valid') . ': ' . $model->filetype); } } else { // No asset source selected craft()->userSession->setError(Craft::t('Please select an asset source.')); } } else { // No file uploaded craft()->userSession->setError(Craft::t('Please upload a file.')); } }
/** * @param $modx * @param string $lang_attribute * @param bool $debug */ public function __construct($modx, $lang_attribute = 'en', $debug = false) { $this->modx = $modx; $this->_table = $modx->getFullTableName($this->table); $this->lang_attribute = $lang_attribute; $this->params = $modx->event->params; if ($this->checkTemplate && !isset($this->params['template']) && $modx->event->name != 'OnEmptyTrash') { $this->params['template'] = array_pop($modx->getDocument($this->params['id'], 'template', 'all', 'all')); } //overload plugin and class properties $_params = $modx->parseProperties('&template=;;' . $this->params['template'] . ' &id=;;' . $this->params['id'], $modx->event->activePlugin, 'plugin'); foreach ($_params as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } $this->params = array_merge($this->params, $_params); $modx->event->_output = ""; $this->DLTemplate = \DLTemplate::getInstance($this->modx); $this->fs = \Helpers\FS::getInstance(); $this->assets = \AssetsHelper::getInstance($modx); }
/** * Upload a file. * * @param array $file * @param int $folderId * * @return bool|int */ private function _uploadFile($file, $folderId) { $fileName = AssetsHelper::cleanAssetName($file['name']); // Save the file to a temp location and pass this on to the source type implementation $filePath = AssetsHelper::getTempFilePath(IOHelper::getExtension($fileName)); move_uploaded_file($file['tmp_name'], $filePath); $response = craft()->assets->insertFileByLocalPath($filePath, $fileName, $folderId); // Make sure the file is removed. IOHelper::deleteFile($filePath, true); // Prevent sensitive information leak. Just in case. $response->deleteDataItem('filePath'); // Return file ID return $response->getDataItem('fileId'); }
/** * Crop user photo. * * @return null */ public function actionCropUserPhoto() { $this->requireAjaxRequest(); craft()->userSession->requireLogin(); $userId = craft()->request->getRequiredPost('userId'); if ($userId != craft()->userSession->getUser()->id) { craft()->userSession->requirePermission('editUsers'); } try { $x1 = craft()->request->getRequiredPost('x1'); $x2 = craft()->request->getRequiredPost('x2'); $y1 = craft()->request->getRequiredPost('y1'); $y2 = craft()->request->getRequiredPost('y2'); $source = craft()->request->getRequiredPost('source'); // Strip off any querystring info, if any. $source = UrlHelper::stripQueryString($source); $user = craft()->users->getUserById($userId); $userName = AssetsHelper::cleanAssetName($user->username, false); // make sure that this is this user's file $imagePath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/' . $source; if (IOHelper::fileExists($imagePath) && craft()->images->checkMemoryForImage($imagePath)) { craft()->users->deleteUserPhoto($user); $image = craft()->images->loadImage($imagePath); $image->crop($x1, $x2, $y1, $y2); if (craft()->users->saveUserPhoto(IOHelper::getFileName($imagePath), $image, $user)) { IOHelper::clearFolder(craft()->path->getTempUploadsPath() . 'userphotos/' . $userName); $html = craft()->templates->render('users/_userphoto', array('account' => $user)); $this->returnJson(array('html' => $html)); } } IOHelper::clearFolder(craft()->path->getTempUploadsPath() . 'userphotos/' . $userName); } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('Something went wrong when processing the photo.')); }
<h1><?php echo CHtml::encode($model->name); ?> </h1> </div> <div id="commandBlock"> <ul class="menu"> <li class="list"> <?php echo CHtml::link(Yii::t('app', 'Back to list'), array('/admin/language/admin', 'ajax' => 'adminGridView', 'page' => Yii::app()->session->get('admin_current_page'), 'filter' => Yii::app()->session->get('admin_current_filter') ? 1 : 0)); ?> </li> <li class="create"> <?php echo CHtml::link(Yii::t('AdminModule.labels', 'Add a language'), array('/admin/language/create')); ?> </li> <li class="update"> <?php echo CHtml::link(Yii::t('AdminModule.labels', 'Update this language'), array('/admin/language/update', "id" => $model->id)); ?> </li> </ul> </div> <div class="clear"></div> </div> <div id="content_section"> <?php $this->widget('zii.widgets.CDetailView', array('data' => $model, 'attributes' => array(array('name' => 'enabled', 'value' => AssetsHelper::getImageTagForBoolean($model->enabled), 'type' => 'html'), array('name' => 'created_at', 'type' => 'datetime'), array('name' => 'updated_at', 'type' => 'datetime'), 'code', 'name'))); ?> </div>
/** * Resolves a resource path to the actual file system path, or returns false if the resource cannot be found. * * @param string $path * * @throws HttpException * @return string */ public function getResourcePath($path) { $segs = explode('/', $path); // Special resource routing if (isset($segs[0])) { switch ($segs[0]) { case 'js': // Route to js/compressed/ if useCompressedJs is enabled // unless js/uncompressed/* is requested, in which case drop the uncompressed/ seg if (isset($segs[1]) && $segs[1] == 'uncompressed') { array_splice($segs, 1, 1); } else { if (craft()->config->get('useCompressedJs')) { array_splice($segs, 1, 0, 'compressed'); } } $path = implode('/', $segs); break; case 'userphotos': if (isset($segs[1]) && $segs[1] == 'temp') { if (!isset($segs[2])) { return false; } return craft()->path->getTempUploadsPath() . 'userphotos/' . $segs[2] . '/' . $segs[3]; } else { if (!isset($segs[3])) { return false; } $size = AssetsHelper::cleanAssetName($segs[2], false); // Looking for either a numeric size or "original" keyword if (!is_numeric($size) && $size != "original") { return false; } $username = AssetsHelper::cleanAssetName($segs[1], false); $filename = AssetsHelper::cleanAssetName($segs[3]); $userPhotosPath = craft()->path->getUserPhotosPath() . $username . '/'; $sizedPhotoFolder = $userPhotosPath . $size . '/'; $sizedPhotoPath = $sizedPhotoFolder . $filename; // If the photo doesn't exist at this size, create it. if (!IOHelper::fileExists($sizedPhotoPath)) { $originalPhotoPath = $userPhotosPath . 'original/' . $filename; if (!IOHelper::fileExists($originalPhotoPath)) { return false; } IOHelper::ensureFolderExists($sizedPhotoFolder); if (IOHelper::isWritable($sizedPhotoFolder)) { craft()->images->loadImage($originalPhotoPath)->resize($size)->saveAs($sizedPhotoPath); } else { Craft::log('Tried to write to target folder and could not: ' . $sizedPhotoFolder, LogLevel::Error); } } return $sizedPhotoPath; } case 'defaultuserphoto': return craft()->path->getResourcesPath() . 'images/user.svg'; case 'tempuploads': array_shift($segs); return craft()->path->getTempUploadsPath() . implode('/', $segs); case 'tempassets': array_shift($segs); return craft()->path->getAssetsTempSourcePath() . implode('/', $segs); case 'assetthumbs': if (empty($segs[1]) || empty($segs[2]) || !is_numeric($segs[1]) || !is_numeric($segs[2])) { return $this->_getBrokenImageThumbPath(); } $fileModel = craft()->assets->getFileById($segs[1]); if (empty($fileModel)) { return $this->_getBrokenImageThumbPath(); } $size = $segs[2]; try { return craft()->assetTransforms->getThumbServerPath($fileModel, $size); } catch (\Exception $e) { return $this->_getBrokenImageThumbPath(); } case 'icons': if (empty($segs[1]) || !preg_match('/^\\w+/i', $segs[1])) { return false; } return $this->_getIconPath($segs[1]); case 'rebrand': if (!in_array($segs[1], array('logo', 'icon'))) { return false; } return craft()->path->getRebrandPath() . $segs[1] . "/" . $segs[2]; case 'transforms': try { if (!empty($segs[1])) { $transformIndexModel = craft()->assetTransforms->getTransformIndexModelById((int) $segs[1]); } if (empty($transformIndexModel)) { throw new HttpException(404); } $url = craft()->assetTransforms->ensureTransformUrlByIndexModel($transformIndexModel); } catch (Exception $exception) { throw new HttpException(404, $exception->getMessage()); } craft()->request->redirect($url, true, 302); craft()->end(); case '404': throw new HttpException(404); } } // Check app/resources folder first. $appResourcePath = craft()->path->getResourcesPath() . $path; if (IOHelper::fileExists($appResourcePath)) { return $appResourcePath; } // See if the first segment is a plugin handle. if (isset($segs[0])) { $pluginResourcePath = craft()->path->getPluginsPath() . $segs[0] . '/' . 'resources/' . implode('/', array_splice($segs, 1)); if (IOHelper::fileExists($pluginResourcePath)) { return $pluginResourcePath; } } // Maybe a plugin wants to do something custom with this URL craft()->plugins->loadPlugins(); $pluginPath = craft()->plugins->callFirst('getResourcePath', array($path), true); if ($pluginPath && IOHelper::fileExists($pluginPath)) { return $pluginPath; } // Couldn't find the file return false; }
/** * Crops and saves a user’s photo. * * @param string $fileName The name of the file. * @param Image $image The image. * @param UserModel $user The user. * * @throws \Exception * @return bool Whether the photo was saved successfully. */ public function saveUserPhoto($fileName, Image $image, UserModel $user) { $userName = IOHelper::cleanFilename($user->username); $userPhotoFolder = craft()->path->getUserPhotosPath() . $userName . '/'; $targetFolder = $userPhotoFolder . 'original/'; IOHelper::ensureFolderExists($userPhotoFolder); IOHelper::ensureFolderExists($targetFolder); $targetPath = $targetFolder . AssetsHelper::cleanAssetName($fileName); $result = $image->saveAs($targetPath); if ($result) { IOHelper::changePermissions($targetPath, craft()->config->get('defaultFilePermissions')); $record = UserRecord::model()->findById($user->id); $record->photo = $fileName; $record->save(); $user->photo = $fileName; return true; } return false; }
/** * @inheritDoc IFieldType::prepValueFromPost() * * @param mixed $value * * @return mixed */ public function prepValueFromPost($value) { $dataFiles = array(); // Grab data strings if (isset($value['data']) && is_array($value['data'])) { foreach ($value['data'] as $index => $dataString) { if (preg_match('/^data:(?<type>[a-z0-9]+\\/[a-z0-9]+);base64,(?<data>.+)/i', $dataString, $matches)) { $type = $matches['type']; $data = base64_decode($matches['data']); if (!$data) { continue; } if (!empty($value['filenames'][$index])) { $filename = $value['filenames'][$index]; } else { $extension = FileHelper::getExtensionByMimeType($type); $filename = 'Uploaded file.' . $extension; } $dataFiles[] = array('filename' => $filename, 'data' => $data); } } } // Remove these so they don't interfere. if (isset($value['data']) && isset($value['filenames'])) { unset($value['data'], $value['filenames']); } $uploadedFiles = array(); // See if we have uploaded file(s). $contentPostLocation = $this->getContentPostLocation(); if ($contentPostLocation) { $files = UploadedFile::getInstancesByName($contentPostLocation); foreach ($files as $file) { $uploadedFiles[] = array('filename' => $file->getName(), 'location' => $file->getTempName()); } } // See if we have to validate against fileKinds $settings = $this->getSettings(); $allowedExtensions = false; if (isset($settings->restrictFiles) && !empty($settings->restrictFiles) && !empty($settings->allowedKinds)) { $allowedExtensions = static::_getAllowedExtensions($settings->allowedKinds); } if (is_array($allowedExtensions)) { foreach ($dataFiles as $file) { $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename'])); if (!in_array($extension, $allowedExtensions)) { $this->_failedFiles[] = $file['filename']; } } foreach ($uploadedFiles as $file) { $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename'])); if (!in_array($extension, $allowedExtensions)) { $this->_failedFiles[] = $file['filename']; } } } if (!empty($this->_failedFiles)) { return true; } // If we got here either there are no restrictions or all files are valid so let's turn them into Assets // Unless there are no files at all. if (empty($value) && empty($dataFiles) && empty($uploadedFiles)) { return array(); } if (empty($value)) { $value = array(); } $fileIds = array(); if (!empty($dataFiles) || !empty($uploadedFiles)) { $targetFolderId = $this->_determineUploadFolderId($settings); foreach ($dataFiles as $file) { $tempPath = AssetsHelper::getTempFilePath($file['filename']); IOHelper::writeToFile($tempPath, $file['data']); $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId); $fileIds[] = $response->getDataItem('fileId'); IOHelper::deleteFile($tempPath, true); } foreach ($uploadedFiles as $file) { $tempPath = AssetsHelper::getTempFilePath($file['filename']); move_uploaded_file($file['location'], $tempPath); $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId); $fileIds[] = $response->getDataItem('fileId'); IOHelper::deleteFile($tempPath, true); } } $fileIds = array_merge($value, $fileIds); // Make it look like the actual POST data contained these file IDs as well, // so they make it into entry draft/version data $this->element->setRawPostContent($this->model->handle, $fileIds); return $fileIds; }
/** * Upload a file. * * @param AssetFolderModel $folder * @return object * @throws Exception */ public function uploadFile($folder) { // Upload the file and drop it in the temporary folder $uploader = new \qqFileUploader(); // Make sure a file was uploaded if (!$uploader->file) { throw new Exception(Craft::t('No file was uploaded')); } $size = $uploader->file->getSize(); // Make sure the file isn't empty if (!$size) { throw new Exception(Craft::t('Uploaded file was empty')); } $fileName = IOHelper::cleanFilename($uploader->file->getName()); // Save the file to a temp location and pass this on to the source type implementation $filePath = AssetsHelper::getTempFilePath(IOHelper::getExtension($fileName)); $uploader->file->save($filePath); // We hate Javascript and PHP in our image files. if (IOHelper::getFileKind(IOHelper::getExtension($filePath)) == 'image') { craft()->images->cleanImage($filePath); } $response = $this->_insertFileInFolder($folder, $filePath, $fileName); // Naming conflict. create a new file and ask the user what to do with it if ($response->isConflict()) { $newFileName = $this->_getNameReplacement($folder, $fileName); $conflictResponse = $response; $response = $this->_insertFileInFolder($folder, $filePath, $newFileName); } if ($response->isSuccess()) { $filename = IOHelper::getFileName($response->getDataItem('filePath')); $fileModel = new AssetFileModel(); $fileModel->sourceId = $this->model->id; $fileModel->folderId = $folder->id; $fileModel->filename = IOHelper::getFileName($filename); $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($filename)); $fileModel->size = filesize($filePath); $fileModel->dateModified = IOHelper::getLastTimeModified($filePath); if ($fileModel->kind == 'image') { list($width, $height) = getimagesize($filePath); $fileModel->width = $width; $fileModel->height = $height; } craft()->assets->storeFile($fileModel); if (!$this->isSourceLocal() && $fileModel->kind == 'image') { // Store copy locally for all sorts of operations. IOHelper::copyFile($filePath, craft()->path->getAssetsImageSourcePath() . $fileModel->id . '.' . IOHelper::getExtension($fileModel->filename)); } // Check if we stored a conflict response originally - send that back then. if (isset($conflictResponse)) { $response = $conflictResponse->setDataItem('additionalInfo', $folder->id . ':' . $fileModel->id)->setDataItem('newFileId', $fileModel->id); } $response->setDataItem('fileId', $fileModel->id); } IOHelper::deleteFile($filePath); // Prevent sensitive information leak. Just in case. $response->deleteDataItem('filePath'); return $response; }
/** * Update the asset transforms for the FileModel. * * @param AssetFileModel $fileModel * @param array|object|string $transformsToUpdate * @return bool */ public function updateTransforms(AssetFileModel $fileModel, $transformsToUpdate) { if (!in_array(IOHelper::getExtension($fileModel->filename), ImageHelper::getAcceptedExtensions())) { return true; } $sourceType = craft()->assetSources->getSourceTypeById($fileModel->sourceId); $imageSource = $sourceType->getImageSourcePath($fileModel); if (!IOHelper::fileExists($imageSource)) { return false; } if (!is_array($transformsToUpdate)) { $transformsToUpdate = array($transformsToUpdate); } foreach ($transformsToUpdate as $transform) { $transform = $this->normalizeTransform($transform); $transformLocation = $this->_getTransformLocation($transform); $timeModified = $sourceType->getTimeTransformModified($fileModel, $transformLocation); // Create the transform if the file doesn't exist, or if it was created before the image was last updated // or if the transform dimensions have changed since it was last created if (!$timeModified || $timeModified < $fileModel->dateModified || $timeModified < $transform->dimensionChangeTime) { $targetFile = AssetsHelper::getTempFilePath(IOHelper::getExtension($fileModel->filename)); switch ($transform->mode) { case 'fit': craft()->images->loadImage($imageSource)->scaleToFit($transform->width, $transform->height)->saveAs($targetFile); break; case 'stretch': craft()->images->loadImage($imageSource)->resize($transform->width, $transform->height)->saveAs($targetFile); break; default: craft()->images->loadImage($imageSource)->scaleAndCrop($transform->width, $transform->height, true, $transform->position)->saveAs($targetFile); break; } clearstatcache(true, $targetFile); $sourceType->putImageTransform($fileModel, $transformLocation, $targetFile); IOHelper::deleteFile($targetFile); } } return true; }
<b><?php echo Yii::t('app', 'Texts'); ?> :</b> <?php echo implode(', ', $data->getTextsNames()); ?> <br/> </div> <div class="adminData"> <b><?php echo CHtml::encode($data->getAttributeLabel('enabled')); ?> :</b> <?php echo AssetsHelper::getImageTagForBoolean($data->enabled); ?> <br/> <b><?php echo CHtml::encode($data->getAttributeLabel('created_at')); ?> :</b> <?php echo CHtml::encode(CodeGeneratorHelper::getFormattedValue('datetime', $data->created_at)); ?> <br/> <b><?php echo CHtml::link($data->getAttributeLabel('updated_at'), array($this->id . '/update/id/' . $data->id)); ?>
/** * Get URL for a file. * * @param AssetFileModel $file * @param string $transform * * @return string */ public function getUrlForFile(AssetFileModel $file, $transform = null) { if (!$transform || !ImageHelper::isImageManipulatable(IOHelper::getExtension($file->filename))) { $sourceType = craft()->assetSources->getSourceTypeById($file->sourceId); return AssetsHelper::generateUrl($sourceType, $file); } // Get the transform index model $index = craft()->assetTransforms->getTransformIndex($file, $transform); // Does the file actually exist? if ($index->fileExists) { return craft()->assetTransforms->getUrlForTransformByTransformIndex($index); } else { if (craft()->config->get('generateTransformsBeforePageLoad')) { // Mark the transform as in progress $index->inProgress = true; craft()->assetTransforms->storeTransformIndexData($index); // Generate the transform craft()->assetTransforms->generateTransform($index); // Update the index $index->fileExists = true; craft()->assetTransforms->storeTransformIndexData($index); // Return the transform URL return craft()->assetTransforms->getUrlForTransformByTransformIndex($index); } else { // Queue up a new Generate Pending Transforms task, if there isn't one already if (!craft()->tasks->areTasksPending('GeneratePendingTransforms')) { craft()->tasks->createTask('GeneratePendingTransforms'); } // Return the temporary transform URL return UrlHelper::getResourceUrl('transforms/' . $index->id); } } }
/** * @inheritDoc BaseAssetSourceType::insertFileInFolder() * * @param AssetFolderModel $folder * @param $filePath * @param $fileName * * @throws Exception * @return AssetFileModel */ protected function insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { $fileName = AssetsHelper::cleanAssetName($fileName); $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } $uriPath = $this->_getPathPrefix() . $folder->path . $fileName; $fileInfo = $this->_getObjectInfo($uriPath); if ($fileInfo) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } clearstatcache(); // Upload file try { $this->_uploadFile($uriPath, $filePath); } catch (\Exception $exception) { throw new Exception(Craft::t('Could not copy file to target destination')); } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $uriPath); }
?> <div id="title_section"> <div id="titleBlock"> <h1><?php echo Yii::t('WebPagesModule.labels', 'Your web pages'); ?> </h1> </div> <div id="commandBlock"> <ul class="menu"> <li class="create"> <?php echo CHtml::link(Yii::t('WebPagesModule.labels', 'Add a web page'), array('/webPages/webPage/create')); ?> </li> <li class="reset"> <?php echo CHtml::link(Yii::t('app', 'Reset filters'), array('/webPages/webPage/admin', 'ajax' => 'adminGridView', 'page' => 1), array('onclick' => 'javascript:Site.resetGridViewFilters("grid-view")')); ?> </li> </ul> </div> <div class="clear"></div> </div> <div id="content_section"> <?php $dataProvider = $model->search(); $dataProvider->setPagination($pager); $this->widget('zii.widgets.grid.CGridView', array('id' => 'adminGridView', 'dataProvider' => $dataProvider, 'filter' => $model, 'template' => "{summary}\n{pager}<br/>\n{items}\n{pager}", 'columns' => array(array('header' => Yii::t('WebPagesModule.labels', 'Name'), 'name' => 'name', 'value' => 'CHtml::link(CHtml::encode($data->name), array("/webPages/webPage/view", "id" => $data->id))', 'type' => 'html'), 'title', array('header' => Yii::t('WebPagesModule.labels', 'Enabled'), 'value' => 'AssetsHelper::getImageTagForBoolean($data->enabled, false)', 'type' => 'raw', 'name' => 'enabled', 'filter' => AssetsHelper::getBooleanListData(), 'htmlOptions' => array('class' => 'center')), array('header' => Yii::t('WebPagesModule.labels', 'Texts'), 'value' => 'count($data->webTexts)', 'type' => 'raw', 'htmlOptions' => array('class' => 'center')), array('class' => 'CButtonColumn', 'template' => '{update}{delete}{view}')))); ?> </div>
/** * Make a local copy of the file and return the path to it. * * @param AssetFileModel $file * @return mixed */ public function getLocalCopy(AssetFileModel $file) { $location = AssetsHelper::getTempFilePath($file->getExtension()); $this->_prepareForRequests(); $this->_s3->getObject($this->getSettings()->bucket, $this->_getS3Path($file), $location); return $location; }
/** * Create a transform for the file by the transform index. * * @param AssetFileModel $file * @param AssetTransformIndexModel $index * * @throws Exception if the AssetTransformIndexModel cannot be determined to have a transform * @return null */ private function _createTransformForFile(AssetFileModel $file, AssetTransformIndexModel $index) { if (!ImageHelper::isImageManipulatable(IOHelper::getExtension($file->filename))) { return; } if (empty($index->transform)) { $transform = $this->normalizeTransform(mb_substr($index->location, 1)); if (empty($transform)) { throw new Exception(Craft::t("Unable to recognize the transform for this transform index!")); } } else { $transform = $index->transform; } if (!isset($index->detectedFormat)) { $index->detectedFormat = !empty($index->format) ? $index->format : $this->detectAutoTransformFormat($file); } $sourceType = craft()->assetSources->populateSourceType($file->getSource()); $imageSource = $file->getTransformSource(); $quality = $transform->quality ? $transform->quality : craft()->config->get('defaultImageQuality'); $image = craft()->images->loadImage($imageSource, $transform->width, $transform->height); $image->setQuality($quality); switch ($transform->mode) { case 'fit': $image->scaleToFit($transform->width, $transform->height); break; case 'stretch': $image->resize($transform->width, $transform->height); break; default: $image->scaleAndCrop($transform->width, $transform->height, true, $transform->position); break; } $createdTransform = AssetsHelper::getTempFilePath($index->detectedFormat); $image->saveAs($createdTransform); clearstatcache(true, $createdTransform); $sourceType->putImageTransform($file, $index, $createdTransform); IOHelper::deleteFile($createdTransform); if (craft()->assetSources->populateSourceType($file->getSource())->isRemote()) { $this->queueSourceForDeletingIfNecessary($imageSource); } return; }
/** * @inheritDoc BaseAssetSourceType::insertFileInFolder() * * @param AssetFolderModel $folder * @param string $filePath * @param string $fileName * * @throws Exception * @return AssetOperationResponseModel */ protected function insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { // Check if the set file system path exists $basePath = $this->getSourceFileSystemPath(); if (empty($basePath)) { $basePath = $this->getBasePath(); if (!empty($basePath)) { throw new Exception(Craft::t('The file system path “{folder}” set for this source does not exist.', array('folder' => $this->getBasePath()))); } } $targetFolder = $this->getSourceFileSystemPath() . $folder->path; // Make sure the folder exists. if (!IOHelper::folderExists($targetFolder)) { throw new Exception(Craft::t('The folder “{folder}” does not exist.', array('folder' => $targetFolder))); } // Make sure the folder is writable if (!IOHelper::isWritable($targetFolder)) { throw new Exception(Craft::t('The folder “{folder}” is not writable.', array('folder' => $targetFolder))); } $fileName = AssetsHelper::cleanAssetName($fileName); $targetPath = $targetFolder . $fileName; $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } if (IOHelper::fileExists($targetPath)) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } if (!IOHelper::copyFile($filePath, $targetPath)) { throw new Exception(Craft::t('Could not copy file to target destination')); } IOHelper::changePermissions($targetPath, craft()->config->get('defaultFilePermissions')); $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $targetPath); }
/** * Returns the URL to the user's photo. * * @param int $size * * @return string|null */ public function getPhotoUrl($size = 100) { if ($this->photo) { $username = AssetsHelper::cleanAssetName($this->username, false); return UrlHelper::getResourceUrl('userphotos/' . $username . '/' . $size . '/' . $this->photo); } }
/** * @inheritDoc IFieldType::prepValueFromPost() * * @param mixed $value * * @return mixed */ public function prepValueFromPost($value) { // See if we have uploaded file(s). $contentPostLocation = $this->getContentPostLocation(); if ($contentPostLocation) { $uploadedFiles = UploadedFile::getInstancesByName($contentPostLocation); if (!empty($uploadedFiles)) { // See if we have to validate against fileKinds $settings = $this->getSettings(); if (isset($settings->restrictFiles) && !empty($settings->restrictFiles) && !empty($settings->allowedKinds)) { $allowedExtensions = static::_getAllowedExtensions($settings->allowedKinds); $failedFiles = array(); foreach ($uploadedFiles as $uploadedFile) { $extension = mb_strtolower(IOHelper::getExtension($uploadedFile->getName())); if (!in_array($extension, $allowedExtensions)) { $failedFiles[] = $uploadedFile; } } // If any files failed the validation, make a note of it. if (!empty($failedFiles)) { $this->_failedFiles = $failedFiles; return true; } } // If we got here either there are no restrictions or all files are valid so let's turn them into Assets $fileIds = array(); $targetFolderId = $this->_determineUploadFolderId($settings); if (!empty($targetFolderId)) { foreach ($uploadedFiles as $file) { $tempPath = AssetsHelper::getTempFilePath($file->getName()); move_uploaded_file($file->getTempName(), $tempPath); $response = craft()->assets->insertFileByLocalPath($tempPath, $file->getName(), $targetFolderId); $fileIds[] = $response->getDataItem('fileId'); IOHelper::deleteFile($tempPath, true); } if (is_array($value) && is_array($fileIds)) { $fileIds = array_merge($value, $fileIds); } // Make it look like the actual POST data contained these file IDs as well, // so they make it into entry draft/version data $this->element->setRawPostContent($this->model->handle, $fileIds); return $fileIds; } } } return parent::prepValueFromPost($value); }
/** * Create a folder. * * @param AssetFolderModel $parentFolder The assetFolderModel representing the folder to create. * @param string $folderName The name of the folder to create. * * @throws Exception * @return AssetOperationResponseModel */ public function createFolder(AssetFolderModel $parentFolder, $folderName) { $folderName = AssetsHelper::cleanAssetName($folderName); // If folder exists in DB or physically, bail out if (craft()->assets->findFolder(array('parentId' => $parentFolder->id, 'name' => $folderName)) || $this->folderExists($parentFolder, $folderName)) { throw new Exception(Craft::t('A folder already exists with that name!')); } if (!$this->createSourceFolder($parentFolder, $folderName)) { throw new Exception(Craft::t('There was an error while creating the folder.')); } $newFolder = new AssetFolderModel(); $newFolder->sourceId = $parentFolder->sourceId; $newFolder->parentId = $parentFolder->id; $newFolder->name = $folderName; $newFolder->path = $parentFolder->path . $folderName . '/'; $folderId = craft()->assets->storeFolder($newFolder); $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('folderId', $folderId)->setDataItem('parentId', $parentFolder->id)->setDataItem('folderName', $folderName); }
/** * If 'unverifiedEmail' is set on the UserModel, then this method will transfer it to the official email property * and clear the unverified one. * * @param UserModel $user * * @throws Exception */ public function verifyEmailForUser(UserModel $user) { if ($user->unverifiedEmail) { $userRecord = $this->_getUserRecordById($user->id); $oldEmail = $userRecord->email; $userRecord->email = $user->unverifiedEmail; if (craft()->config->get('useEmailAsUsername')) { $userRecord->username = $user->unverifiedEmail; $oldProfilePhotoPath = craft()->path->getUserPhotosPath() . AssetsHelper::cleanAssetName($oldEmail, false, true); $newProfilePhotoPath = craft()->path->getUserPhotosPath() . AssetsHelper::cleanAssetName($user->unverifiedEmail, false, true); // Update the user profile photo folder name, if it exists. if (IOHelper::folderExists($oldProfilePhotoPath)) { IOHelper::rename($oldProfilePhotoPath, $newProfilePhotoPath); } } $userRecord->unverifiedEmail = null; $userRecord->save(); // If the user status is pending, let's activate them. if ($userRecord->pending == true) { $this->activateUser($user); } } }
/** * @inheritDoc BaseAssetSourceType::insertFileInFolder() * * @param AssetFolderModel $folder * @param $filePath * @param $fileName * * @throws Exception * @return AssetFileModel */ protected function insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { $fileName = AssetsHelper::cleanAssetName($fileName); $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } $uriPath = $this->_getPathPrefix() . $folder->path . $fileName; $this->_prepareForRequests(); $settings = $this->getSettings(); $fileInfo = $this->_s3->getObjectInfo($settings->bucket, $uriPath); if ($fileInfo) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } clearstatcache(); $this->_prepareForRequests(); if (!$this->putObject($filePath, $this->getSettings()->bucket, $uriPath, \S3::ACL_PUBLIC_READ)) { throw new Exception(Craft::t('Could not copy file to target destination')); } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $uriPath); }
<h1><?php echo CHtml::encode($model->title); ?> </h1> </div> <div id="commandBlock"> <ul class="menu"> <li class="list"> <?php echo CHtml::link(Yii::t('app', 'Back to list'), array('/news/news/admin', 'ajax' => 'adminGridView', 'page' => Yii::app()->session->get('admin_current_page'), 'filter' => Yii::app()->session->get('admin_current_filter') ? 1 : 0)); ?> </li> <li class="create"> <?php echo CHtml::link(Yii::t('NewsModule.labels', 'Add a news'), array('/news/news/create')); ?> </li> <li class="update"> <?php echo CHtml::link(Yii::t('NewsModule.labels', 'Update this news'), array('/news/news/update', "id" => $model->id)); ?> </li> </ul> </div> <div class="clear"></div> </div> <div id="content_section"> <?php $this->widget('zii.widgets.CDetailView', array('data' => $model, 'attributes' => array(array('label' => Yii::t('app', 'Enabled'), 'value' => AssetsHelper::getImageTagForBoolean($model->enabled), 'type' => 'html'), array('label' => Yii::t('app', 'Created at'), 'name' => 'created_at', 'type' => 'datetime'), array('label' => Yii::t('app', 'Updated at'), 'name' => 'updated_at', 'type' => 'datetime'), array('label' => '', 'value' => "<hr/>", 'type' => 'html'), array('label' => Yii::t('NewsModule.labels', 'Event date'), 'name' => 'event_date', 'type' => 'datetime'), array('label' => Yii::t('app', 'Title'), 'value' => $model->getTranslation()->title), array('label' => Yii::t('app', 'Description'), 'value' => $model->getTranslation()->description), array('label' => Yii::t('app', 'Keywords'), 'value' => $model->getTranslation()->keywords), array('label' => Yii::t('NewsModule.labels', 'Tags'), 'value' => implode(', ', $model->getTagsNames())), array('label' => Yii::t('NewsModule.labels', 'Translations'), 'value' => implode(', ', $model->getLanguagesCodes()))))); ?> </div>