/** * 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')); }
/** * 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.')); } }
/** * 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')); }
/** * 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; }
/** * 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); } }
/** * 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; }
/** * Move or rename files. * * @param $fileIds * @param $folderId * @param string $filename If this is a rename operation or not. * @param array $actions Actions to take in case of a conflict. * * @throws Exception * @return bool|AssetOperationResponseModel */ public function moveFiles($fileIds, $folderId, $filename = '', $actions = array()) { if ($filename && is_array($fileIds) && count($fileIds) > 1) { throw new Exception(Craft::t("It’s not possible to rename multiple files!")); } if (!is_array($fileIds)) { $fileIds = array($fileIds); } if (!is_array($actions)) { $actions = array($actions); } $results = array(); $response = new AssetOperationResponseModel(); $folder = $this->getFolderById($folderId); $newSourceType = craft()->assetSources->getSourceTypeById($folder->sourceId); // Does the source folder exist? $parent = $folder->getParent(); if ($parent && $folder->parentId && !$newSourceType->folderExists($parent ? $parent->path : '', $folder->name)) { $response->setError(Craft::t("The target folder does not exist!")); } else { foreach ($fileIds as $i => $fileId) { $file = $this->getFileById($fileId); // If this is not a rename operation, then the filename remains the original if (count($fileIds) > 1 || empty($filename)) { $filename = $file->filename; } // If the new file does not have an extension, give it the old file extension. if (!IOHelper::getExtension($filename)) { $filename .= '.' . $file->getExtension(); } $filename = AssetsHelper::cleanAssetName($filename); if ($folderId == $file->folderId && $filename == $file->filename) { $response = new AssetOperationResponseModel(); $response->setSuccess(); $results[] = $response; } $originalSourceType = craft()->assetSources->getSourceTypeById($file->sourceId); if ($originalSourceType && $newSourceType) { if (!($response = $newSourceType->moveFileInsideSource($originalSourceType, $file, $folder, $filename, $actions[$i]))) { $response = $this->_moveFileBetweenSources($originalSourceType, $newSourceType, $file, $folder, $actions[$i]); } } else { $response->setError(Craft::t("There was an error moving the file {file}.", array('file' => $file->filename))); } } } return $response; }
/** * 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'); }
/** * 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 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); }
/** * @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); }
/** * @param $user * * @return null */ private function _processUserPhoto($user) { // Delete their photo? if (craft()->request->getPost('deleteUserPhoto')) { craft()->users->deleteUserPhoto($user); } // Did they upload a new one? if ($userPhoto = UploadedFile::getInstanceByName('userPhoto')) { craft()->users->deleteUserPhoto($user); $image = craft()->images->loadImage($userPhoto->getTempName()); $imageWidth = $image->getWidth(); $imageHeight = $image->getHeight(); $dimension = min($imageWidth, $imageHeight); $horizontalMargin = ($imageWidth - $dimension) / 2; $verticalMargin = ($imageHeight - $dimension) / 2; $image->crop($horizontalMargin, $imageWidth - $horizontalMargin, $verticalMargin, $imageHeight - $verticalMargin); craft()->users->saveUserPhoto(AssetsHelper::cleanAssetName($userPhoto->getName()), $image, $user); IOHelper::deleteFile($userPhoto->getTempName()); } }
/** * Replace a file * * @throws Exception * @return null */ public function actionReplaceFile() { $this->requireAjaxRequest(); $fileId = craft()->request->getPost('fileId'); try { if (empty($_FILES['replaceFile']) || !isset($_FILES['replaceFile']['error']) || $_FILES['replaceFile']['error'] != 0) { throw new Exception(Craft::t('The upload failed.')); } $existingFile = craft()->assets->getFileById($fileId); if (!$existingFile) { throw new Exception(Craft::t('The file to be replaced cannot be found.')); } $targetFolderId = $existingFile->folderId; try { $this->_checkUploadPermissions($targetFolderId); } catch (Exception $e) { $this->returnErrorJson($e->getMessage()); } // Fire an 'onBeforeReplaceFile' event $event = new Event($this, array('asset' => $existingFile)); craft()->assets->onBeforeReplaceFile($event); // Is the event preventing this from happening? if (!$event->performAction) { throw new Exception(Craft::t('The file could not be replaced.')); } $fileName = AssetsHelper::cleanAssetName($_FILES['replaceFile']['name']); $fileLocation = AssetsHelper::getTempFilePath(pathinfo($fileName, PATHINFO_EXTENSION)); move_uploaded_file($_FILES['replaceFile']['tmp_name'], $fileLocation); $response = craft()->assets->insertFileByLocalPath($fileLocation, $fileName, $targetFolderId, AssetConflictResolution::KeepBoth); $insertedFileId = $response->getDataItem('fileId'); $newFile = craft()->assets->getFileById($insertedFileId); if ($newFile && $existingFile) { $source = craft()->assetSources->populateSourceType($newFile->getSource()); if (StringHelper::toLowerCase($existingFile->filename) == StringHelper::toLowerCase($fileName)) { $filenameToUse = $existingFile->filename; } else { // If the file uploaded had to resolve a conflict, grab the final filename if ($response->getDataItem('filename')) { $filenameToUse = $response->getDataItem('filename'); } else { $filenameToUse = $fileName; } } $source->replaceFile($existingFile, $newFile, $filenameToUse); IOHelper::deleteFile($fileLocation, true); } else { throw new Exception(Craft::t('Something went wrong with the replace operation.')); } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } // Fire an 'onReplaceFile' event craft()->assets->onReplaceFile(new Event($this, array('asset' => $existingFile))); $this->returnJson(array('success' => true, 'fileId' => $fileId)); }
/** * 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); }
/** * 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.')); }
/** * @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); }
/** * 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 if (craft()->config->get('useCompressedJs') && !craft()->request->getQuery('uncompressed')) { 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]); // Looking for either a numeric size or "original" keyword if (!is_numeric($size) && $size != "original") { return false; } $username = AssetsHelper::cleanAssetName($segs[1]); $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': if (!isset($segs[1]) || !is_numeric($segs[1])) { return; } $size = $segs[1]; $sourceFile = craft()->path->getResourcesPath() . 'images/' . static::DefaultUserphotoFilename; $targetFolder = craft()->path->getUserPhotosPath() . '__default__/'; IOHelper::ensureFolderExists($targetFolder); if (IOHelper::isWritable($targetFolder)) { $targetFile = $targetFolder . $size . '.' . IOHelper::getExtension($sourceFile); craft()->images->loadImage($sourceFile)->resize($size)->saveAs($targetFile); return $targetFile; } else { Craft::log('Tried to write to the target folder, but could not:' . $targetFolder, LogLevel::Error); } 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 false; } $fileModel = craft()->assets->getFileById($segs[1]); if (empty($fileModel)) { return false; } $size = $segs[2]; return craft()->assetTransforms->getThumbServerPath($fileModel, $size); case 'icons': if (empty($segs[1]) || empty($segs[2]) || !is_numeric($segs[2]) || !preg_match('/^(?P<extension>[a-z_0-9]+)/i', $segs[1])) { return false; } $ext = StringHelper::toLowerCase($segs[1]); $size = $segs[2]; $iconPath = $this->_getIconPath($ext, $size); return $iconPath; case 'logo': return craft()->path->getStoragePath() . implode('/', $segs); 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(); } } // 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(); $pluginPaths = craft()->plugins->call('getResourcePath', array($path)); foreach ($pluginPaths as $path) { if ($path && IOHelper::fileExists($path)) { return $path; } } // Couldn't find the file return false; }