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; }
/** * 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.')); }
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); }
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(); } }
/** * 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.')); } }
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; }
/** * 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']; }
/** * 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; }
/** * 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.')); }
/** * 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.')); }
/** * 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; }
/** * 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; }
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); $submitterEmail = $formBuilderEntry->data[$emailField->handle]; $this->_sendRegistrantEmailNotification($formBuilderEntry, $form, $submitterEmail); } if (!empty($form->successMessage)) { $successMessage = $form->successMessage; } else { $successMessage = Craft::t('Thank you, we have received your submission and we\'ll be in touch shortly.'); } craft()->userSession->setFlash('success', $successMessage); if ($ajax) { $this->returnJson(['success' => true, 'message' => $successMessage]); } else { if ($formRedirect) { $this->redirect($formRedirectUrl); } } } else { if (!$verified) { if (!$captchaPlugin) { craft()->userSession->setFlash('error', 'Please enable reCaptcha plugin!'); $this->redirectToPostedUrl(); } craft()->userSession->setFlash('error', 'Please check captcha!'); $this->redirectToPostedUrl(); } if (!empty($form->errorMessage)) { $errorMessage = $form->errorMessage; } else { $errorMessage = Craft::t('We\'re sorry, but something has gone wrong.'); } if ($ajax) { $this->returnJson(['error' => true, 'message' => $errorMessage]); } else { if ($formRedirect) { $this->redirectToPostedUrl(); } else { craft()->userSession->setFlash('error', $errorMessage); } } } }
/** * 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; }
/** * 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; }
/** * Move a file in source. * * @param AssetFileModel $file * @param AssetFolderModel $targetFolder * @param string $fileName * @param bool $overwrite if True, will overwrite target destination * @return mixed */ protected function _moveSourceFile(AssetFileModel $file, AssetFolderModel $targetFolder, $fileName = '', $overwrite = false) { if (empty($fileName)) { $fileName = $file->filename; } $newServerPath = $this->_getSourceFileSystemPath() . $targetFolder->fullPath . $fileName; $conflictingRecord = craft()->assets->findFile(array('folderId' => $targetFolder->id, 'filename' => $fileName)); $conflict = !$overwrite && (IOHelper::fileExists($newServerPath) || !craft()->assets->isMergeInProgress() && is_object($conflictingRecord)); if ($conflict) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->_getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } if (!IOHelper::move($this->_getFileSystemPath($file), $newServerPath)) { $response = new AssetOperationResponseModel(); return $response->setError(Craft::t("Could not save the file")); } if ($file->kind == 'image') { $this->_deleteGeneratedThumbnails($file); // Move transforms $transforms = craft()->assetTransforms->getGeneratedTransformLocationsForFile($file); $baseFromPath = $this->_getSourceFileSystemPath() . $file->getFolder()->fullPath; $baseToPath = $this->_getSourceFileSystemPath() . $targetFolder->fullPath; foreach ($transforms as $location) { if (IOHelper::fileExists($baseFromPath . $location . '/' . $file->filename)) { IOHelper::ensureFolderExists($baseToPath . $location); IOHelper::move($baseFromPath . $location . '/' . $file->filename, $baseToPath . $location . '/' . $fileName); } } } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('newId', $file->id)->setDataItem('newFileName', $fileName); }
/** * Perform pre-flight checks to ensure we can run. * * @return this */ protected function flightcheck() { if (!self::$_pluginSettings) { throw new Exception(Craft::t('Minimee is not installed.')); } if (!$this->settings->enabled) { throw new Exception(Craft::t('Minimee has been disabled via settings.')); } if (!$this->settings->validate()) { $exceptionErrors = ''; foreach ($this->settings->getErrors() as $error) { $exceptionErrors .= implode('. ', $error); } throw new Exception(Craft::t('Minimee has detected invalid plugin settings: ') . $exceptionErrors); } if ($this->settings->useResourceCache()) { IOHelper::ensureFolderExists($this->makePathToStorageFolder()); } else { if (!IOHelper::folderExists($this->settings->cachePath)) { throw new Exception(Craft::t('Minimee\'s Cache Folder does not exist: ' . $this->settings->cachePath)); } if (!IOHelper::isWritable($this->settings->cachePath)) { throw new Exception(Craft::t('Minimee\'s Cache Folder is not writable: ' . $this->settings->cachePath)); } } if (!$this->assets) { throw new Exception(Craft::t('Minimee has no assets to operate upon.')); } if (!$this->type) { throw new Exception(Craft::t('Minimee has no value for `type`.')); } return $this; }
/** * 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 = 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.')); } $user = craft()->users->getUserById($userId); $userName = AssetsHelper::cleanAssetName($user->username, false); $folderPath = craft()->path->getTempUploadsPath() . 'userphotos/' . $userName . '/'; IOHelper::clearFolder($folderPath); IOHelper::ensureFolderExists($folderPath); 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')); } craft()->images->loadImage($folderPath . $fileName)->scaleToFit(500, 500, false)->saveAs($folderPath . $fileName); list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('userphotos/temp/' . $userName . '/' . $fileName), 'width' => $width, 'height' => $height, '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.')); }
/** * Crop and save a user's photo by coordinates for a given user model. * * @param $source * @param $x1 * @param $x2 * @param $y1 * @param $y2 * @param UserModel $user * @return bool * @throws \Exception */ public function cropAndSaveUserPhoto($source, $x1, $x2, $y1, $y2, UserModel $user) { $userPhotoFolder = craft()->path->getUserPhotosPath() . $user->username . '/'; $targetFolder = $userPhotoFolder . 'original/'; IOHelper::ensureFolderExists($userPhotoFolder); IOHelper::ensureFolderExists($targetFolder); $filename = IOHelper::getFileName($source); $targetPath = $targetFolder . $filename; $image = craft()->images->loadImage($source); $image->crop($x1, $x2, $y1, $y2); $result = $image->saveAs($targetPath); if ($result) { IOHelper::changePermissions($targetPath, IOHelper::getWritableFilePermissions()); $record = UserRecord::model()->findById($user->id); $record->photo = $filename; $record->save(); $user->photo = $filename; return true; } return false; }
/** * @return string */ public function getCachePath() { $path = $this->getRuntimePath() . 'cache/'; IOHelper::ensureFolderExists($path); return $path; }
/** * Get icon path for an extension and size * * @param $ext * @param $size * * @return string */ private function _getIconPath($ext, $size) { if (mb_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' => 40, 'extSize' => 7, 'extY' => 25), array('size' => 350, 'extSize' => 60, 'extY' => 220)); 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 = craft()->images->loadImage($sourceFile); // Text placement. if ($ext) { $font = craft()->path->getAppPath() . 'etc/assets/helveticaneue-webfont.ttf'; $image->setFontProperties($font, $sourceSize['extSize'], "#999"); $text = StringHelper::toUpperCase($ext); $box = $image->getTextBox($text); $width = $box->getWidth(); // place the text in the center-bottom-ish of the image $x = ceil(($sourceSize['size'] - $width) / 2); $y = $sourceSize['extY']; $image->writeText($text, $x, $y); } // Make sure we have a folder to save to and save it. IOHelper::ensureFolderExists($sourceFolder); $image->saveAs($sourceIconLocation); } if ($size != $sourceSize['size']) { // Resize the source icon to fit this size. craft()->images->loadImage($sourceIconLocation, $size, $size)->scaleAndCrop($size, $size)->saveAs($iconLocation); } return $iconLocation; }
/** * Get the store folder path. * * @param array $params * * @return string */ private function _getStoreFolder($params) { // Effect on image? $folderEffectName = ''; foreach ($params['filters'] as $filter) { $actualFilter = $filter; if (is_array($filter)) { if (isset($filter['effect'])) { $actualFilter = $filter['effect']; } elseif (isset($filter['filter'])) { $actualFilter = $filter['filter']; } elseif (isset($filter['type'])) { $actualFilter = $filter['type']; } } switch ($actualFilter) { case 'blur': $folderEffectName .= '_blur'; break; case 'colorize': if (isset($filter['color']) && substr($filter['color'], 0, 1) === '#') { if (strpos($folderEffectName, '_colorize') === false) { $folderEffectName .= '_colorize'; } $folderEffectName .= '_' . substr($filter['color'], 1); } break; case 'grey': case 'gray': case 'grayscale': $folderEffectName .= '_gray'; break; case 'negative': $folderEffectName .= '_negative'; break; case 'sharp': case 'sharpen': $folderEffectName .= '_sharpen'; break; } } // Store folder $storeFolder = '_' . $params['width'] . '_' . $params['height'] . '_' . (strtolower($params['mode']) == 'crop' ? 'crop' : 'fit') . (strtolower($params['mode']) == 'crop' ? '_' . $params['position'] : '') . $folderEffectName . DIRECTORY_SEPARATOR; IOHelper::ensureFolderExists($this->_path . $storeFolder); return $storeFolder; }
/** * Process Submission Entry * */ public function processSubmissionEntry(FormBuilder2_EntryModel $submission) { // Fire Before Save Event $this->onBeforeSave(new Event($this, array('entry' => $submission))); $form = craft()->formBuilder2_form->getFormById($submission->formId); $formFields = $form->fieldLayout->getFieldLayout()->getFields(); $attributes = $form->getAttributes(); $formSettings = $attributes['formSettings']; $submissionRecord = new FormBuilder2_EntryRecord(); // File Uploads if ($submission->files) { $fileIds = []; foreach ($submission->files as $key => $value) { if ($value->size) { $folder = $value->getFolder(); // Make sure folder excist $source = $folder->getSource()['settings']; IOHelper::ensureFolderExists($source['path'], $suppressErrors = true); // Save/Store Files $fileName = IOHelper::getFileName($value->filename, true); $response = craft()->assets->insertFileByLocalPath($value->originalName, $fileName, $value->folderId, AssetConflictResolution::KeepBoth); $fileIds[] = $response->getDataItem('fileId'); // Delete Temp Files IOHelper::deleteFile($value->originalName, true); if ($response->isError()) { $response->setError(Craft::t('There was an error with file uploads.')); } } $submissionRecord->files = $fileIds; } } // Build Entry Record $submissionRecord->formId = $submission->formId; $submissionRecord->title = $submission->title; $submissionRecord->submission = $submission->submission; $submissionRecord->validate(); $submission->addErrors($submissionRecord->getErrors()); // Save To Database if (!$submission->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if (craft()->elements->saveElement($submission)) { $submissionRecord->id = $submission->id; $submissionRecord->save(false); if ($transaction !== null) { $transaction->commit(); } return $submissionRecord->id; } else { return false; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }
/** * Adds support for Twitter user photo resource paths. * * @param string $path * @return string|null */ public function getResourcePath($path) { // Are they requesting a Twitter user image? if (strncmp($path, 'twitteruserimages/', 18) === 0) { $parts = array_merge(array_filter(explode('/', $path))); if (count($parts) != 3) { return; } $userId = $parts[1]; $size = $parts[2]; $imageSizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73); if (is_numeric($size) && ($sizeKey = array_search($size, $imageSizes)) !== false) { $size = $sizeKey; } $baseUserImagePath = craft()->path->getRuntimePath() . 'twitter/userimages/' . $userId . '/'; $sizedFolderPath = $baseUserImagePath . $size . '/'; // Have we already downloaded this user's image at this size? $contents = IOHelper::getFolderContents($sizedFolderPath, false); if ($contents) { return $contents[0]; } else { // Do we have the original image? if (!is_numeric($size)) { if ($size == 'original' || array_key_exists($size, $imageSizes)) { $sizeName = $size; } else { return; } } else { $sizeName = 'original'; foreach ($imageSizes as $sizeKey => $sizeSize) { if ($size <= $sizeSize) { $sizeName = $sizeKey; break; } } } $originalFolderPath = $baseUserImagePath . $sizeName . '/'; $contents = IOHelper::getFolderContents($originalFolderPath, false); if ($contents) { $originalPath = $contents[0]; } else { // OK, let's fetch it then $user = craft()->twitter->getUserById($userId); if (!$user || empty($user['profile_image_url'])) { return; } $url = $user['profile_image_url']; if ($sizeName != 'normal') { if ($sizeName == 'original') { $url = str_replace('_normal', '', $url); } else { $url = str_replace('_normal', '_' . $sizeName, $url); } } IOHelper::ensureFolderExists($originalFolderPath); $fileName = pathinfo($url, PATHINFO_BASENAME); $originalPath = $originalFolderPath . $fileName; $response = \Guzzle\Http\StaticClient::get($url, array('save_to' => $originalPath)); if (!$response->isSuccessful()) { return; } } // If they were actually requesting "mini", "normal", "bigger", or "original", we're done if (!is_numeric($size)) { return $originalPath; } // Resize it to the requested size $fileName = pathinfo($originalPath, PATHINFO_BASENAME); $sizedPath = $sizedFolderPath . $fileName; IOHelper::ensureFolderExists($sizedFolderPath); craft()->images->loadImage($originalPath)->scaleAndCrop($size, $size)->saveAs($sizedPath); return $sizedPath; } } }
/** * Start import task. */ public function actionImport() { // Get import post $settings = craft()->request->getRequiredPost('import'); // Get file $file = craft()->request->getParam('file'); // Get mapping fields $map = craft()->request->getParam('fields'); $unique = craft()->request->getParam('unique'); // Get rows/steps from file $rows = count(craft()->import->data($file)); // Proceed when atleast one row if ($rows) { // Set more settings $settings = array_merge(array('file' => $file, 'rows' => $rows, 'map' => $map, 'unique' => $unique), $settings); // Create history $history = craft()->import_history->start($settings); // Add history to settings $settings['history'] = $history; // UNCOMMENT FOR DEBUGGING //craft()->import->debug($settings, $history, 1); // Determine new folder to save original importfile $folder = dirname($file) . '/' . $history . '/'; IOHelper::ensureFolderExists($folder); // Move the file to its history folder IOHelper::move($file, $folder . basename($file)); // Update the settings with the new file location $settings['file'] = $folder . basename($file); // Create the import task $task = craft()->tasks->createTask('Import', Craft::t('Importing') . ' ' . basename($file), $settings); // Notify user craft()->userSession->setNotice(Craft::t('Import process started.')); // Redirect to history $this->redirect('import/history?task=' . $task->id); } else { // Redirect to history $this->redirect('import/history'); } }
/** * 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) { // If there's no dynamic tags in the set path, or if the element has already been saved, we con use the real // folder if (!empty($this->element->id) || !empty($settings->useSingleFolder) && strpos($settings->singleUploadLocationSubpath, '{') === false || empty($settings->useSingleFolder) && strpos($settings->defaultUploadLocationSubpath, '{') === false) { // Use the appropriate settings for folder determination if (empty($settings->useSingleFolder)) { $folderId = $this->_resolveSourcePathToFolderId($settings->defaultUploadLocationSource, $settings->defaultUploadLocationSubpath); } else { $folderId = $this->_resolveSourcePathToFolderId($settings->singleUploadLocationSource, $settings->singleUploadLocationSubpath); } } else { // New element, so we default to User's upload folder for this field $userModel = craft()->userSession->getUser(); $userFolder = craft()->assets->getUserFolder($userModel); $folderName = 'field_' . $this->model->id; $elementFolder = craft()->assets->findFolder(array('parentId' => $userFolder->id, 'name' => $folderName)); if (!$elementFolder) { $folderId = $this->_createSubFolder($userFolder, $folderName); } else { $folderId = $elementFolder->id; } IOHelper::ensureFolderExists(craft()->path->getAssetsTempSourcePath() . $folderName); } return $folderId; }
/** * Returns the path to the file cache folder. * * This will be located at craft/storage/runtime/cache/ by default, but that can be overridden with the 'cachePath' * config setting in craft/config/filecache.php. * * @return string The path to the file cache folder. */ public function getCachePath() { $path = craft()->config->get('cachePath', ConfigFile::FileCache); if (!$path) { $path = $this->getRuntimePath() . 'cache/'; } IOHelper::ensureFolderExists($path); return $path; }
/** * Create an export file. * * @param AmForms_ExportModel $export * @param AmForms_FormModel $form * * @return string */ private function _createExportFile(AmForms_ExportModel $export, AmForms_FormModel $form) { // Determine folder $folder = $this->_getExportPath(); IOHelper::ensureFolderExists($folder); // What type of export? $fileExtension = $export->submissions ? '.zip' : '.csv'; // Create export file $file = $folder . $form->handle . $fileExtension; $counter = 1; while (!IOHelper::createFile($file)) { $file = $folder . $form->handle . $counter . $fileExtension; $counter++; } // Only add columns when we are not working with a zip file if (!$export->submissions) { // Add columns to export file $exportFile = fopen($file, 'w'); fputcsv($exportFile, $this->_getExportColumns($export, $form), $this->_delimiter); fclose($exportFile); } // Return file path return $file; }