/**
  * Prepare asset for cropping.
  */
 public function actionPrepareForCrop()
 {
     $this->requireAjaxRequest();
     $elementId = craft()->request->getParam('elementId');
     // Get the asset file
     $asset = craft()->assets->getFileById($elementId);
     $source = $asset->getSource();
     $sourceType = $source->getSourceType();
     $file = $sourceType->getLocalCopy($asset);
     try {
         // Test if we will be able to perform image actions on this image
         if (!craft()->images->checkMemoryForImage($file)) {
             IOHelper::deleteFile($file);
             $this->returnErrorJson(Craft::t('The selected image is too large.'));
         }
         // Scale to fit 500x500 for fitting in CP modal
         craft()->images->loadImage($file)->scaleToFit(500, 500, false)->saveAs($file);
         list($width, $height) = ImageHelper::getImageSize($file);
         // If the file is in the format badscript.php.gif perhaps.
         if ($width && $height) {
             $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => $asset->url, 'width' => $width, 'height' => $height, 'fileName' => $asset->filename));
             $this->returnJson(array('html' => $html));
         }
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
 }
 /**
  * Returns an array of the width and height of the image.
  *
  * @return array
  */
 public function getSize()
 {
     if (!isset($this->size)) {
         $size = ImageHelper::getImageSize($this->path);
         $this->size = array($size[0], $size[1]);
     }
     return $this->size;
 }
 /**
  * Loads an image from a file system path.
  *
  * @param string $path
  *
  * @throws Exception
  * @return Image
  */
 public function loadImage($path)
 {
     if (!IOHelper::fileExists($path)) {
         throw new Exception(Craft::t('No file exists at the path “{path}”', array('path' => $path)));
     }
     list($width, $height) = ImageHelper::getImageSize($path);
     $svg = IOHelper::getFileContents($path);
     // If the size is defined by viewbox only, add in width and height attributes
     if (!preg_match(static::SVG_WIDTH_RE, $svg) && preg_match(static::SVG_HEIGHT_RE, $svg)) {
         $svg = preg_replace(static::SVG_TAG_RE, "<svg width=\"{$width}px\" height=\"{$height}px\" ", $svg);
     }
     $this->_height = $height;
     $this->_width = $width;
     $this->_svgContent = $svg;
     return $this;
 }
 /**
  * Upload a logo for the admin panel.
  *
  * @return null
  */
 public function actionUploadSiteImage()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     $type = craft()->request->getRequiredPost('type');
     if (!in_array($type, $this->_allowedTypes)) {
         $this->returnErrorJson(Craft::t('That is not an accepted site image type.'));
     }
     // Upload the file and drop it in the temporary folder
     $file = UploadedFile::getInstanceByName('image-upload');
     try {
         // Make sure a file was uploaded
         if ($file) {
             $fileName = AssetsHelper::cleanAssetName($file->getName());
             if (!ImageHelper::isImageManipulatable($file->getExtensionName())) {
                 throw new Exception(Craft::t('The uploaded file is not an image.'));
             }
             $folderPath = craft()->path->getTempUploadsPath();
             IOHelper::ensureFolderExists($folderPath);
             IOHelper::clearFolder($folderPath, true);
             move_uploaded_file($file->getTempName(), $folderPath . $fileName);
             // Test if we will be able to perform image actions on this image
             if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) {
                 IOHelper::deleteFile($folderPath . $fileName);
                 $this->returnErrorJson(Craft::t('The uploaded image is too large'));
             }
             list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName);
             if (IOHelper::getExtension($fileName) != 'svg') {
                 craft()->images->cleanImage($folderPath . $fileName);
             } else {
                 craft()->images->loadImage($folderPath . $fileName)->saveAs($folderPath . $fileName);
             }
             $constraint = 500;
             // If the file is in the format badscript.php.gif perhaps.
             if ($width && $height) {
                 // Never scale up the images, so make the scaling factor always <= 1
                 $factor = min($constraint / $width, $constraint / $height, 1);
                 $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName));
                 $this->returnJson(array('html' => $html));
             }
         }
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('There was an error uploading your photo'));
 }
 /**
  * Upload 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'));
             }
             list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName);
             if (IOHelper::getExtension($fileName) != 'svg') {
                 craft()->images->cleanImage($folderPath . $fileName);
             } else {
                 // Resave svg files as png
                 $newFilename = preg_replace('/\\.svg$/i', '.png', $fileName);
                 craft()->images->loadImage($folderPath . $fileName, $width, $height)->saveAs($folderPath . $newFilename);
                 IOHelper::deleteFile($folderPath . $fileName);
                 $fileName = $newFilename;
             }
             $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'));
 }
 /**
  * @inheritDoc BaseAssetSourceType::processIndex()
  *
  * @param $sessionId
  * @param $offset
  *
  * @return mixed
  */
 public function processIndex($sessionId, $offset)
 {
     $indexEntryModel = craft()->assetIndexing->getIndexEntry($this->model->id, $sessionId, $offset);
     if (empty($indexEntryModel)) {
         return false;
     }
     $uriPath = $indexEntryModel->uri;
     $fileModel = $this->indexFile($uriPath);
     $this->_prepareForRequests();
     if ($fileModel) {
         $settings = $this->getSettings();
         craft()->assetIndexing->updateIndexEntryRecordId($indexEntryModel->id, $fileModel->id);
         $fileModel->size = $indexEntryModel->size;
         $fileInfo = $this->_s3->getObjectInfo($settings->bucket, $this->_getPathPrefix() . $uriPath);
         $targetPath = craft()->path->getAssetsImageSourcePath() . $fileModel->id . '.' . IOHelper::getExtension($fileModel->filename);
         $timeModified = new DateTime('@' . $fileInfo['time']);
         if ($fileModel->kind == 'image' && ($fileModel->dateModified != $timeModified || !IOHelper::fileExists($targetPath))) {
             $this->_s3->getObject($settings->bucket, $this->_getPathPrefix() . $indexEntryModel->uri, $targetPath);
             clearstatcache();
             list($width, $height) = ImageHelper::getImageSize($targetPath);
             $fileModel->width = $width;
             $fileModel->height = $height;
             // Store the local source or delete - maxCacheCloudImageSize is king.
             craft()->assetTransforms->storeLocalSource($targetPath, $targetPath);
             craft()->assetTransforms->queueSourceForDeletingIfNecessary($targetPath);
         }
         $fileModel->dateModified = $timeModified;
         craft()->assets->storeFile($fileModel);
         return $fileModel->id;
     }
     return false;
 }
 /**
  * Submit Entry
  *
  */
 public function actionSubmitEntry()
 {
     $this->requirePostRequest();
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // VARIABLES
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $files = '';
     $ajax = false;
     $passedValidation = true;
     $validationErrors = [];
     $submissionErrorMessage = [];
     $customSuccessMessage = '';
     $customErrorMessage = '';
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $form = craft()->formBuilder2_entry->getFormByHandle(craft()->request->getPost('formHandle'));
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM SUBMISSION
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $formFields = $form->fieldLayout->getFieldLayout()->getFields();
     // Get all form fields
     $submission = craft()->request->getPost();
     // Get all values from the submitted form
     $submissionData = $this->filterSubmissionKeys($submission);
     // Fillter out unused submission data
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM ATTRIBUTES
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $attributes = $form->getAttributes();
     $formSettings = $attributes['formSettings'];
     $spamProtectionSettings = $attributes['spamProtectionSettings'];
     $messageSettings = $attributes['messageSettings'];
     $notificationSettings = $attributes['notificationSettings'];
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM SETTINGS ||| (1) Custom Redirect, (2) File Uploads, (3) Ajax Submissions
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // (1) Custom Redirect
     if ($formSettings['formRedirect']['customRedirect'] != '') {
         $redirectUrl = $formSettings['formRedirect']['customRedirectUrl'];
     }
     // (2) File Uploads
     if ($formSettings['hasFileUploads'] == '1') {
         foreach ($formFields as $key => $value) {
             $field = $value->getField();
             switch ($field->type) {
                 case 'Assets':
                     foreach ($_FILES as $key => $value) {
                         if (!$value['tmp_name'] == '') {
                             $fileModel = new AssetFileModel();
                             $folderId = $field->settings['singleUploadLocationSource'][0];
                             $sourceId = $field->settings['singleUploadLocationSource'][0];
                             $fileModel->originalName = $value['tmp_name'];
                             $fileModel->sourceId = $sourceId;
                             $fileModel->folderId = $folderId;
                             $fileModel->filename = IOHelper::getFileName($value['name']);
                             $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($value['name']));
                             $fileModel->size = filesize($value['tmp_name']);
                             if ($value['tmp_name']) {
                                 $fileModel->dateModified = IOHelper::getLastTimeModified($value['tmp_name']);
                             }
                             if ($fileModel->kind == 'image') {
                                 list($width, $height) = ImageHelper::getImageSize($value['tmp_name']);
                                 $fileModel->width = $width;
                                 $fileModel->height = $height;
                             }
                             $files[$key] = $fileModel;
                         }
                     }
                     break;
             }
         }
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM CUSTOM MESSAGES ||| (1) Success Message (2) Error Message
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // (1) Success Message
     $customSuccessMessage = $messageSettings['successMessage'] ? $messageSettings['successMessage'] : Craft::t('Submission was successful.');
     // (2) Error Message
     $customErrorMessage = $messageSettings['errorMessage'] ? $messageSettings['errorMessage'] : Craft::t('There was a problem with your submission.');
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // (3) Ajax Submissions
     if ($formSettings['ajaxSubmit'] == '1') {
         $this->requireAjaxRequest();
         $ajax = true;
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FORM SPAM PROTECTION ||| (1) Timed Method (2) Honeypot Method
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // (1) Timed Method
     if ($spamProtectionSettings['spamTimeMethod'] == '1') {
         $formSubmissionTime = (int) craft()->request->getPost('spamTimeMethod');
         $submissionDuration = time() - $formSubmissionTime;
         $allowedTime = (int) $spamProtectionSettings['spamTimeMethodTime'];
         if ($submissionDuration < $allowedTime) {
             if ($ajax) {
                 $this->returnJson(['validationErrors' => [Craft::t('You submitted too fast, you are robot!')], 'customErrorMessage' => $customErrorMessage]);
             } else {
                 $spamTimedMethod = false;
                 $submissionErrorMessage[] = Craft::t('You submitted too fast, you are robot!');
             }
         } else {
             $spamTimedMethod = true;
         }
     } else {
         $spamTimedMethod = true;
     }
     // (2) Honeypot Method
     if ($spamProtectionSettings['spamHoneypotMethod'] == '1') {
         $honeypotField = craft()->request->getPost('email-address-new');
         if ($honeypotField != '') {
             if ($ajax) {
                 $this->returnJson(['validationErrors' => [Craft::t('You tried the honey, you are robot bear!')], 'customErrorMessage' => $customErrorMessage]);
             } else {
                 $spamHoneypotMethod = false;
                 $submissionErrorMessage[] = Craft::t('You tried the honey, you are robot bear!');
             }
         } else {
             $spamHoneypotMethod = true;
         }
     } else {
         $spamHoneypotMethod = true;
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // NEW FORM MODEL
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $submissionEntry = new FormBuilder2_EntryModel();
     $submissionEntry->formId = $form->id;
     $submissionEntry->title = $form->name;
     $submissionEntry->files = $files;
     $submissionEntry->submission = $submissionData;
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // FAILED SUBMISSION REDIRECT W/MESSAGES (Spam Protection)
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     if ($submissionErrorMessage) {
         craft()->userSession->setFlash('error', $customErrorMessage);
         craft()->urlManager->setRouteVariables(array('errors' => $submissionErrorMessage));
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // VALIDATE SUBMISSION DATA
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     $validation = craft()->formBuilder2_entry->validateEntry($form, $submissionData);
     // if ($validation != '') {
     if (!empty($validation)) {
         if ($ajax) {
             $this->returnJson(['passedValidation' => false, 'validationErrors' => $validation, 'customErrorMessage' => $customErrorMessage]);
         } else {
             craft()->userSession->setFlash('error', $customErrorMessage);
             $passedValidation = false;
             return craft()->urlManager->setRouteVariables(['value' => $submissionData, 'errors' => $validation]);
         }
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     // PROCESS SUBMISSION ENTRY
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     if (!$submissionErrorMessage && $passedValidation && $spamTimedMethod && $spamHoneypotMethod) {
         $submissionResponseId = craft()->formBuilder2_entry->processSubmissionEntry($submissionEntry);
         if ($submissionResponseId) {
             // Notify Admin of Submission
             if ($notificationSettings['notifySubmission'] == '1') {
                 $this->notifyAdminOfSubmission($submissionResponseId, $form);
             }
             // Successful Submission Messages
             if ($ajax) {
                 $this->returnJson(['success' => true, 'customSuccessMessage' => $customSuccessMessage]);
             } else {
                 craft()->userSession->setFlash('success', $customSuccessMessage);
                 if ($formSettings['formRedirect']['customRedirect'] != '') {
                     $this->redirect($redirectUrl);
                 } else {
                     $this->redirectToPostedUrl();
                 }
             }
         } else {
             // Submission Error Messages
             if ($ajax) {
                 $this->returnJson(['error' => true, 'customErrorMessage' => $customErrorMessage]);
             } else {
                 craft()->userSession->setFlash('error', $customErrorMessage);
                 return craft()->urlManager->setRouteVariables(['value' => $submissionData, 'errors' => $validation]);
             }
         }
     }
     // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 }
 /**
  * Insert a file into a folder by it's local path.
  *
  * @param string           $localFilePath    The local file path of the file to insert.
  * @param AssetFolderModel $folder           The assetFolderModel where the file should be uploaded to.
  * @param string           $filename         The name of the file to insert.
  * @param bool             $preventConflicts If set to true, will ensure that a conflict is not encountered by
  *                                           checking the file name prior insertion.
  *
  * @return AssetOperationResponseModel
  */
 public function insertFileByPath($localFilePath, AssetFolderModel $folder, $filename, $preventConflicts = false)
 {
     // Fire an 'onBeforeUploadAsset' event
     $event = new Event($this, array('path' => $localFilePath, 'folder' => $folder, 'filename' => $filename));
     craft()->assets->onBeforeUploadAsset($event);
     if ($event->performAction) {
         // We hate Javascript and PHP in our image files.
         if (IOHelper::getFileKind(IOHelper::getExtension($localFilePath)) == 'image' && ImageHelper::isImageManipulatable(IOHelper::getExtension($localFilePath)) && IOHelper::getExtension($localFilePath) != 'svg') {
             craft()->images->cleanImage($localFilePath);
         }
         $mobileUpload = false;
         if (IOHelper::getFileName($filename, false) == "image" && craft()->request->isMobileBrowser(true)) {
             $mobileUpload = true;
             $date = DateTimeHelper::currentUTCDateTime();
             $filename = "image_" . $date->format('Ymd_His') . "." . IOHelper::getExtension($filename);
         }
         if ($preventConflicts) {
             $newFileName = $this->getNameReplacementInFolder($folder, $filename);
             $response = $this->insertFileInFolder($folder, $localFilePath, $newFileName);
         } else {
             $response = $this->insertFileInFolder($folder, $localFilePath, $filename);
             // Naming conflict. create a new file and ask the user what to do with it
             if ($response->isConflict()) {
                 $newFileName = $this->getNameReplacementInFolder($folder, $filename);
                 $conflictResponse = $response;
                 $response = $this->insertFileInFolder($folder, $localFilePath, $newFileName);
             }
         }
         if ($response->isSuccess()) {
             $fileModel = new AssetFileModel();
             $title = $fileModel->generateAttributeLabel(IOHelper::getFileName($filename, false));
             // If there were double spaces, it's because the filename had a space followed by a
             // capital letter. We convert the space to a dash, but Yii thinks it's a new "word"
             // and adds another space.
             $fileModel->getContent()->title = str_replace('  ', ' ', $title);
             $filename = IOHelper::getFileName($response->getDataItem('filePath'));
             $fileModel->filename = IOHelper::getFileName($filename);
             $fileModel->sourceId = $this->model->id;
             $fileModel->folderId = $folder->id;
             $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($filename));
             $fileModel->size = filesize($localFilePath);
             $fileModel->dateModified = IOHelper::getLastTimeModified($localFilePath);
             if ($fileModel->kind == 'image') {
                 list($width, $height) = ImageHelper::getImageSize($localFilePath);
                 $fileModel->width = $width;
                 $fileModel->height = $height;
             }
             if ($mobileUpload) {
                 $fileModel->getContent()->title = Craft::t('Mobile Upload');
             }
             craft()->assets->storeFile($fileModel);
             if (!$this->isSourceLocal() && $fileModel->kind == 'image') {
                 craft()->assetTransforms->storeLocalSource($localFilePath, 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;
             }
             $response->setDataItem('fileId', $fileModel->id);
         }
     } else {
         $response = new AssetOperationResponseModel();
         $response->setError(Craft::t('The file upload was cancelled.'));
     }
     return $response;
 }
 /**
  * @inheritDoc BaseAssetSourceType::processIndex()
  *
  * @param string $sessionId
  * @param int    $offset
  *
  * @return mixed
  */
 public function processIndex($sessionId, $offset)
 {
     $indexEntryModel = craft()->assetIndexing->getIndexEntry($this->model->id, $sessionId, $offset);
     if (empty($indexEntryModel)) {
         return false;
     }
     // Make sure we have a trailing slash. Some people love to skip those.
     $uploadPath = $this->getSourceFileSystemPath();
     $file = $indexEntryModel->uri;
     // This is the part of the path that actually matters
     $uriPath = mb_substr($file, mb_strlen($uploadPath));
     $fileModel = $this->indexFile($uriPath);
     if ($fileModel) {
         craft()->assetIndexing->updateIndexEntryRecordId($indexEntryModel->id, $fileModel->id);
         $fileModel->size = $indexEntryModel->size;
         $fileModel->dateModified = IOHelper::getLastTimeModified($indexEntryModel->uri);
         if ($fileModel->kind == 'image') {
             list($width, $height) = ImageHelper::getImageSize($indexEntryModel->uri);
             $fileModel->width = $width;
             $fileModel->height = $height;
         }
         craft()->assets->storeFile($fileModel);
         return $fileModel->id;
     }
     return false;
 }
Ejemplo n.º 10
0
 /**
  * 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.'));
 }
 /**
  * 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'));
             }
             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('userphotos/temp/' . $userName . '/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName));
                 $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.'));
 }
 /**
  * Submit Entry
  *
  */
 public function actionSubmitEntry()
 {
     $form = craft()->formBuilder2_entry->getFormByHandle(craft()->request->getPost('formHandle'));
     // Set Up Form Submission
     $formFields = $form->fieldLayout->getFieldLayout()->getFields();
     $submission = craft()->request->getPost();
     $submissionData = $this->filterSubmissionKeys($submission);
     // Defaults
     $attributes = $form->getAttributes();
     $formSettings = $attributes['formSettings'];
     $spamProtectionSettings = $attributes['spamProtectionSettings'];
     $messageSettings = $attributes['messageSettings'];
     $notificationSettings = $attributes['notificationSettings'];
     $files = '';
     $errorMessage = [];
     // Prepare submissionEntry for processing
     $submissionEntry = new FormBuilder2_EntryModel();
     // Using Ajax
     if ($formSettings['ajaxSubmit'] == '1') {
         $this->requireAjaxRequest();
     } else {
         $this->requirePostRequest();
     }
     // Custom Redirect
     if ($formSettings['formRedirect']['customRedirect'] != '') {
         $redirectUrl = $formSettings['formRedirect']['customRedirectUrl'];
     }
     // Spam Protection | Timed Method
     if ($spamProtectionSettings['spamTimeMethod'] == '1') {
         $formSubmissionTime = (int) craft()->request->getPost('spamTimeMethod');
         $submissionDuration = time() - $formSubmissionTime;
         $allowedTime = (int) $spamProtectionSettings['spamTimeMethodTime'];
         if ($submissionDuration < $allowedTime) {
             $spamMethodOne = false;
             $errorMessage[] = Craft::t('You submitted too fast, you are robot!');
         } else {
             $spamMethodOne = true;
         }
     } else {
         $spamMethodOne = true;
     }
     // Spam Protection | Honeypot Method
     if ($spamProtectionSettings['spamHoneypotMethod'] == '1') {
         $honeypotField = craft()->request->getPost('email-address-new');
         if ($honeypotField != '') {
             $spamMethodTwo = false;
             $errorMessage[] = Craft::t('You tried the honey, you are robot bear!');
         } else {
             $spamMethodTwo = true;
         }
     } else {
         $spamMethodTwo = true;
     }
     // Validate Required Fields
     $validateRequired = craft()->formBuilder2_entry->validateEntry($form, $submissionData);
     // File Uploads
     if ($formSettings['hasFileUploads'] == '1') {
         foreach ($formFields as $key => $value) {
             $field = $value->getField();
             switch ($field->type) {
                 case 'Assets':
                     foreach ($_FILES as $key => $value) {
                         if (!$value['tmp_name'] == '') {
                             $fileModel = new AssetFileModel();
                             $folderId = $field->settings['singleUploadLocationSource'][0];
                             $sourceId = $field->settings['singleUploadLocationSource'][0];
                             $fileModel->originalName = $value['tmp_name'];
                             $fileModel->sourceId = $sourceId;
                             $fileModel->folderId = $folderId;
                             $fileModel->filename = IOHelper::getFileName($value['name']);
                             $fileModel->kind = IOHelper::getFileKind(IOHelper::getExtension($value['name']));
                             $fileModel->size = filesize($value['tmp_name']);
                             if ($value['tmp_name']) {
                                 $fileModel->dateModified = IOHelper::getLastTimeModified($value['tmp_name']);
                             }
                             if ($fileModel->kind == 'image') {
                                 list($width, $height) = ImageHelper::getImageSize($value['tmp_name']);
                                 $fileModel->width = $width;
                                 $fileModel->height = $height;
                             }
                             $files[$key] = $fileModel;
                         }
                     }
                     break;
             }
         }
     }
     $submissionEntry->formId = $form->id;
     $submissionEntry->title = $form->name;
     $submissionEntry->files = $files;
     $submissionEntry->submission = $submissionData;
     // Process Errors
     if ($errorMessage) {
         craft()->urlManager->setRouteVariables(array('errors' => $errorMessage));
     }
     // Process Submission Entry
     if (!$errorMessage && $spamMethodOne && $spamMethodTwo && $validateRequired) {
         $submissionResponseId = craft()->formBuilder2_entry->processSubmissionEntry($submissionEntry);
         // Notify Admin of Submission
         if ($notificationSettings['notifySubmission'] == '1') {
             $this->notifyAdminOfSubmission($submissionResponseId, $form);
         }
         // Messages
         if ($formSettings['ajaxSubmit'] == '1') {
             $this->returnJson(['success' => true, 'message' => $messageSettings['successMessage'], 'form' => $form]);
         } else {
             craft()->userSession->setFlash('success', $messageSettings['successMessage']);
             if ($formSettings['formRedirect']['customRedirect'] != '') {
                 $this->redirect($redirectUrl);
             } else {
                 $this->redirectToPostedUrl();
             }
         }
     } else {
         if ($formSettings['ajaxSubmit'] == '1') {
             $this->returnJson(['error' => true, 'message' => $messageSettings['errorMessage'], 'form' => $form]);
         } else {
             craft()->userSession->setFlash('error', $messageSettings['errorMessage']);
         }
     }
 }
 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);
             }
         }
     }
 }
Ejemplo n.º 14
0
 /**
  * Insert a file into a folder by it's local path.
  *
  * @param string           $localFilePath    The local file path of the file to insert.
  * @param AssetFolderModel $folder           The assetFolderModel where the file should be uploaded to.
  * @param string           $fileName         The name of the file to insert.
  * @param bool             $preventConflicts If set to true, will ensure that a conflict is not encountered by
  *                                           checking the file name prior insertion.
  *
  * @return AssetOperationResponseModel
  */
 public function insertFileByPath($localFilePath, AssetFolderModel $folder, $fileName, $preventConflicts = false)
 {
     // Fire an 'onBeforeUploadAsset' event
     $event = new Event($this, array('path' => $localFilePath, 'folder' => $folder, 'filename' => $fileName));
     craft()->assets->onBeforeUploadAsset($event);
     if ($event->performAction) {
         // We hate Javascript and PHP in our image files.
         if (IOHelper::getFileKind(IOHelper::getExtension($localFilePath)) == 'image' && ImageHelper::isImageManipulatable(IOHelper::getExtension($localFilePath)) && IOHelper::getExtension($localFilePath) != 'svg') {
             craft()->images->cleanImage($localFilePath);
         }
         if ($preventConflicts) {
             $newFileName = $this->getNameReplacement($folder, $fileName);
             $response = $this->insertFileInFolder($folder, $localFilePath, $newFileName);
         } else {
             $response = $this->insertFileInFolder($folder, $localFilePath, $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, $localFilePath, $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($localFilePath);
             $fileModel->dateModified = IOHelper::getLastTimeModified($localFilePath);
             if ($fileModel->kind == 'image') {
                 list($width, $height) = ImageHelper::getImageSize($localFilePath);
                 $fileModel->width = $width;
                 $fileModel->height = $height;
             }
             craft()->assets->storeFile($fileModel);
             if (!$this->isSourceLocal() && $fileModel->kind == 'image') {
                 craft()->assetTransforms->storeLocalSource($localFilePath, 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;
             }
             $response->setDataItem('fileId', $fileModel->id);
         }
     } else {
         $response = new AssetOperationResponseModel();
         $response->setError(Craft::t('The file upload was cancelled.'));
     }
     return $response;
 }
Ejemplo n.º 15
0
 /**
  * Get crop values and make up for CP fitting.
  *
  * @param string $file
  *
  * @return array
  */
 protected function getCropValues($file)
 {
     // Get saved crop values from db
     list($x1, $x2, $y1, $y2) = $this->getContent()->{$this->handle};
     // Get original image size
     list($width, $height) = ImageHelper::getImageSize($file);
     // Calculate factor
     $factor = $width / 500;
     // Return fixed crop values
     return array($x1 * $factor, $x2 * $factor, $y1 * $factor, $y2 * $factor);
 }
Ejemplo n.º 16
0
 public function getThumbnail($thumbWidth, $thumbHeight)
 {
     list($width, $height) = ImageHelper::getImageSize($this->image);
 }