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


PHP IOHelper::ensureFolderExists方法代码示例

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


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

示例1: getBearerToken

 protected function getBearerToken()
 {
     $settings = craft()->plugins->getPlugin('social')->getSettings();
     if (!$settings->twitter_consumer_key || !$settings->twitter_consumer_secret) {
         return false;
     }
     if ($this->token) {
         return $this->token;
     }
     $store = craft()->path->getStoragePath() . 'social/';
     IOHelper::ensureFolderExists($store);
     if (file_exists($store . '/twitter.bearer-token')) {
         $this->token = trim(file_get_contents($store . '/twitter.bearer-token'));
     } else {
         $curl = curl_init(self::TOKEN_URL);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
         curl_setopt($curl, CURLOPT_USERPWD, $settings->twitter_consumer_key . ':' . $settings->twitter_consumer_secret);
         curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('grant_type' => 'client_credentials')));
         $response = curl_exec($curl);
         $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
         if ($status == 200) {
             $decoded = json_decode($response);
             $this->token = $decoded->access_token;
         } else {
             return false;
         }
         file_put_contents($store . '/twitter.bearer-token', $this->token);
     }
     return $this->token;
 }
开发者ID:imarc,项目名称:craft-social,代码行数:32,代码来源:Social_TwitterService.php

示例2: actionCropLogo

 /**
  * Crop user photo.
  */
 public function actionCropLogo()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     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.
         if (($qIndex = strpos($source, '?')) !== false) {
             $source = substr($source, 0, strpos($source, '?'));
         }
         $imagePath = craft()->path->getTempUploadsPath() . $source;
         if (IOHelper::fileExists($imagePath) && craft()->images->setMemoryForImage($imagePath)) {
             $targetPath = craft()->path->getStoragePath() . 'logo/';
             IOHelper::ensureFolderExists($targetPath);
             IOHelper::clearFolder($targetPath);
             craft()->images->loadImage($imagePath)->crop($x1, $x2, $y1, $y2)->scaleToFit(300, 300, false)->saveAs($targetPath . $source);
             IOHelper::deleteFile($imagePath);
             $html = craft()->templates->render('settings/general/_logo');
             $this->returnJson(array('html' => $html));
         }
         IOHelper::deleteFile($imagePath);
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the logo.'));
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:33,代码来源:RebrandController.php

示例3: __construct

 public function __construct()
 {
     $this->document_root = \Craft\Craft::getPathOfAlias('webroot');
     $this->cache_dir = $this->document_root . "/cache";
     $this->cache_url = $this->makeBaseCacheUrl();
     IOHelper::ensureFolderExists($this->cache_dir);
 }
开发者ID:Hambrook,项目名称:Compressor,代码行数:7,代码来源:CompressorService.php

示例4: cache

 public function cache($network, $posts = null)
 {
     $settings = craft()->plugins->getPlugin('social')->getSettings();
     $filename = craft()->path->getStoragePath() . 'social/';
     IOHelper::ensureFolderExists($filename);
     $filename = $filename . $network . ".posts";
     if ($posts !== null) {
         file_put_contents($filename, json_encode($posts));
     } else {
         if (file_exists($filename)) {
             $age = time() - filemtime($filename);
             if ($age <= $settings->social_cache_expiration) {
                 return json_decode(file_get_contents($filename), true);
             }
         }
         return array();
     }
 }
开发者ID:imarc,项目名称:craft-social,代码行数:18,代码来源:SocialVariable.php

示例5: actionConfirm

 /**
  * Upload file and process it for mapping.
  */
 public function actionConfirm()
 {
     $this->requirePostRequest();
     craft()->userSession->requireAdmin();
     // Get POST fields
     $import = craft()->request->getRequiredPost('import');
     // Get file
     $file = \CUploadedFile::getInstanceByName('file');
     // Is file valid?
     if (!is_null($file)) {
         // Determine folder
         $folder = craft()->path->getStoragePath() . 'instablog/';
         // Ensure folder exists
         IOHelper::ensureFolderExists($folder);
         // Get filepath - save in storage folder
         $path = $folder . $file->getName();
         // Save file to Craft's temp folder for later use
         if ($file->saveAs($path)) {
             // Put vars in model and validate filetype
             $model = new InstaBlog_ImportModel();
             $model->filetype = $file->getType();
             if ($model->validate()) {
                 $variables = craft()->instaBlog_import->prepData($path);
                 $variables['import'] = $import;
                 $variables['file'] = $path;
                 // Send variables to template and display
                 $this->renderTemplate('instablog/settings/_confirm', $variables);
             } else {
                 // Not validated, delete and show error
                 @unlink($path);
                 craft()->userSession->setError(Craft::t('This filetype is not valid. Expected XML but got') . ': ' . $model->filetype);
             }
         } else {
             // No file uploaded probably due to php settings.
             craft()->userSession->setError(Craft::t('Couldn\'t Upload file. Check upload_max_filesize or other php.ini settings.'));
         }
     } else {
         // No file uploaded
         craft()->userSession->setError(Craft::t('Select a Wordpress XML export file to upload.'));
     }
 }
开发者ID:lukeholder,项目名称:craft-instablog,代码行数:44,代码来源:InstaBlog_ImportController.php

示例6: generate

 public function generate(GoogleMaps_StaticMapModel $data, $options = array())
 {
     $basePath = craft()->config->get('staticMapCachePath', 'googlemaps');
     $baseUrl = craft()->config->get('staticMapCacheUrl', 'googlemaps');
     $url = $this->url . '?' . $data->getParameters();
     if ($this->expirationLength) {
         $expires = date('Y-m-d H:i:s', time() - $this->expirationLength * 24 * 60 * 60);
     } else {
         $expires = '0000-00-00 00:00:00';
     }
     $record = GoogleMaps_StaticMapRecord::model()->find('query = :query AND dateCreated >= :date', array(':query' => $data->getParameters(), ':date' => $expires));
     if ($record && $record->cachedFileExists()) {
         return $record->getCachedUrl();
     }
     if ($basePath && $baseUrl) {
         $basePath = rtrim($basePath, '/') . '/';
         $baseUrl = rtrim($baseUrl, '/') . '/';
         $client = new \Guzzle\Http\Client();
         $response = $client->get($url);
         $response->send();
         $rawdata = (string) $response->getResponse()->getBody();
         IOHelper::ensureFolderExists($basePath);
         $filename = md5($basePath . time()) . '.' . $data->format;
         $fullpath = $basePath . $filename;
         if (file_exists($fullpath)) {
             unlink($fullpath);
         }
         $fp = fopen($fullpath, 'x');
         fwrite($fp, $rawdata);
         fclose($fp);
         $record = new GoogleMaps_StaticMapRecord();
         $record->query = $data->getParameters();
         $record->filename = $filename;
         $record->save();
         return $baseUrl . $filename;
     }
     return $url;
 }
开发者ID:andrelopez,项目名称:Google-Maps-for-Craft,代码行数:38,代码来源:GoogleMaps_StaticMapService.php

示例7: _addAsset

 /**
  * Adds remote image file as asset
  *
  * @param mixed $settings Array of settings
  * @param string $remoteImagePath url of remote image
  * @param string $baseUrl domain and uri path to Wordpress site
  * @param bool $returnArray Return array or int of Asset Id's
  *
  * @return bool / array File Ids
  */
 private function _addAsset($settings, $remoteImagePath, $baseUrl, $returnArray = true)
 {
     $assetIds = array();
     $tempFolder = craft()->path->getStoragePath() . 'instablog/';
     $remoteImagePath = $this->_getAbsoluteUrl($remoteImagePath, $baseUrl);
     $remoteImageParsed = parse_url($remoteImagePath);
     $imageFileName = IOHelper::getFileName($remoteImageParsed['path']);
     // Ensure folder exists
     IOHelper::ensureFolderExists($tempFolder);
     // Ensure target folder is writable
     try {
         $this->_checkUploadPermissions($settings->assetDestination);
     } catch (Exception $e) {
         Craft::log(var_export($e->getMessage(), true), LogLevel::Error, true, '_addAsset', 'InstaBlog');
         return false;
     }
     // Check to see if this is a WP resized image
     if (preg_match('|-([\\d]+)x([\\d]+)|i', $imageFileName, $resizeDimentions)) {
         // WP dimentions detected in filename. Attempt to get original size image.
         $assetIds['original'] = $this->_addAsset($settings, str_replace($resizeDimentions[0], '', $remoteImagePath), $baseUrl, false);
         $assetIds['originalSrc'] = str_replace($resizeDimentions[0], '', $remoteImagePath);
         // Check to see if this is a Wordpress.com resized image (example: filename.ext?w=XXX)
     } else {
         if (array_key_exists('query', $remoteImageParsed)) {
             parse_str($remoteImageParsed['query'], $params);
             if (array_key_exists('w', $params)) {
                 // WP dimentions detected in parameters. Attempt to import original size image.
                 $assetIds['original'] = $this->_addAsset($settings, UrlHelper::stripQueryString($remoteImagePath), $baseUrl, false);
                 $assetIds['originalSrc'] = UrlHelper::stripQueryString($remoteImagePath);
                 // Add width dimension to asset filename to differentiate from original size image.
                 $imageFileNameParts = explode('.', $imageFileName);
                 $imageFileNameParts[0] .= '-' . $params['w'];
                 $imageFileName = implode('.', $imageFileNameParts);
             }
         }
     }
     // Temp Local Image
     $tempLocalImage = $tempFolder . $imageFileName;
     $curlResponse = $this->_getRemoteFile($remoteImagePath, $tempLocalImage);
     if ($curlResponse && $this->_validateImage($remoteImagePath, $tempLocalImage)) {
         $response = craft()->assets->insertFileByLocalPath($tempLocalImage, $imageFileName, $settings->assetDestination, AssetConflictResolution::KeepBoth);
         $fileId = $response->getDataItem('fileId');
         $assetIds['asset'] = $fileId;
     } else {
         Craft::log('Unable to import ' . $remoteImagePath, LogLevel::Error, true, '_addAsset', 'InstaBlog');
         return false;
     }
     IOHelper::deleteFile($tempLocalImage, true);
     return $returnArray ? $assetIds : $assetIds['asset'];
 }
开发者ID:lukeholder,项目名称:craft-instablog,代码行数:60,代码来源:InstaBlog_ImportService.php

示例8: _determineUploadFolderId

 /**
  * Determine an upload folder id by looking at the settings and whether Element this field belongs to is new or not.
  *
  * @param $settings
  *
  * @throws Exception
  * @return mixed|null
  */
 private function _determineUploadFolderId($settings)
 {
     // Use the appropriate settings for folder determination
     if (empty($settings->useSingleFolder)) {
         $folderSourceId = $settings->defaultUploadLocationSource;
         $folderSubpath = $settings->defaultUploadLocationSubpath;
     } else {
         $folderSourceId = $settings->singleUploadLocationSource;
         $folderSubpath = $settings->singleUploadLocationSubpath;
     }
     // Attempt to find the actual folder ID
     try {
         $folderId = $this->_resolveSourcePathToFolderId($folderSourceId, $folderSubpath);
     } catch (InvalidSubpathException $e) {
         // If this is a new element, the subpath probably just contained a token that returned null, like {id}
         // so use the user's upload folder instead
         if (empty($this->element->id)) {
             $userModel = craft()->userSession->getUser();
             $userFolder = craft()->assets->getUserFolder($userModel);
             $folderName = 'field_' . $this->model->id;
             $folder = craft()->assets->findFolder(array('parentId' => $userFolder->id, 'name' => $folderName));
             if ($folder) {
                 $folderId = $folder->id;
             } else {
                 $folderId = $this->_createSubFolder($userFolder, $folderName);
             }
             IOHelper::ensureFolderExists(craft()->path->getAssetsTempSourcePath() . $folderName);
         } else {
             // Existing element, so this is just a bad subpath
             throw $e;
         }
     }
     return $folderId;
 }
开发者ID:jmstan,项目名称:craft-website,代码行数:42,代码来源:AssetsFieldType.php

示例9: actionCropSiteImage

 /**
  * Crop user photo.
  *
  * @return null
  */
 public function actionCropSiteImage()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     $type = craft()->request->getRequiredPost('type');
     if (!in_array($type, $this->_allowedTypes)) {
         $this->returnErrorJson(Craft::t('That is not a legal site image type.'));
     }
     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);
         $imagePath = craft()->path->getTempUploadsPath() . $source;
         if (IOHelper::fileExists($imagePath) && craft()->images->checkMemoryForImage($imagePath)) {
             $targetPath = craft()->path->getRebrandPath() . $type . '/';
             IOHelper::ensureFolderExists($targetPath);
             IOHelper::clearFolder($targetPath);
             craft()->images->loadImage($imagePath)->crop($x1, $x2, $y1, $y2)->scaleToFit(300, 300, false)->saveAs($targetPath . $source);
             IOHelper::deleteFile($imagePath);
             $html = craft()->templates->render('settings/general/_images/' . $type);
             $this->returnJson(array('html' => $html));
         }
         IOHelper::deleteFile($imagePath);
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the logo.'));
 }
开发者ID:jmstan,项目名称:craft-website,代码行数:37,代码来源:RebrandController.php

示例10: actionUploadUserPhoto

 /**
  * Upload a user photo.
  *
  * @return null
  */
 public function actionUploadUserPhoto()
 {
     $this->requireAjaxRequest();
     craft()->userSession->requireLogin();
     $userId = craft()->request->getRequiredPost('userId');
     if ($userId != craft()->userSession->getUser()->id) {
         craft()->userSession->requirePermission('editUsers');
     }
     // 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'])) {
             $user = craft()->users->getUserById($userId);
             $userName = AssetsHelper::cleanAssetName($user->username, false);
             $folderPath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/';
             IOHelper::clearFolder($folderPath);
             IOHelper::ensureFolderExists($folderPath);
             $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('userphotos/temp/' . $userName . '/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint));
                 $this->returnJson(array('html' => $html));
             }
         }
     } catch (Exception $exception) {
         Craft::log('There was an error uploading the photo: ' . $exception->getMessage(), LogLevel::Error);
     }
     $this->returnErrorJson(Craft::t('There was an error uploading your photo.'));
 }
开发者ID:scisahaha,项目名称:generator-craft,代码行数:46,代码来源:UsersController.php

示例11: _getIconPath

 /**
  * Get icon path for an extension and size
  *
  * @param $ext
  * @param $size
  * @return string
  */
 private function _getIconPath($ext, $size)
 {
     if (strlen($ext) > 4) {
         $ext = '';
     }
     $extAlias = array('docx' => 'doc', 'xlsx' => 'xls', 'pptx' => 'ppt', 'jpeg' => 'jpg', 'html' => 'htm');
     if (isset($extAlias[$ext])) {
         $ext = $extAlias[$ext];
     }
     $sizeFolder = craft()->path->getAssetsIconsPath() . $size;
     // See if we have the icon already
     $iconLocation = $sizeFolder . '/' . $ext . '.png';
     if (IOHelper::fileExists($iconLocation)) {
         return $iconLocation;
     }
     // We are going to need that folder to exist.
     IOHelper::ensureFolderExists($sizeFolder);
     // Determine the closest source size
     $sourceSizes = array(array('size' => 28, 'extSize' => 4, 'extY' => 20), array('size' => 56, 'extSize' => 8, 'extY' => 40), array('size' => 178, 'extSize' => 30, 'extY' => 142), array('size' => 350, 'extSize' => 60, 'extY' => 280));
     foreach ($sourceSizes as $sourceSize) {
         if ($sourceSize['size'] >= $size) {
             break;
         }
     }
     $sourceFolder = craft()->path->getAssetsIconsPath() . $sourceSize['size'];
     // Do we have a source icon that we can resize?
     $sourceIconLocation = $sourceFolder . '/' . $ext . '.png';
     if (!IOHelper::fileExists($sourceIconLocation)) {
         $sourceFile = craft()->path->getAppPath() . 'etc/assets/fileicons/' . $sourceSize['size'] . '.png';
         $image = imagecreatefrompng($sourceFile);
         // Text placement.
         if ($ext) {
             $color = imagecolorallocate($image, 153, 153, 153);
             $text = strtoupper($ext);
             $font = craft()->path->getAppPath() . 'etc/assets/helveticaneue-webfont.ttf';
             // Get the bounding box so we can calculate the position
             $box = imagettfbbox($sourceSize['extSize'], 0, $font, $text);
             $width = $box[4] - $box[0];
             // place the text in the center-bottom-ish of the image
             imagettftext($image, $sourceSize['extSize'], 0, ceil(($sourceSize['size'] - $width) / 2), $sourceSize['extY'], $color, $font, $text);
         }
         // Preserve transparency
         imagealphablending($image, false);
         $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
         imagefill($image, 0, 0, $color);
         imagesavealpha($image, true);
         // Make sure we have a folder to save to and save it.
         IOHelper::ensureFolderExists($sourceFolder);
         imagepng($image, $sourceIconLocation);
     }
     if ($size != $sourceSize['size']) {
         // Resize the source icon to fit this size.
         craft()->images->loadImage($sourceIconLocation)->scaleAndCrop($size, $size)->saveAs($iconLocation);
     }
     return $iconLocation;
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:63,代码来源:ResourcesService.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: actionSaveFormEntry

 public function actionSaveFormEntry()
 {
     $ajax = false;
     $redirect = false;
     $formBuilderHandle = craft()->request->getPost('formHandle');
     if (!$formBuilderHandle) {
         throw new HttpException(404);
     }
     $form = craft()->formBuilder_entries->getFormByHandle($formBuilderHandle);
     if (!$form) {
         throw new HttpException(404);
     }
     $ajaxSubmit = $form->ajaxSubmit;
     $formRedirect = $form->successPageRedirect;
     $formRedirectUrl = $form->redirectUrl;
     if ($ajaxSubmit) {
         $ajax = true;
         $this->requirePostRequest();
         $this->requireAjaxRequest();
     } else {
         $this->requirePostRequest();
     }
     $data = craft()->request->getPost();
     $postData = $this->_filterPostKeys($data);
     $formBuilderEntry = new FormBuilder_EntryModel();
     $fileupload = true;
     $validExtension = false;
     if ($form->hasFileUploads) {
         if (isset(array_values($_FILES)[0])) {
             $filename = array_values($_FILES)[0]['name'];
             $file = array_values($_FILES)[0]['tmp_name'];
             $extension = IOHelper::getFileKind(IOHelper::getExtension($filename));
             if (!in_array($extension, $this->valid_extensions)) {
                 $fileupload = false;
                 $validExtension = false;
             } else {
                 $validExtension = true;
             }
             if ($validExtension) {
                 // Create formbuilder directory inside craft/storage if one doesn't exist
                 $storagePath = craft()->path->getStoragePath();
                 $myStoragePath = $storagePath . 'formbuilder/';
                 IOHelper::ensureFolderExists($myStoragePath);
                 $uploadDir = $myStoragePath;
                 // Rename each file with unique name
                 $uniqe_filename = uniqid() . '-' . $filename;
                 foreach ($_FILES as $key => $value) {
                     $fileUploadHandle = $key;
                 }
                 $postData[$fileUploadHandle] = $uniqe_filename;
             }
         }
     }
     $formBuilderEntry->formId = $form->id;
     $formBuilderEntry->title = $form->name;
     $formBuilderEntry->data = $postData;
     // Use reCaptcha
     $useCaptcha = $form->useReCaptcha;
     if ($useCaptcha && !DEV_MODE) {
         $captchaPlugin = craft()->plugins->getPlugin('recaptcha');
         if ($captchaPlugin && $captchaPlugin->isEnabled) {
             $captcha = craft()->request->getPost('g-recaptcha-response');
             $verified = craft()->recaptcha_verify->verify($captcha);
         } else {
             $verified = false;
         }
     } else {
         $verified = true;
     }
     // Save Form Entry
     if ($verified && $fileupload && craft()->formBuilder_entries->saveFormEntry($formBuilderEntry)) {
         // Save Uploaded File
         if ($validExtension) {
             if (move_uploaded_file($file, $uploadDir . $uniqe_filename)) {
                 IOHelper::deleteFile($file);
                 $file = $uploadDir . $uniqe_filename;
                 $fileModel = new AssetFileModel();
                 $fileModel->sourceId = $form->uploadSource;
                 $fileModel->folderId = $this->assetFolderId;
                 $fileModel->filename = IOHelper::getFileName($uniqe_filename);
                 $fileModel->originalName = IOHelper::getFileName($filename);
                 $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($uniqe_filename));
                 $fileModel->size = filesize($file);
                 $fileModel->dateModified = IOHelper::getLastTimeModified($file);
                 if ($fileModel->kind == 'image') {
                     list($width, $height) = ImageHelper::getImageSize($file);
                     $fileModel->width = $width;
                     $fileModel->height = $height;
                 }
                 craft()->assets->storeFile($fileModel);
             } else {
                 $fileupload = false;
             }
         }
         // Valid extension
         if ($form->notifyFormAdmin && $form->toEmail != '') {
             $this->_sendEmailNotification($formBuilderEntry, $form);
         }
         if ($form->notifyRegistrant && $form->notificationFieldHandleName != '') {
             $emailField = craft()->fields->getFieldByHandle($form->notificationFieldHandleName);
//.........这里部分代码省略.........
开发者ID:nealstammers,项目名称:FormBuilder-Craft-CMS,代码行数:101,代码来源:FormBuilder_EntriesController.php

示例14: 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

示例15: getThumbServerPath

 /**
  * Get a thumb server path by file model and size.
  *
  * @param $fileModel
  * @param $size
  *
  * @return bool|string
  */
 public function getThumbServerPath(AssetFileModel $fileModel, $size)
 {
     $thumbFolder = craft()->path->getAssetsThumbsPath() . $size . '/';
     IOHelper::ensureFolderExists($thumbFolder);
     $extension = $this->_getThumbExtension($fileModel);
     $thumbPath = $thumbFolder . $fileModel->id . '.' . $extension;
     if (!IOHelper::fileExists($thumbPath)) {
         $imageSource = $this->getLocalImageSource($fileModel);
         craft()->images->loadImage($imageSource, $size, $size)->scaleAndCrop($size, $size)->saveAs($thumbPath);
         if (craft()->assetSources->populateSourceType($fileModel->getSource())->isRemote()) {
             $this->queueSourceForDeletingIfNecessary($imageSource);
         }
     }
     return $thumbPath;
 }
开发者ID:JulesVan,项目名称:solutions-con,代码行数:23,代码来源:AssetTransformsService.php


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