/**
  * 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());
     }
 }
 /**
  * Download zipfile.
  *
  * @param array  $files
  * @param string $filename
  *
  * @return string
  */
 public function download($files, $filename)
 {
     // Get assets
     $criteria = craft()->elements->getCriteria(ElementType::Asset);
     $criteria->id = $files;
     $criteria->limit = null;
     $assets = $criteria->find();
     // Set destination zip
     $destZip = craft()->path->getTempPath() . $filename . '_' . time() . '.zip';
     // Create zip
     $zip = new \ZipArchive();
     // Open zip
     if ($zip->open($destZip, $zip::CREATE) === true) {
         // Loop through assets
         foreach ($assets as $asset) {
             // Get asset source
             $source = $asset->getSource();
             // Get asset source type
             $sourceType = $source->getSourceType();
             // Get asset file
             $file = $sourceType->getLocalCopy($asset);
             // Add to zip
             $zip->addFromString($asset->filename, IOHelper::getFileContents($file));
             // Remove the file
             IOHelper::deleteFile($file);
         }
         // Close zip
         $zip->close();
         // Return zip destination
         return $destZip;
     }
     // Something went wrong
     throw new Exception(Craft::t('Failed to generate the zipfile'));
 }
예제 #3
0
 /**
  * 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.'));
 }
예제 #4
0
 /**
  * Downloads a file and cleans up old temporary assets
  */
 public function actionDownloadFile()
 {
     // Clean up temp assets files that are more than a day old
     $fileResults = array();
     $files = IOHelper::getFiles(craft()->path->getTempPath(), true);
     foreach ($files as $file) {
         $lastModifiedTime = IOHelper::getLastTimeModified($file, true);
         if (substr(IOHelper::getFileName($file, false, true), 0, 6) === "assets" && DateTimeHelper::currentTimeStamp() - $lastModifiedTime->getTimestamp() >= 86400) {
             IOHelper::deleteFile($file);
         }
     }
     // Sort out the file we want to download
     $id = craft()->request->getParam('id');
     $criteria = craft()->elements->getCriteria(ElementType::Asset);
     $criteria->id = $id;
     $asset = $criteria->first();
     if ($asset) {
         // Get a local copy of the file
         $sourceType = craft()->assetSources->getSourceTypeById($asset->sourceId);
         $localCopy = $sourceType->getLocalCopy($asset);
         // Send it to the browser
         craft()->request->sendFile($asset->filename, IOHelper::getFileContents($localCopy), array('forceDownload' => true));
         craft()->end();
     }
 }
 /**
  * {@inheritdoc}
  */
 public static function tearDownAfterClass()
 {
     // Remove test file
     $file = __DIR__ . '/../translations/test.php';
     IOHelper::deleteFile($file);
     // Tear down parent
     parent::tearDownAfterClass();
 }
 private function deleteTempFiles($fileName)
 {
     $tempPath = craft()->path->getTempPath();
     IOHelper::deleteFile($tempPath . $fileName, true);
     $info = pathinfo($fileName);
     $fileNameNoExtension = $info['filename'];
     $ext = $info['extension'];
     IOHelper::deleteFile($tempPath . $fileNameNoExtension . '-temp.' . $ext, true);
 }
 public function resize($sourceId, $path, $width, $height)
 {
     try {
         $settings = craft()->imageResizer->getSettings();
         $image = craft()->images->loadImage($path);
         $filename = basename($path);
         // We can have settings globally, or per asset source. Check!
         // Our maximum width/height for assets from plugin settings
         $imageWidth = craft()->imageResizer->getSettingForAssetSource($sourceId, 'imageWidth');
         $imageHeight = craft()->imageResizer->getSettingForAssetSource($sourceId, 'imageHeight');
         // Allow for overrides passed on-demand
         $imageWidth = $width ? $width : $imageWidth;
         $imageHeight = $height ? $height : $imageHeight;
         // Lets check to see if this image needs resizing. Split into two steps to ensure
         // proper aspect ratio is preserved and no upscaling occurs.
         $hasResized = false;
         if ($image->getWidth() > $imageWidth) {
             $hasResized = true;
             $this->_resizeImage($image, $imageWidth, null);
         }
         if ($image->getHeight() > $imageHeight) {
             $hasResized = true;
             $this->_resizeImage($image, null, $imageHeight);
         }
         if ($hasResized) {
             // Set image quality - but normalise (for PNG)!
             $image->setQuality(craft()->imageResizer->getImageQuality($filename));
             // If we're checking for larger images
             if ($settings->skipLarger) {
                 // Save this resized image in a temporary location - we need to test filesize difference
                 $tempPath = AssetsHelper::getTempFilePath($filename);
                 $image->saveAs($tempPath);
                 clearstatcache();
                 // Lets check to see if this resize resulted in a larger file - revert if so.
                 if (filesize($tempPath) < filesize($path)) {
                     $image->saveAs($path);
                     // Its a smaller file - properly save
                 } else {
                     ImageResizerPlugin::log('Did not resize ' . $filename . ' as it would result in a larger file.', LogLevel::Info, true);
                 }
                 // Delete our temp file we test filesize with
                 IOHelper::deleteFile($tempPath, true);
             } else {
                 $image->saveAs($path);
             }
         }
         return true;
     } catch (\Exception $e) {
         ImageResizerPlugin::log($e->getMessage(), LogLevel::Error, true);
         return false;
     }
 }
예제 #8
0
 /**
  * Performs the tool's action.
  *
  * @param array $params
  * @return array
  */
 public function performAction($params = array())
 {
     $file = craft()->db->backup();
     if (IOHelper::fileExists($file) && isset($params['downloadBackup']) && (bool) $params['downloadBackup']) {
         $destZip = craft()->path->getTempPath() . IOHelper::getFileName($file, false) . '.zip';
         if (IOHelper::fileExists($destZip)) {
             IOHelper::deleteFile($destZip, true);
         }
         IOHelper::createFile($destZip);
         if (Zip::add($destZip, $file, craft()->path->getDbBackupPath())) {
             return array('backupFile' => IOHelper::getFileName($destZip, false));
         }
     }
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $filesToDelete = array('elementtypes/MatrixRecordElementType.php', 'etc/assets/fileicons/56.png', 'etc/console/commands/MigrateCommand.php', 'etc/console/commands/QuerygenCommand.php', 'migrations/m130917_000000_drop_users_enctype.php', 'migrations/m130917_000001_big_names_and_handles.php', 'migrations/m130917_000002_entry_types.php', 'migrations/m130917_000003_section_types.php', 'migrations/m131105_000000_content_column_field_prefixes.php', 'migrations/m131105_000001_add_missing_content_and_i18n_rows.php', 'migrations/m131105_000001_element_content.php', 'migrations/m131105_000002_schema_version.php', 'migrations/m131105_000003_field_contexts.php', 'migrations/m131105_000004_matrix.php', 'migrations/m131105_000004_matrix_blocks.php', 'migrations/m131105_000005_correct_tag_field_layouts.php', 'migrations/m131105_000006_remove_gethelp_widget_for_non_admins.php', 'migrations/m131105_000007_new_relation_column_names.php', 'migrations/m131105_000008_add_values_for_unknown_asset_kinds.php', 'models/MatrixRecordModel.php', 'models/MatrixRecordTypeModel.php', 'models/TagSetModel.php', 'records/EntryLocaleRecord.php', 'records/MatrixRecordRecord.php', 'records/MatrixRecordTypeRecord.php', 'records/StructuredEntryRecord.php', 'records/TagSetRecord.php', 'resources/images/whats-new/entrytypes.png', 'resources/images/whats-new/single.png', 'resources/images/whats-new/structure.png', 'resources/js/compressed/dashboard.js', 'resources/js/compressed/dashboard.min.map', 'resources/js/dashboard.js', 'templates/assets/_nav_folder.html', 'templates/users/_edit/_userphoto.html', 'templates/users/_edit/account.html', 'templates/users/_edit/admin.html', 'templates/users/_edit/layout.html', 'templates/users/_edit/profile.html', 'translations/fr_fr.php');
     $appPath = craft()->path->getAppPath();
     foreach ($filesToDelete as $fileToDelete) {
         if (IOHelper::fileExists($appPath . $fileToDelete)) {
             $fullPath = $appPath . $fileToDelete;
             Craft::log('Deleting file: ' . $fullPath . ' because it is not supposed to exist.', LogLevel::Info, true);
             IOHelper::deleteFile($appPath . $fileToDelete);
         } else {
             Craft::log('File: ' . $fileToDelete . ' does not exist.  Good.', LogLevel::Info, true);
         }
     }
     return true;
 }
예제 #10
0
 /**
  * Get cropped image url.
  *
  * @param null|array $settings
  *
  * @return string
  */
 public function getUrl($settings = null)
 {
     // Get image
     $file = $this->getFile();
     // Do the cropping
     $this->applyCrop($file, $settings);
     // Get base64 of crop
     $base64 = $this->getBase64($file);
     // Get mime
     $mime = IOHelper::getMimeType($file);
     // Delete the temp image
     IOHelper::deleteFile($file);
     // Return base64 string
     return 'data:' . $mime . ';base64,' . $base64;
 }
예제 #11
0
 /**
  * @inheritDoc ITool::performAction()
  *
  * @param array $params
  *
  * @return array
  */
 public function performAction($params = array())
 {
     // In addition to the default tables we want to ignore data in, we also don't care about data in the session
     // table in this tools' case.
     $file = craft()->db->backup(array('sessions'));
     if (IOHelper::fileExists($file) && isset($params['downloadBackup']) && (bool) $params['downloadBackup']) {
         $destZip = craft()->path->getTempPath() . IOHelper::getFileName($file, false) . '.zip';
         if (IOHelper::fileExists($destZip)) {
             IOHelper::deleteFile($destZip, true);
         }
         IOHelper::createFile($destZip);
         if (Zip::add($destZip, $file, craft()->path->getDbBackupPath())) {
             return array('backupFile' => IOHelper::getFileName($destZip, false));
         }
     }
 }
예제 #12
0
 /**
  * @param $source
  * @param $destZip
  *
  * @return bool 'true' if the zip was successfully created, 'false' if not.
  */
 public static function compress($source, $destZip)
 {
     $source = IOHelper::normalizePathSeparators($source);
     $destZip = IOHelper::normalizePathSeparators($destZip);
     if (!IOHelper::folderExists($source) && !IOHelper::fileExists($destZip)) {
         Craft::log('Tried to zip the contents of ' . $source . ' to ' . $destZip . ', but the source path does not exist.', LogLevel::Error);
         return false;
     }
     if (IOHelper::fileExists($destZip)) {
         IOHelper::deleteFile($destZip);
     }
     IOHelper::createFile($destZip);
     craft()->config->maxPowerCaptain();
     $zip = static::_getZipInstance($destZip);
     return $zip->zip(IOHelper::getRealPath($source), IOHelper::getRealPath($destZip));
 }
예제 #13
0
 /**
  * Based on the cache's hashed base, attempts to delete any older versions of same name.
  */
 public function deleteExpiredCache()
 {
     MinimeePlugin::log(Craft::t('Minimee is attempting to delete expired caches.'));
     $files = IOHelper::getFiles($this->settings->cachePath);
     foreach ($files as $file) {
         // skip self
         if ($file === $this->makePathToCacheFilename()) {
             continue;
         }
         if (strpos($file, $this->makePathToHashOfCacheBase()) === 0) {
             MinimeePlugin::log(Craft::t('Minimee is attempting to delete file: ') . $file);
             // suppress errors by passing true as second parameter
             IOHelper::deleteFile($file, true);
         }
     }
 }
 public function actionDownload()
 {
     $segments = craft()->request->segments;
     $file = craft()->assets->getFileById((int) end($segments));
     $user = craft()->userSession->getUser();
     if ($file && $user) {
         $source = $file->getSource();
         $sourceType = $source->getSourceType();
         $download = $sourceType->getLocalCopy($file);
         header('Content-type: ' . $file->getMimeType());
         header('Content-Disposition: attachment; filename="' . $file->filename . '"');
         echo file_get_contents($download);
         IOHelper::deleteFile($download);
     } else {
         $this->redirect("404");
     }
 }
예제 #15
0
 /**
  * Download zip.
  */
 public function actionDownload()
 {
     // Get wanted filename
     $filename = craft()->request->getRequiredParam('filename');
     // Get file id's
     $files = craft()->request->getRequiredParam('files');
     // Generate zipfile
     $zipfile = craft()->zipAssets->download($files, $filename);
     // Get zip filename
     $zipname = IOHelper::getFileName($zipfile);
     // Get zip filecontents
     $zip = IOHelper::getFileContents($zipfile);
     // Delete zipfile
     IOHelper::deleteFile($zipfile);
     // Download it
     craft()->request->sendFile($zipname, $zip, array('forceDownload' => true));
 }
 /**
  * Create a transform for the file by the transform index.
  *
  * @param AssetFileModel           $file
  * @param AssetTransformIndexModel $index
  *
  * @throws Exception if the AssetTransformIndexModel cannot be determined to have a transform
  * @return null
  */
 private function _createTransformForFile(AssetFileModel $file, AssetTransformIndexModel $index)
 {
     if (!ImageHelper::isImageManipulatable(IOHelper::getExtension($file->filename))) {
         return;
     }
     if (empty($index->transform)) {
         $transform = $this->normalizeTransform(mb_substr($index->location, 1));
         if (empty($transform)) {
             throw new Exception(Craft::t("Unable to recognize the transform for this transform index!"));
         }
     } else {
         $transform = $index->transform;
     }
     if (!isset($index->detectedFormat)) {
         $index->detectedFormat = !empty($index->format) ? $index->format : $this->detectAutoTransformFormat($file);
     }
     $sourceType = craft()->assetSources->populateSourceType($file->getSource());
     $imageSource = $file->getTransformSource();
     $quality = $transform->quality ? $transform->quality : craft()->config->get('defaultImageQuality');
     $image = craft()->images->loadImage($imageSource, $transform->width, $transform->height);
     $image->setQuality($quality);
     switch ($transform->mode) {
         case 'fit':
             $image->scaleToFit($transform->width, $transform->height);
             break;
         case 'stretch':
             $image->resize($transform->width, $transform->height);
             break;
         default:
             $image->scaleAndCrop($transform->width, $transform->height, true, $transform->position);
             break;
     }
     $createdTransform = AssetsHelper::getTempFilePath($index->detectedFormat);
     $image->saveAs($createdTransform);
     clearstatcache(true, $createdTransform);
     $sourceType->putImageTransform($file, $index, $createdTransform);
     IOHelper::deleteFile($createdTransform);
     if (craft()->assetSources->populateSourceType($file->getSource())->isRemote()) {
         $this->queueSourceForDeletingIfNecessary($imageSource);
     }
     return;
 }
 /**
  * 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 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'];
 }
예제 #19
0
 /**
  * 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.'));
 }
예제 #20
0
 /**
  * @inheritDoc IFieldType::prepValueFromPost()
  *
  * @param mixed $value
  *
  * @return mixed
  */
 public function prepValueFromPost($value)
 {
     $dataFiles = array();
     // Grab data strings
     if (isset($value['data']) && is_array($value['data'])) {
         foreach ($value['data'] as $index => $dataString) {
             if (preg_match('/^data:(?<type>[a-z0-9]+\\/[a-z0-9]+);base64,(?<data>.+)/i', $dataString, $matches)) {
                 $type = $matches['type'];
                 $data = base64_decode($matches['data']);
                 if (!$data) {
                     continue;
                 }
                 if (!empty($value['filenames'][$index])) {
                     $filename = $value['filenames'][$index];
                 } else {
                     $extension = FileHelper::getExtensionByMimeType($type);
                     $filename = 'Uploaded file.' . $extension;
                 }
                 $dataFiles[] = array('filename' => $filename, 'data' => $data);
             }
         }
     }
     // Remove these so they don't interfere.
     if (isset($value['data']) && isset($value['filenames'])) {
         unset($value['data'], $value['filenames']);
     }
     $uploadedFiles = array();
     // See if we have uploaded file(s).
     $contentPostLocation = $this->getContentPostLocation();
     if ($contentPostLocation) {
         $files = UploadedFile::getInstancesByName($contentPostLocation);
         foreach ($files as $file) {
             $uploadedFiles[] = array('filename' => $file->getName(), 'location' => $file->getTempName());
         }
     }
     // See if we have to validate against fileKinds
     $settings = $this->getSettings();
     $allowedExtensions = false;
     if (isset($settings->restrictFiles) && !empty($settings->restrictFiles) && !empty($settings->allowedKinds)) {
         $allowedExtensions = static::_getAllowedExtensions($settings->allowedKinds);
     }
     if (is_array($allowedExtensions)) {
         foreach ($dataFiles as $file) {
             $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename']));
             if (!in_array($extension, $allowedExtensions)) {
                 $this->_failedFiles[] = $file['filename'];
             }
         }
         foreach ($uploadedFiles as $file) {
             $extension = StringHelper::toLowerCase(IOHelper::getExtension($file['filename']));
             if (!in_array($extension, $allowedExtensions)) {
                 $this->_failedFiles[] = $file['filename'];
             }
         }
     }
     if (!empty($this->_failedFiles)) {
         return true;
     }
     // If we got here either there are no restrictions or all files are valid so let's turn them into Assets
     // Unless there are no files at all.
     if (empty($value) && empty($dataFiles) && empty($uploadedFiles)) {
         return array();
     }
     if (empty($value)) {
         $value = array();
     }
     $fileIds = array();
     if (!empty($dataFiles) || !empty($uploadedFiles)) {
         $targetFolderId = $this->_determineUploadFolderId($settings);
         foreach ($dataFiles as $file) {
             $tempPath = AssetsHelper::getTempFilePath($file['filename']);
             IOHelper::writeToFile($tempPath, $file['data']);
             $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId);
             $fileIds[] = $response->getDataItem('fileId');
             IOHelper::deleteFile($tempPath, true);
         }
         foreach ($uploadedFiles as $file) {
             $tempPath = AssetsHelper::getTempFilePath($file['filename']);
             move_uploaded_file($file['location'], $tempPath);
             $response = craft()->assets->insertFileByLocalPath($tempPath, $file['filename'], $targetFolderId);
             $fileIds[] = $response->getDataItem('fileId');
             IOHelper::deleteFile($tempPath, true);
         }
     }
     $fileIds = array_merge($value, $fileIds);
     // Make it look like the actual POST data contained these file IDs as well,
     // so they make it into entry draft/version data
     $this->element->setRawPostContent($this->model->handle, $fileIds);
     return $fileIds;
 }
예제 #21
0
 /**
  * Move a file between sources.
  *
  * @param BaseAssetSourceType $originatingSource
  * @param BaseAssetSourceType $targetSource
  * @param AssetFileModel      $file
  * @param AssetFolderModel    $folder
  * @param string              $action
  *
  * @return AssetOperationResponseModel
  */
 private function _moveFileBetweenSources(BaseAssetSourceType $originatingSource, BaseAssetSourceType $targetSource, AssetFileModel $file, AssetFolderModel $folder, $action = '')
 {
     $localCopy = $originatingSource->getLocalCopy($file);
     // File model will be updated in the process, but we need the old data in order to finalize the transfer.
     $oldFileModel = clone $file;
     $response = $targetSource->transferFileIntoSource($localCopy, $folder, $file, $action);
     if ($response->isSuccess()) {
         // Use the previous data to clean up
         craft()->assetTransforms->deleteAllTransformData($oldFileModel);
         $originatingSource->finalizeTransfer($oldFileModel);
         IOHelper::deleteFile($localCopy);
     }
     return $response;
 }
 /**
  * Upload a file.
  *
  * @param array $file
  * @param int   $folderId
  *
  * @return bool|int
  */
 private function _uploadFile($file, $folderId)
 {
     $fileName = AssetsHelper::cleanAssetName($file['name']);
     // Save the file to a temp location and pass this on to the source type implementation
     $filePath = AssetsHelper::getTempFilePath(IOHelper::getExtension($fileName));
     move_uploaded_file($file['tmp_name'], $filePath);
     $response = craft()->assets->insertFileByLocalPath($filePath, $fileName, $folderId);
     // Make sure the file is removed.
     IOHelper::deleteFile($filePath, true);
     // Prevent sensitive information leak. Just in case.
     $response->deleteDataItem('filePath');
     // Return file ID
     return $response->getDataItem('fileId');
 }
예제 #23
0
 /**
  * Upload file in chunks.
  *
  * @param string                       $file
  * @param \Google_Http_MediaFileUpload $media
  * @param int                          $chunkSizeBytes
  *
  * @return bool|string
  */
 protected function uploadChunks($file, \Google_Http_MediaFileUpload $media, $chunkSizeBytes)
 {
     // Upload the various chunks. $status will be false until the process is complete.
     $status = false;
     $handle = fopen($file, 'rb');
     while (!$status && !feof($handle)) {
         $chunk = $this->readVideoChunk($handle, $chunkSizeBytes);
         $status = $media->nextChunk($chunk);
     }
     // The final value of $status will be the data from the API for the object
     // that has been uploaded.
     $result = false;
     if ($status != false) {
         $result = $status;
     }
     fclose($handle);
     // Remove the local asset file
     IOHelper::deleteFile($file);
     // Return YouTube ID or false
     return $result;
 }
 /**
  * Delete all the generated images for this file.
  *
  * @param AssetFileModel $file The assetFileModel representing the file to delete any generated thumbnails for.
  *
  * @return null
  */
 protected function deleteGeneratedThumbnails(AssetFileModel $file)
 {
     $thumbFolders = IOHelper::getFolderContents(craft()->path->getAssetsThumbsPath());
     foreach ($thumbFolders as $folder) {
         if (is_dir($folder)) {
             IOHelper::deleteFile($folder . '/' . $file->id . '.' . IOHelper::getExtension($file->filename));
         }
     }
 }
예제 #25
0
 /**
  * Finish importing.
  *
  * @param array  $settings
  * @param string $backup
  */
 public function finish($settings, $backup)
 {
     craft()->import_history->end($settings['history'], ImportModel::StatusFinished);
     if ($settings['email']) {
         // Gather results
         $results = array('success' => $settings['rows'], 'errors' => array());
         // Gather errors
         foreach ($this->log as $line => $result) {
             $results['errors'][$line] = $result;
         }
         // Recalculate successful results
         $results['success'] -= count($results['errors']);
         // Prepare the mail
         $email = new EmailModel();
         $emailSettings = craft()->email->getSettings();
         $email->toEmail = $emailSettings['emailAddress'];
         // Get current user
         $currentUser = craft()->userSession->getUser();
         // Zip the backup
         if ($currentUser->can('backup') && $settings['backup'] && IOHelper::fileExists($backup)) {
             $destZip = craft()->path->getTempPath() . IOHelper::getFileName($backup, false) . '.zip';
             if (IOHelper::fileExists($destZip)) {
                 IOHelper::deleteFile($destZip, true);
             }
             IOHelper::createFile($destZip);
             if (Zip::add($destZip, $backup, craft()->path->getDbBackupPath())) {
                 $backup = $destZip;
             }
         }
         // Set email content
         $email->subject = Craft::t('The import task is finished');
         $email->htmlBody = TemplateHelper::getRaw(craft()->templates->render('import/_email', array('results' => $results, 'backup' => $backup)));
         // Send it
         craft()->email->sendEmail($email);
     }
 }
 /**
  * Delete a file.
  *
  * @param AssetFileModel $file
  * @return AssetOperationResponseModel
  */
 public function deleteFile(AssetFileModel $file)
 {
     // Delete all the created images, such as transforms, thumbnails
     $this->deleteCreatedImages($file);
     craft()->assetTransforms->deleteTransformRecordsByFileId($file->id);
     if (IOHelper::fileExists(craft()->path->getAssetsImageSourcePath() . $file->id . '.' . IOHelper::getExtension($file->filename))) {
         IOHelper::deleteFile(craft()->path->getAssetsImageSourcePath() . $file->id . '.' . IOHelper::getExtension($file->filename));
     }
     // Delete DB record and the file itself.
     craft()->elements->deleteElementById($file->id);
     $this->_deleteSourceFile($file->getFolder(), $file->filename);
     $response = new AssetOperationResponseModel();
     return $response->setSuccess();
 }
예제 #27
0
 /**
  * @return bool
  */
 public function delete()
 {
     if (!IOHelper::deleteFile($this->getRealPath())) {
         return false;
     }
     return true;
 }
 /**
  * Creates a new support ticket for the GetHelp widget.
  */
 public function actionSendSupportRequest()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     craft()->config->maxPowerCaptain();
     $getHelpModel = new GetHelpModel();
     $getHelpModel->fromEmail = craft()->request->getPost('fromEmail');
     $getHelpModel->message = craft()->request->getPost('message');
     $getHelpModel->attachDebugFiles = (bool) craft()->request->getPost('attachDebugFiles');
     if ($getHelpModel->validate()) {
         $user = craft()->userSession->getUser();
         $requestParamDefaults = array('sFirstName' => $user->getFriendlyName(), 'sLastName' => $user->lastName ? $user->lastName : 'Doe', 'sEmail' => $getHelpModel->fromEmail, 'tNote' => $getHelpModel->message);
         $requestParams = $requestParamDefaults;
         $hsParams = array('helpSpotApiURL' => 'https://support.pixelandtonic.com/api/index.php');
         try {
             if ($getHelpModel->attachDebugFiles) {
                 $tempZipFile = craft()->path->getTempPath() . StringHelper::UUID() . '.zip';
                 IOHelper::createFile($tempZipFile);
                 if (IOHelper::folderExists(craft()->path->getLogPath())) {
                     // Grab the latest log file.
                     Zip::add($tempZipFile, craft()->path->getLogPath() . 'craft.log', craft()->path->getStoragePath());
                     // Grab the most recent rolled-over log file, if one exists.
                     if (IOHelper::fileExists(craft()->path->getLogPath() . 'craft.log.1')) {
                         Zip::add($tempZipFile, craft()->path->getLogPath() . 'craft.log.1', craft()->path->getStoragePath());
                     }
                     // Grab the phperrors log file, if it exists.
                     if (IOHelper::fileExists(craft()->path->getLogPath() . 'phperrors.log')) {
                         Zip::add($tempZipFile, craft()->path->getLogPath() . 'phperrors.log', craft()->path->getStoragePath());
                     }
                 }
                 if (IOHelper::folderExists(craft()->path->getDbBackupPath())) {
                     // Make a fresh database backup of the current schema/data.
                     craft()->db->backup();
                     $contents = IOHelper::getFolderContents(craft()->path->getDbBackupPath());
                     rsort($contents);
                     // Only grab the most recent 3 sorted by timestamp.
                     for ($counter = 0; $counter <= 2; $counter++) {
                         if (isset($contents[$counter])) {
                             Zip::add($tempZipFile, $contents[$counter], craft()->path->getStoragePath());
                         }
                     }
                 }
                 $requestParams['File1_sFilename'] = 'SupportAttachment.zip';
                 $requestParams['File1_sFileMimeType'] = 'application/zip';
                 $requestParams['File1_bFileBody'] = base64_encode(IOHelper::getFileContents($tempZipFile));
                 // Bump the default timeout because of the attachment.
                 $hsParams['callTimeout'] = 120;
             }
         } catch (\Exception $e) {
             Craft::log('Tried to attach debug logs to a support request and something went horribly wrong: ' . $e->getMessage(), LogLevel::Warning);
             // There was a problem zipping, so reset the params and just send the email without the attachment.
             $requestParams = $requestParamDefaults;
         }
         require_once craft()->path->getLibPath() . 'HelpSpotAPI.php';
         $hsapi = new \HelpSpotAPI($hsParams);
         $result = $hsapi->requestCreate($requestParams);
         if ($result) {
             if ($getHelpModel->attachDebugFiles) {
                 if (IOHelper::fileExists($tempZipFile)) {
                     IOHelper::deleteFile($tempZipFile);
                 }
             }
             $this->returnJson(array('success' => true));
         } else {
             $hsErrors = array_filter(preg_split("/(\r\n|\n|\r)/", $hsapi->errors));
             $this->returnJson(array('errors' => array('Support' => $hsErrors)));
         }
     } else {
         $this->returnJson(array('errors' => $getHelpModel->getErrors()));
     }
 }
예제 #29
0
 /**
  * @param string $unzipFolder
  *
  * @throws Exception
  * @return array
  */
 private function _validateNewRequirements($unzipFolder)
 {
     $requirementsFolderPath = $unzipFolder . '/app/etc/requirements/';
     $requirementsFile = $requirementsFolderPath . 'Requirements.php';
     $errors = array();
     if (!IOHelper::fileExists($requirementsFile)) {
         throw new Exception(Craft::t('The Requirements file is required and it does not exist at {path}.', array('path' => $requirementsFile)));
     }
     // Make sure we can write to craft/app/requirements
     if (!IOHelper::isWritable(craft()->path->getAppPath() . 'etc/requirements/')) {
         throw new Exception(StringHelper::parseMarkdown(Craft::t('Craft CMS needs to be able to write to your craft/app/etc/requirements folder and cannot. Please check your [permissions]({url}).', array('url' => 'http://craftcms.com/docs/updating#one-click-updating'))));
     }
     $tempFileName = StringHelper::UUID() . '.php';
     // Make a dupe of the requirements file and give it a random file name.
     IOHelper::copyFile($requirementsFile, $requirementsFolderPath . $tempFileName);
     $newTempFilePath = craft()->path->getAppPath() . 'etc/requirements/' . $tempFileName;
     // Copy the random file name requirements to the requirements folder.
     // We don't want to execute any PHP from the storage folder.
     IOHelper::copyFile($requirementsFolderPath . $tempFileName, $newTempFilePath);
     require_once $newTempFilePath;
     $checker = new RequirementsChecker();
     $checker->run();
     if ($checker->getResult() == RequirementResult::Failed) {
         foreach ($checker->getRequirements() as $requirement) {
             if ($requirement->getResult() == InstallStatus::Failed) {
                 Craft::log('Requirement "' . $requirement->getName() . '" failed with the message: ' . $requirement->getNotes(), LogLevel::Error, true);
                 $errors[] = $requirement->getNotes();
             }
         }
     }
     // Cleanup
     IOHelper::deleteFile($newTempFilePath);
     return $errors;
 }
예제 #30
0
 /**
  * @param $user
  *
  * @return null
  */
 private function _processUserPhoto($user)
 {
     // Delete their photo?
     if (craft()->request->getPost('deleteUserPhoto')) {
         craft()->users->deleteUserPhoto($user);
     }
     // Did they upload a new one?
     if ($userPhoto = UploadedFile::getInstanceByName('userPhoto')) {
         craft()->users->deleteUserPhoto($user);
         $image = craft()->images->loadImage($userPhoto->getTempName());
         $imageWidth = $image->getWidth();
         $imageHeight = $image->getHeight();
         $dimension = min($imageWidth, $imageHeight);
         $horizontalMargin = ($imageWidth - $dimension) / 2;
         $verticalMargin = ($imageHeight - $dimension) / 2;
         $image->crop($horizontalMargin, $imageWidth - $horizontalMargin, $verticalMargin, $imageHeight - $verticalMargin);
         craft()->users->saveUserPhoto($userPhoto->getName(), $image, $user);
         IOHelper::deleteFile($userPhoto->getTempName());
     }
 }