当前位置: 首页>>代码示例>>PHP>>正文


PHP AssetsHelper类代码示例

本文整理汇总了PHP中AssetsHelper的典型用法代码示例。如果您正苦于以下问题:PHP AssetsHelper类的具体用法?PHP AssetsHelper怎么用?PHP AssetsHelper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AssetsHelper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: actionUploadLogo

 /**
  * 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'));
 }
开发者ID:harish94,项目名称:Craft-Release,代码行数:40,代码来源:RebrandController.php

示例2: parseSettings

 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;
 }
开发者ID:developeryamhi,项目名称:laravel-admin,代码行数:33,代码来源:SettingsController.php

示例3: __construct

 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);
 }
开发者ID:Pathologic,项目名称:YandexMapCustomTV,代码行数:8,代码来源:ymap.class.php

示例4: generateUrl

 /**
  * 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;
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:16,代码来源:AssetsHelper.php

示例5: resize

 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;
     }
 }
开发者ID:engram-design,项目名称:ImageResizer,代码行数:52,代码来源:ImageResizer_ResizeService.php

示例6: actionUploadSiteImage

 /**
  * 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'));
 }
开发者ID:paulcarvill,项目名称:Convergence-craft,代码行数:51,代码来源:RebrandController.php

示例7: actionUpload

 /**
  * 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.'));
     }
 }
开发者ID:boboldehampsink,项目名称:import,代码行数:49,代码来源:ImportController.php

示例8: __construct

 /**
  * @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);
 }
开发者ID:AgelxNash,项目名称:modx.evo.custom,代码行数:27,代码来源:plugin.class.php

示例9: _uploadFile

 /**
  * 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');
 }
开发者ID:webremote,项目名称:amforms,代码行数:22,代码来源:AmForms_SubmissionsController.php

示例10: actionCropUserPhoto

 /**
  * 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.'));
 }
开发者ID:scisahaha,项目名称:generator-craft,代码行数:41,代码来源:UsersController.php

示例11: array

		<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>
开发者ID:ChristopheBrun,项目名称:hLib,代码行数:31,代码来源:view.php

示例12: getResourcePath

 /**
  * 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);
//.........这里部分代码省略.........
开发者ID:JamesGibsonUK,项目名称:gibsonlearn,代码行数:101,代码来源:ResourcesService.php

示例13: saveUserPhoto

 /**
  * 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;
 }
开发者ID:webremote,项目名称:craft_boilerplate,代码行数:29,代码来源:UsersService.php

示例14: prepValueFromPost

 /**
  * @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;
 }
开发者ID:jmstan,项目名称:craft-website,代码行数:97,代码来源:AssetsFieldType.php

示例15: uploadFile

 /**
  * 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;
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:65,代码来源:BaseAssetSourceType.php


注:本文中的AssetsHelper类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。