/** * Upload a logo for the admin panel. */ public function actionUploadLogo() { $this->requireAjaxRequest(); $this->requireAdmin(); // Upload the file and drop it in the temporary folder $uploader = new \qqFileUploader(); try { // Make sure a file was uploaded if ($uploader->file && $uploader->file->getSize()) { $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); $fileName = IOHelper::cleanFilename($uploader->file->getName()); $uploader->file->save($folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->setMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } craft()->images->cleanImage($folderPath . $fileName); $constraint = 500; list($width, $height) = getimagesize($folderPath . $fileName); // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
/** * Get template file by its name * * @param string $templateName Template file name * @return array Returns template file information */ public function getTemplateByName($templateName) { $template = []; $path = craft()->path->getPluginsPath() . 'formbuilder2/templates/email/templates/' . $templateName; $file = IOHelper::getFile($path); $template = ['fileName' => $file->getFileName(false), 'fileOriginalName' => $file->getFileName(), 'fileNameCleaned' => IOHelper::cleanFilename(IOHelper::getFileName($file->getRealPath(), false)), 'fileExtension' => $file->getExtension(), 'filePath' => $file->getRealPath(), 'fileContents' => $file->getContents()]; return $template; }
/** * Clean an Asset's filename. * * @param $fileName * * @return mixed */ public static function cleanAssetName($fileName) { $separator = craft()->config->get('filenameWordSeparator'); if (!is_string($separator)) { $separator = null; } return IOHelper::cleanFilename($fileName, false, $separator); }
/** * Dump all tables * * @return string */ public function run() { $this->_currentVersion = 'v' . Craft::getVersion() . '.' . Craft::getBuild(); $result = $this->_processHeader(); foreach (craft()->db->getSchema()->getTables() as $tableName => $val) { $result .= $this->_processTable($tableName); } $result .= $this->_processConstraints(); $result .= $this->_processFooter(); $fileName = IOHelper::cleanFilename(Craft::getSiteName()) . '_' . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql'; $filePath = craft()->path->getDbBackupPath() . strtolower($fileName); IOHelper::writeToFile($filePath, $result); return $filePath; }
/** * Backup All Forms */ public function backupAllForms() { $forms = FormBuilder2_FormRecord::model()->ordered()->findAll(); $table = 'craft_formbuilder2_forms'; if ($forms) { $this->_currentVersion = 'v' . craft()->getVersion() . '.' . craft()->getBuild(); $siteName = IOHelper::cleanFilename(StringHelper::asciiString(craft()->getSiteName())); $fileName = ($siteName ? $siteName . '_' : '') . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql'; $this->_filePath = craft()->path->getDbBackupPath() . StringHelper::toLowerCase($fileName); $this->_processHeader(); $results = $this->_processResult($table); $this->_processConstraints(); $this->_processFooter(); $filepath = $this->_filePath; $this->_processFile($fileName, $filepath); } else { return false; } }
public function getTemplateFiles() { $folderEmpty = true; if (IOHelper::isFolderEmpty(craft()->path->getPluginsPath() . 'formbuilder2/templates/email/layouts')) { throw new HttpException(404, Craft::t('Looks like you don\'t have any templates in your email/layouts folder.')); } else { $folderEmpty = false; } $fileList = IOHelper::getFolderContents(craft()->path->getPluginsPath() . 'formbuilder2/templates/email/layouts'); $files = []; $filesModel = []; if (!$folderEmpty) { foreach ($fileList as $key => $file) { $files[$key] = ['fileName' => IOHelper::getFileName($file, false), 'fileOriginalName' => IOHelper::getFileName($file), 'fileNameCleaned' => IOHelper::cleanFilename(IOHelper::getFileName($file, false)), 'fileExtension' => IOHelper::getExtension($file), 'filePath' => $file, 'fileContents' => IOHelper::getFileContents($file)]; $filesModel[] = FormBuilder2_FileModel::populateModel($files[$key]); } } return $filesModel; }
/** * Triggers the database backup including all DML and DDL and writes it out to a file. * * @return string The path to the database backup file. */ public function run() { // Normalize the ignored table names if there is a table prefix set. if (($tablePrefix = craft()->config->get('tablePrefix', ConfigFile::Db)) !== '') { foreach ($this->_ignoreDataTables as $key => $tableName) { $this->_ignoreDataTables[$key] = $tablePrefix . '_' . $tableName; } } $this->_currentVersion = 'v' . craft()->getVersion() . '.' . craft()->getBuild(); $fileName = IOHelper::cleanFilename(craft()->getSiteName()) . '_' . gmdate('ymd_His') . '_' . $this->_currentVersion . '.sql'; $this->_filePath = craft()->path->getDbBackupPath() . StringHelper::toLowerCase($fileName); $this->_processHeader(); foreach (craft()->db->getSchema()->getTables() as $resultName => $val) { $this->_processResult($resultName); } $this->_processConstraints(); $this->_processFooter(); return $this->_filePath; }
public function actionSetTemplate() { $this->requirePostRequest(); $this->requireAjaxRequest(); $templatePath = craft()->request->getRequiredPost('templatePath'); $folderContents = IOHelper::getFolderContents(craft()->path->getPluginsPath() . 'formbuilder2/templates/layouts/templates/'); $theFile = ''; if ($folderContents && $templatePath) { foreach ($folderContents as $key => $file) { $fileName = IOHelper::getFileName($file, false); if ($fileName == $templatePath) { $theFile = IOHelper::getFile($file); } } } if ($theFile == '') { $this->returnErrorJson('No template with that name.'); } else { $template = ['fileName' => $theFile->getFileName(false), 'fileOriginalName' => $theFile->getFileName(), 'fileNameCleaned' => IOHelper::cleanFilename(IOHelper::getFileName($theFile->getRealPath(), false)), 'fileExtension' => $theFile->getExtension(), 'filePath' => $theFile->getRealPath(), 'fileContents' => $theFile->getContents()]; $this->returnJson(['success' => true, 'message' => Craft::t('Template is set.'), 'layout' => $template]); } }
/** * Clean an Asset's filename. * * @param $name * @param bool $isFilename if set to true (default), will separate extension * and clean the filename separately. * * @return mixed */ public static function cleanAssetName($name, $isFilename = true) { if ($isFilename) { $baseName = IOHelper::getFileName($name, false); $extension = '.' . IOHelper::getExtension($name); } else { $baseName = $name; $extension = ''; } $separator = craft()->config->get('filenameWordSeparator'); if (!is_string($separator)) { $separator = null; } $baseName = IOHelper::cleanFilename($baseName, craft()->config->get('convertFilenamesToAscii'), $separator); if ($isFilename && empty($baseName)) { $baseName = '-'; } return $baseName . $extension; }
/** * 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; }
/** * Resolves a resource path to the actual file system path, or returns false if the resource cannot be found. * * @param string $path * @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 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; } $username = IOHelper::cleanFilename($segs[1]); $size = IOHelper::cleanFilename($segs[2]); $filename = IOHelper::cleanFilename($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); craft()->images->loadImage($originalPhotoPath)->resize($size)->saveAs($sizedPhotoPath); } return $sizedPhotoPath; } case 'tempuploads': array_shift($segs); return craft()->path->getTempUploadsPath() . implode('/', $segs); case 'assetthumbs': if (empty($segs[1]) || empty($segs[2]) || !is_numeric($segs[1]) || !is_numeric($segs[2])) { return false; } $fileModel = craft()->assets->getFileById($segs[1]); if (empty($fileModel)) { return false; } $sourceType = craft()->assetSources->getSourceTypeById($fileModel->sourceId); $size = $segs[2]; $thumbFolder = craft()->path->getAssetsThumbsPath() . $size . '/'; IOHelper::ensureFolderExists($thumbFolder); $thumbPath = $thumbFolder . $fileModel->id . '.' . pathinfo($fileModel->filename, PATHINFO_EXTENSION); if (!IOHelper::fileExists($thumbPath)) { $sourcePath = $sourceType->getImageSourcePath($fileModel); if (!IOHelper::fileExists($sourcePath)) { return false; } craft()->images->loadImage($sourcePath)->scaleAndCrop($size, $size)->saveAs($thumbPath); } return $thumbPath; case 'icons': if (empty($segs[1]) || empty($segs[2]) || !is_numeric($segs[2]) || !preg_match('/^(?P<extension>[a-z_0-9]+)/i', $segs[1])) { return false; } $ext = strtolower($segs[1]); $size = $segs[2]; $iconPath = $this->_getIconPath($ext, $size); return $iconPath; case 'logo': return craft()->path->getStoragePath() . implode('/', $segs); } } // 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 $pluginPaths = craft()->plugins->call('getResourcePath', array($path)); foreach ($pluginPaths as $path) { if ($path && IOHelper::fileExists($path)) { return $path; } } // Couldn't find the file return false; }
/** * Create a subfolder. * * @param AssetFolderModel $parentFolder * @param $folderName * @return AssetOperationResponseModel * @throws Exception */ public function createFolder(AssetFolderModel $parentFolder, $folderName) { $folderName = IOHelper::cleanFilename($folderName); // If folder exists in DB or physically, bail out if (craft()->assets->findFolder(array('parentId' => $parentFolder->id, 'name' => $folderName)) || $this->_sourceFolderExists($parentFolder, $folderName)) { throw new Exception(Craft::t('A folder already exists with that name!')); } if (!$this->_createSourceFolder($parentFolder, $folderName)) { throw new Exception(Craft::t('There was an error while creating the folder.')); } $newFolder = new AssetFolderModel(); $newFolder->sourceId = $parentFolder->sourceId; $newFolder->parentId = $parentFolder->id; $newFolder->name = $folderName; $newFolder->fullPath = $parentFolder->fullPath . $folderName . '/'; $folderId = craft()->assets->storeFolder($newFolder); $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('folderId', $folderId)->setDataItem('parentId', $parentFolder->id)->setDataItem('folderName', $folderName); }
/** * Creates a new support ticket for the GetHelp widget. * * @return null */ public function actionSendSupportRequest() { $this->requirePostRequest(); craft()->config->maxPowerCaptain(); $success = false; $errors = array(); $zipFile = null; $tempFolder = null; $widgetId = craft()->request->getPost('widgetId'); $namespace = craft()->request->getPost('namespace'); $namespace = $namespace ? $namespace . '.' : ''; $getHelpModel = new GetHelpModel(); $getHelpModel->fromEmail = craft()->request->getPost($namespace . 'fromEmail'); $getHelpModel->message = trim(craft()->request->getPost($namespace . 'message')); $getHelpModel->attachLogs = (bool) craft()->request->getPost($namespace . 'attachLogs'); $getHelpModel->attachDbBackup = (bool) craft()->request->getPost($namespace . 'attachDbBackup'); $getHelpModel->attachTemplates = (bool) craft()->request->getPost($namespace . 'attachTemplates'); $getHelpModel->attachment = UploadedFile::getInstanceByName($namespace . 'attachAdditionalFile'); if ($getHelpModel->validate()) { $user = craft()->userSession->getUser(); // Add some extra info about this install $message = $getHelpModel->message . "\n\n" . "------------------------------\n\n" . 'Craft ' . craft()->getEditionName() . ' ' . craft()->getVersion() . '.' . craft()->getBuild(); $plugins = craft()->plugins->getPlugins(); if ($plugins) { $pluginNames = array(); foreach ($plugins as $plugin) { $pluginNames[] = $plugin->getName() . ' ' . $plugin->getVersion() . ' (' . $plugin->getDeveloper() . ')'; } $message .= "\nPlugins: " . implode(', ', $pluginNames); } $requestParamDefaults = array('sFirstName' => $user->getFriendlyName(), 'sLastName' => $user->lastName ? $user->lastName : 'Doe', 'sEmail' => $getHelpModel->fromEmail, 'tNote' => $message); $requestParams = $requestParamDefaults; $hsParams = array('helpSpotApiURL' => 'https://support.pixelandtonic.com/api/index.php'); try { if ($getHelpModel->attachLogs || $getHelpModel->attachDbBackup) { if (!$zipFile) { $zipFile = $this->_createZip(); } if ($getHelpModel->attachLogs && IOHelper::folderExists(craft()->path->getLogPath())) { // Grab it all. $logFolderContents = IOHelper::getFolderContents(craft()->path->getLogPath()); foreach ($logFolderContents as $file) { // Make sure it's a file. if (IOHelper::fileExists($file)) { Zip::add($zipFile, $file, craft()->path->getStoragePath()); } } } if ($getHelpModel->attachDbBackup && IOHelper::folderExists(craft()->path->getDbBackupPath())) { // Make a fresh database backup of the current schema/data. We want all data from all tables // for debugging. craft()->db->backup(); $backups = IOHelper::getLastModifiedFiles(craft()->path->getDbBackupPath(), 3); foreach ($backups as $backup) { if (IOHelper::getExtension($backup) == 'sql') { Zip::add($zipFile, $backup, craft()->path->getStoragePath()); } } } } if ($getHelpModel->attachment) { // If we don't have a zip file yet, create one now. if (!$zipFile) { $zipFile = $this->_createZip(); } $tempFolder = craft()->path->getTempPath() . StringHelper::UUID() . '/'; if (!IOHelper::folderExists($tempFolder)) { IOHelper::createFolder($tempFolder); } $tempFile = $tempFolder . $getHelpModel->attachment->getName(); $getHelpModel->attachment->saveAs($tempFile); // Make sure it actually saved. if (IOHelper::fileExists($tempFile)) { Zip::add($zipFile, $tempFile, $tempFolder); } } if ($getHelpModel->attachTemplates) { // If we don't have a zip file yet, create one now. if (!$zipFile) { $zipFile = $this->_createZip(); } if (IOHelper::folderExists(craft()->path->getLogPath())) { // Grab it all. $templateFolderContents = IOHelper::getFolderContents(craft()->path->getSiteTemplatesPath()); foreach ($templateFolderContents as $file) { // Make sure it's a file. if (IOHelper::fileExists($file)) { $templateFolderName = IOHelper::getFolderName(craft()->path->getSiteTemplatesPath(), false); $siteTemplatePath = craft()->path->getSiteTemplatesPath(); $tempPath = substr($siteTemplatePath, 0, strlen($siteTemplatePath) - strlen($templateFolderName) - 1); Zip::add($zipFile, $file, $tempPath); } } } } if ($zipFile) { $requestParams['File1_sFilename'] = 'SupportAttachment-' . IOHelper::cleanFilename(craft()->getSiteName()) . '.zip'; $requestParams['File1_sFileMimeType'] = 'application/zip'; $requestParams['File1_bFileBody'] = base64_encode(IOHelper::getFileContents($zipFile)); // Bump the default timeout because of the attachment. $hsParams['callTimeout'] = 120; } // Grab the license.key file. if (IOHelper::fileExists(craft()->path->getLicenseKeyPath())) { $requestParams['File2_sFilename'] = 'license.key'; $requestParams['File2_sFileMimeType'] = 'text/plain'; $requestParams['File2_bFileBody'] = base64_encode(IOHelper::getFileContents(craft()->path->getLicenseKeyPath())); } } 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 ($zipFile) { if (IOHelper::fileExists($zipFile)) { IOHelper::deleteFile($zipFile); } } if ($tempFolder) { IOHelper::clearFolder($tempFolder); IOHelper::deleteFolder($tempFolder); } $success = true; } else { $hsErrors = array_filter(preg_split("/(\r\n|\n|\r)/", $hsapi->errors)); $errors = array('Support' => $hsErrors); } } else { $errors = $getHelpModel->getErrors(); } $this->renderTemplate('_components/widgets/GetHelp/response', array('success' => $success, 'errors' => JsonHelper::encode($errors), 'widgetId' => $widgetId)); }
/** * Clean an Asset's filename. * * @param $name * @param bool $isFilename if set to true (default), will separate extension * and clean the filename separately. * @param bool $preventPluginHooks if set to true, will prevent plugins from modifying * the asset name. * * @return mixed */ public static function cleanAssetName($name, $isFilename = true, $preventPluginModifications = false) { if ($isFilename) { $baseName = IOHelper::getFileName($name, false); $extension = '.' . IOHelper::getExtension($name); } else { $baseName = $name; $extension = ''; } $separator = craft()->config->get('filenameWordSeparator'); if (!is_string($separator)) { $separator = null; } if (!$preventPluginModifications) { $pluginModifiedAssetName = craft()->plugins->callFirst('modifyAssetFilename', array($baseName), true); // Use the plugin-modified name, if anyone was up to the task. $baseName = $pluginModifiedAssetName ?: $baseName; } $baseName = IOHelper::cleanFilename($baseName, craft()->config->get('convertFilenamesToAscii'), $separator); if ($isFilename && empty($baseName)) { $baseName = '-'; } return $baseName . $extension; }
/** * Insert a file from path in folder. * * @param AssetFolderModel $folder * @param $filePath * @param $fileName * @return AssetOperationResponseModel * @throws Exception */ protected function _insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { $targetFolder = $this->_getSourceFileSystemPath() . $folder->fullPath; // Make sure the folder exists. if (!IOHelper::folderExists($targetFolder)) { throw new Exception(Craft::t('The “File System Path” specified for this asset source does not appear to exist.')); } // Make sure the folder is writable if (!IOHelper::isWritable($targetFolder)) { throw new Exception(Craft::t('Craft is not able to write to the “File System Path” specified for this asset source.')); } $fileName = IOHelper::cleanFilename($fileName); $targetPath = $targetFolder . $fileName; $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } if (IOHelper::fileExists($targetPath)) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->_getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } if (!IOHelper::copyFile($filePath, $targetPath)) { throw new Exception(Craft::t('Could not copy file to target destination')); } IOHelper::changePermissions($targetPath, IOHelper::getWritableFilePermissions()); $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $targetPath); }
/** * Insert a file from path in folder. * * @param AssetFolderModel $folder * @param $filePath * @param $fileName * @return AssetFileModel * @throws Exception */ protected function _insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { $fileName = IOHelper::cleanFilename($fileName); $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } $uriPath = $this->_getPathPrefix() . $folder->fullPath . $fileName; $this->_prepareForRequests(); $settings = $this->getSettings(); $fileInfo = $this->_s3->getObjectInfo($settings->bucket, $uriPath); if ($fileInfo) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->_getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } clearstatcache(); $this->_prepareForRequests(); if (!$this->_s3->putObject(array('file' => $filePath), $this->getSettings()->bucket, $uriPath, \S3::ACL_PUBLIC_READ)) { throw new Exception(Craft::t('Could not copy file to target destination')); } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $uriPath); }
/** * Resolve a source path to it's folder ID by the source path and the matched source beginning. * * @param int $sourceId * @param string $subpath * * @throws Exception * @return mixed */ private function _resolveSourcePathToFolderId($sourceId, $subpath) { $folder = craft()->assets->findFolder(array('sourceId' => $sourceId, 'parentId' => ':empty:')); // Do we have the folder? if (empty($folder)) { throw new Exception(Craft::t('Cannot find the target folder.')); } // Prepare the path by parsing tokens and normalizing slashes. $subpath = trim($subpath, '/'); $subpath = craft()->templates->renderObjectTemplate($subpath, $this->element); $pathParts = explode('/', $subpath); foreach ($pathParts as &$part) { $part = IOHelper::cleanFilename($part); } $subpath = join('/', $pathParts); if (strlen($subpath)) { $subpath = $subpath . '/'; } // Let's see if the folder already exists. if (empty($subpath)) { $existingFolder = $folder; } else { $folderCriteria = array('sourceId' => $sourceId, 'path' => $folder->path . $subpath); $existingFolder = craft()->assets->findFolder($folderCriteria); } // No dice, go over each folder in the path and create it if it's missing. if (!$existingFolder) { $parts = explode('/', $subpath); // Now make sure that every folder in the path exists. $currentFolder = $folder; foreach ($parts as $part) { if (empty($part)) { continue; } $folderCriteria = array('parentId' => $currentFolder->id, 'name' => $part); $existingFolder = craft()->assets->findFolder($folderCriteria); if (!$existingFolder) { $folderId = $this->_createSubFolder($currentFolder, $part); $existingFolder = craft()->assets->getFolderById($folderId); } $currentFolder = $existingFolder; } } else { $currentFolder = $existingFolder; } return $currentFolder->id; }
/** * Export a submission to the export's zip file. * * @param AmForms_ExportModel $export * @param AmForms_SubmissionModel $submission */ private function _exportSubmissionToZip(AmForms_ExportModel $export, AmForms_SubmissionModel $submission) { // Get submission content $content = craft()->amForms_submissions->getSubmissionEmailBody($submission); // Create submission file $fileName = IOHelper::cleanFilename($submission->title); $fileExtension = '.html'; $folder = $this->_getExportPath(); $file = $folder . $fileName . $fileExtension; $counter = 1; while (!IOHelper::createFile($file)) { $file = $folder . $fileName . $counter . $fileExtension; $counter++; } // Add content to file file_put_contents($file, $content); // Add file to zip Zip::add($export->file, $file, $folder); // Find possible assets foreach ($this->_exportFields[$export->id] as $fieldHandle => $field) { if (is_array($field)) { $field = (object) $field; // Fix standard fields } if ($field->type == 'Assets') { foreach ($submission->{$fieldHandle}->find() as $asset) { $assetPath = craft()->amForms->getPathForAsset($asset); if (IOHelper::fileExists($assetPath . $asset->filename)) { Zip::add($export->file, $assetPath . $asset->filename, $assetPath); } } } } // Remove submission file now that's in the zip IOHelper::deleteFile($file); }
/** * Move or rename files. * * @param $fileIds * @param $folderId * @param string $filename if this is a rename operation * @param array $actions actions to take in case of a conflict. */ public function moveFiles($fileIds, $folderId, $filename = '', $actions = array()) { if (!is_array($fileIds)) { $fileIds = array($fileIds); } if (!is_array($actions)) { $actions = array($actions); } $results = array(); $response = new AssetOperationResponseModel(); foreach ($fileIds as $i => $fileId) { $file = $this->getFileById($fileId); // If this is not a rename operation, then the filename remains the original if (empty($filename)) { $filename = $file->filename; } $filename = IOHelper::cleanFilename($filename); if ($folderId == $file->folderId && $filename == $file->filename) { $response = new AssetOperationResponseModel(); $response->setSuccess(); $results[] = $response; } $originalSourceType = craft()->assetSources->getSourceTypeById($file->sourceId); $folder = $this->getFolderById($folderId); $newSourceType = craft()->assetSources->getSourceTypeById($folder->sourceId); if ($originalSourceType && $newSourceType) { if (!($response = $newSourceType->moveFileInsideSource($originalSourceType, $file, $folder, $filename, $actions[$i]))) { $response = $this->_moveFileBetweenSources($originalSourceType, $newSourceType, $file, $folder, $actions[$i]); } } else { $response->setError(Craft::t("There was an error moving the file {file}.", array('file' => $file->filename))); } } return $response; }
/** * Insert a file from path in folder. * * @param AssetFolderModel $folder * @param $filePath * @param $fileName * @return AssetFileModel * @throws Exception */ protected function _insertFileInFolder(AssetFolderModel $folder, $filePath, $fileName) { $fileName = IOHelper::cleanFilename($fileName); $extension = IOHelper::getExtension($fileName); if (!IOHelper::isExtensionAllowed($extension)) { throw new Exception(Craft::t('This file type is not allowed')); } $uriPath = $this->_getPathPrefix() . $folder->fullPath . $fileName; $fileInfo = $this->_getObjectInfo($uriPath); if ($fileInfo) { $response = new AssetOperationResponseModel(); return $response->setPrompt($this->_getUserPromptOptions($fileName))->setDataItem('fileName', $fileName); } clearstatcache(); // Upload file try { $this->_uploadFile($uriPath, $filePath); } catch (\Exception $exception) { throw new Exception(Craft::t('Could not copy file to target destination')); } $response = new AssetOperationResponseModel(); return $response->setSuccess()->setDataItem('filePath', $uriPath); }