/** * Returns a database backup zip file to the browser. * * @return null */ public function actionDownloadBackupFile() { $fileName = craft()->request->getRequiredQuery('fileName'); if (($filePath = IOHelper::fileExists(craft()->path->getTempPath() . $fileName . '.zip')) == true) { craft()->request->sendFile(IOHelper::getFileName($filePath), IOHelper::getFileContents($filePath), array('forceDownload' => true)); } }
/** * 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(); } }
/** * Finds installable records from the models folder. * * @return array */ public function findInstallableRecords() { $records = array(); $recordsFolder = craft()->path->getAppPath() . 'records/'; $recordFiles = IOHelper::getFolderContents($recordsFolder, false, ".*Record\\.php\$"); foreach ($recordFiles as $file) { if (IOHelper::fileExists($file)) { $fileName = IOHelper::getFileName($file, false); $class = __NAMESPACE__ . '\\' . $fileName; // Ignore abstract classes and interfaces $ref = new \ReflectionClass($class); if ($ref->isAbstract() || $ref->isInterface()) { Craft::log("Skipping record {$file} because it’s abstract or an interface.", LogLevel::Warning); continue; } $obj = new $class('install'); if (method_exists($obj, 'createTable')) { $records[] = $obj; } else { Craft::log("Skipping record {$file} because it doesn’t have a createTable() method.", LogLevel::Warning); } } else { Craft::log("Skipping record {$file} because it doesn’t exist.", LogLevel::Warning); } } return $records; }
/** * 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; }
/** * 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); // Download it craft()->request->sendFile(IOHelper::getFileName($zipfile), IOHelper::getFileContents($zipfile), array('forceDownload' => true)); }
/** * @param bool $includeExtension * * @return mixed */ public function getFileName($includeExtension = true) { if ($includeExtension) { if (!$this->_fileName) { $this->_fileName = IOHelper::getFileName($this->getRealPath(), $includeExtension); } return $this->_fileName; } else { if (!$this->_baseName) { $this->_baseName = IOHelper::getFileName($this->getRealPath(), $includeExtension); } return $this->_baseName; } }
/** * 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)); } } }
/** * Returns the field's settings HTML. * * @return string|null */ public function getSettingsHtml() { $configOptions = array('' => Craft::t('Default')); $configPath = craft()->path->getConfigPath() . 'redactor/'; if (IOHelper::folderExists($configPath)) { $configFiles = IOHelper::getFolderContents($configPath, false, '\\.json$'); if (is_array($configFiles)) { foreach ($configFiles as $file) { $configOptions[IOHelper::getFileName($file)] = IOHelper::getFileName($file, false); } } } return craft()->templates->render('_components/fieldtypes/RichText/settings', array('settings' => $this->getSettings(), 'configOptions' => $configOptions)); }
/** * @param string|null $path * @param bool $fetch * * @return array */ public static function getAlerts($path = null, $fetch = false) { $alerts = array(); $user = craft()->userSession->getUser(); if (!$user) { return $alerts; } if (craft()->updates->isUpdateInfoCached() || $fetch) { // Fetch the updates regardless of whether we're on the Updates page or not, because the other alerts are // relying on cached Elliott info $updateModel = craft()->updates->getUpdates(); // Get the license key status $licenseKeyStatus = craft()->et->getLicenseKeyStatus(); // Invalid license? if ($licenseKeyStatus == LicenseKeyStatus::Invalid) { $alerts[] = Craft::t('Your license key is invalid.'); } else { if (craft()->hasWrongEdition()) { $alerts[] = Craft::t('You’re running Craft {edition} with a Craft {licensedEdition} license.', array('edition' => craft()->getEditionName(), 'licensedEdition' => craft()->getLicensedEditionName())) . ' <a class="go edition-resolution">' . Craft::t('Resolve') . '</a>'; } } if ($path != 'updates' && $user->can('performUpdates')) { if (!empty($updateModel->app->releases)) { if (craft()->updates->criticalCraftUpdateAvailable($updateModel->app->releases)) { $alerts[] = Craft::t('There’s a critical Craft update available.') . ' <a class="go nowrap" href="' . UrlHelper::getUrl('updates') . '">' . Craft::t('Go to Updates') . '</a>'; } } } // Domain mismatch? if ($licenseKeyStatus == LicenseKeyStatus::Mismatched) { $licensedDomain = craft()->et->getLicensedDomain(); $licenseKeyPath = craft()->path->getLicenseKeyPath(); $licenseKeyFile = IOHelper::getFolderName($licenseKeyPath, false) . '/' . IOHelper::getFileName($licenseKeyPath); $message = Craft::t('The license located at {file} belongs to {domain}.', array('file' => $licenseKeyFile, 'domain' => '<a href="http://' . $licensedDomain . '" target="_blank">' . $licensedDomain . '</a>')); // Can they actually do something about it? if ($user->admin) { $action = '<a class="go domain-mismatch">' . Craft::t('Transfer it to this domain') . '</a>'; } else { $action = Craft::t('Please notify one of your site’s admins.'); } $alerts[] = $message . ' ' . $action; } } $allPluginAlerts = craft()->plugins->call('getCpAlerts', array($path, $fetch), true); foreach ($allPluginAlerts as $pluginAlerts) { $alerts = array_merge($alerts, $pluginAlerts); } return $alerts; }
/** * @inheritDoc ISavableComponentType::getSettingsHtml() * * @return string|null */ public function getSettingsHtml() { $configOptions = array('' => Craft::t('Default')); $configPath = craft()->path->getConfigPath() . 'redactor/'; if (IOHelper::folderExists($configPath)) { $configFiles = IOHelper::getFolderContents($configPath, false, '\\.json$'); if (is_array($configFiles)) { foreach ($configFiles as $file) { $configOptions[IOHelper::getFileName($file)] = IOHelper::getFileName($file, false); } } } $columns = array('text' => Craft::t('Text (stores about 64K)'), 'mediumtext' => Craft::t('MediumText (stores about 4GB)')); return craft()->templates->render('_components/fieldtypes/RichText/settings', array('settings' => $this->getSettings(), 'configOptions' => $configOptions, 'columns' => $columns, 'existing' => !empty($this->model->id))); }
/** * @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)); } } }
/** * Returns an array of locales that Craft is translated into. The list of locales is based on whatever files exist * in craft/app/translations/. * * @return array An array of {@link LocaleModel} objects. */ public function getAppLocales() { if (!$this->_appLocales) { $this->_appLocales = array(new LocaleModel('en_us')); $path = craft()->path->getCpTranslationsPath(); $folders = IOHelper::getFolderContents($path, false, ".*\\.php"); if (is_array($folders) && count($folders) > 0) { foreach ($folders as $dir) { $localeId = IOHelper::getFileName($dir, false); if ($localeId != 'en_us') { $this->_appLocales[] = new LocaleModel($localeId); } } } } return $this->_appLocales; }
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; }
/** * 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; }
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]); } }
public function actionDownload() { // Get wanted filename $source_id = craft()->request->getRequiredPost('assetsSource'); if ($source_id == 'all') { $source_name = 'All Sources'; $source_ids = craft()->downloadAssets->getSourceIds(); } else { $source = craft()->assetSources->getSourceById($source_id); $source_name = $source->name; $source_ids = array($source_id); } // Get assets $criteria = craft()->elements->getCriteria(ElementType::Asset); $criteria->sourceId = $source_ids; $criteria->limit = null; $assets = $criteria->find(); // Get filename $filename = 'craftAssetDownload_' . $this->slugify($source_name); // Create zip $zip = new \ZipArchive(); $zipfile = craft()->path->getTempPath() . $filename . '_' . time() . '.zip'; // Open zip if ($zip->open($zipfile, $zip::CREATE) === true) { // Loop through assets foreach ($assets as $asset) { // Get asset path $source = craft()->assetSources->getSourceById($asset->sourceId); // Add asset to zip $zip->addFile($source->settings['path'] . $asset->filename, $asset->filename); } // Close zip $zip->close(); // Download zip craft()->request->sendFile(IOHelper::getFileName($zipfile), IOHelper::getFileContents($zipfile), array('forceDownload' => true)); } // If not redirected, something went wrong throw new Exception(Craft::t('Failed to generate the zipfile')); }
/** * @param string $name command name (case-insensitive) * @return \CConsoleCommand the command object. Null if the name is invalid. */ public function createCommand($name) { $name = strtolower($name); $command = null; if (isset($this->commands[$name])) { $command = $this->commands[$name]; } else { $commands = array_change_key_case($this->commands); if (isset($commands[$name])) { $command = $commands[$name]; } } if ($command !== null) { if (is_string($command)) { if (strpos($command, '/') !== false || strpos($command, '\\') !== false) { $className = IOHelper::getFileName($command, false); // If it's a default framework command, don't namespace it. if (strpos($command, 'framework') === false) { $className = __NAMESPACE__ . '\\' . $className; } if (!class_exists($className, false)) { require_once $command; } } else { $className = Craft::import($command); } return new $className($name, $this); } else { return Craft::createComponent($command, $name, $this); } } else { if ($name === 'help') { return new \CHelpCommand('help', $this); } else { return null; } } }
/** * @inheritDoc ISavableComponentType::getSettingsHtml() * * @return string|null */ public function getSettingsHtml() { $configOptions = array('' => Craft::t('Default')); $configPath = craft()->path->getConfigPath() . 'redactor/'; if (IOHelper::folderExists($configPath)) { $configFiles = IOHelper::getFolderContents($configPath, false, '\\.json$'); if (is_array($configFiles)) { foreach ($configFiles as $file) { $configOptions[IOHelper::getFileName($file)] = IOHelper::getFileName($file, false); } } } $columns = array('text' => Craft::t('Text (stores about 64K)'), 'mediumtext' => Craft::t('MediumText (stores about 4GB)')); $sourceOptions = array(); foreach (craft()->assetSources->getPublicSources() as $source) { $sourceOptions[] = array('label' => $source->name, 'value' => $source->id); } $transformOptions = array(); foreach (craft()->assetTransforms->getAllTransforms() as $transform) { $transformOptions[] = array('label' => $transform->name, 'value' => $transform->id); } return craft()->templates->render('redactori/settings', array('settings' => $this->getSettings(), 'configOptions' => $configOptions, 'assetSourceOptions' => $sourceOptions, 'transformOptions' => $transformOptions, 'columns' => $columns, 'existing' => !empty($this->model->id))); }
/** * @param string|null $path * @param bool $fetch * * @return array */ public static function getAlerts($path = null, $fetch = false) { $alerts = array(); $user = craft()->userSession->getUser(); if (!$user) { return $alerts; } if (craft()->updates->isUpdateInfoCached() || $fetch) { // Fetch the updates regardless of whether we're on the Updates page or not, because the other alerts are // relying on cached Elliott info $updateModel = craft()->updates->getUpdates(); if ($path != 'updates' && $user->can('performUpdates')) { if (!empty($updateModel->app->releases)) { if (craft()->updates->criticalCraftUpdateAvailable($updateModel->app->releases)) { $alerts[] = Craft::t('There’s a critical Craft update available.') . ' <a class="go nowrap" href="' . UrlHelper::getUrl('updates') . '">' . Craft::t('Go to Updates') . '</a>'; } } } // Domain mismatch? $licenseKeyStatus = craft()->et->getLicenseKeyStatus(); if ($licenseKeyStatus == LicenseKeyStatus::MismatchedDomain) { $licensedDomain = craft()->et->getLicensedDomain(); $licenseKeyPath = craft()->path->getLicenseKeyPath(); $licenseKeyFile = IOHelper::getFolderName($licenseKeyPath, false) . '/' . IOHelper::getFileName($licenseKeyPath); $message = Craft::t('The license located at {file} belongs to {domain}.', array('file' => $licenseKeyFile, 'domain' => '<a href="http://' . $licensedDomain . '" target="_blank">' . $licensedDomain . '</a>')); // Can they actually do something about it? if ($user->admin) { $action = '<a class="domain-mismatch">' . Craft::t('Transfer it to this domain?') . '</a>'; } else { $action = Craft::t('Please notify one of your site’s admins.'); } $alerts[] = $message . ' ' . $action; } } return $alerts; }
/** * Returns the actual plugin class handle based on a case-insensitive handle. * * @param string $iHandle * * @return bool|string */ private function _getPluginHandleFromFileSystem($iHandle) { $pluginsPath = craft()->path->getPluginsPath(); $fullPath = $pluginsPath . mb_strtolower($iHandle) . '/' . $iHandle . 'Plugin.php'; if (($file = IOHelper::fileExists($fullPath, true)) !== false) { $file = IOHelper::getFileName($file, false); return mb_substr($file, 0, mb_strlen($file) - mb_strlen('Plugin')); } return false; }
/** * @throws Exception * @return string */ public function backupDatabase() { Craft::log('Starting to backup database.', LogLevel::Info, true); if (($dbBackupPath = craft()->db->backup()) === false) { throw new Exception(Craft::t('There was a problem backing up your database.')); } else { return IOHelper::getFileName($dbBackupPath, 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) { // We hate Javascript and PHP in our image files. if (IOHelper::getFileKind(IOHelper::getExtension($localFilePath)) == 'image' && ImageHelper::isImageManipulatable(IOHelper::getExtension($localFilePath))) { 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) = 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); } return $response; }
/** * @throws EtException|\Exception * @return EtModel|null */ public function phoneHome() { try { $missingLicenseKey = empty($this->_model->licenseKey); // No craft/config/license.key file and we can't write to the config folder. Don't even make the call home. if ($missingLicenseKey && !$this->_isConfigFolderWritable()) { throw new EtException('Craft needs to be able to write to your “craft/config” folder and it can’t.', 10001); } if (!craft()->cache->get('etConnectFailure')) { $data = JsonHelper::encode($this->_model->getAttributes(null, true)); $client = new \Guzzle\Http\Client(); $client->setUserAgent($this->_userAgent, true); $options = array('timeout' => $this->getTimeout(), 'connect_timeout' => $this->getConnectTimeout(), 'allow_redirects' => $this->getAllowRedirects()); $request = $client->post($this->_endpoint, $options); $request->setBody($data, 'application/json'); $response = $request->send(); if ($response->isSuccessful()) { // Clear the connection failure cached item if it exists. if (craft()->cache->get('etConnectFailure')) { craft()->cache->delete('etConnectFailure'); } if ($this->_destinationFileName) { $body = $response->getBody(); // Make sure we're at the beginning of the stream. $body->rewind(); // Write it out to the file IOHelper::writeToFile($this->_destinationFileName, $body->getStream(), true); // Close the stream. $body->close(); return IOHelper::getFileName($this->_destinationFileName); } $etModel = craft()->et->decodeEtModel($response->getBody()); if ($etModel) { if ($missingLicenseKey && !empty($etModel->licenseKey)) { $this->_setLicenseKey($etModel->licenseKey); } // Cache the license key status and which edition it has craft()->cache->set('licenseKeyStatus', $etModel->licenseKeyStatus); craft()->cache->set('licensedEdition', $etModel->licensedEdition); craft()->cache->set('editionTestableDomain@' . craft()->request->getHostName(), $etModel->editionTestableDomain ? 1 : 0); if ($etModel->licenseKeyStatus == LicenseKeyStatus::MismatchedDomain) { craft()->cache->set('licensedDomain', $etModel->licensedDomain); } return $etModel; } else { Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->getBody(), LogLevel::Warning); if (craft()->cache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->cache->delete('etConnectFailure'); } } } else { Craft::log('Error in calling ' . $this->_endpoint . ' Response: ' . $response->getBody(), LogLevel::Warning); if (craft()->cache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->cache->delete('etConnectFailure'); } } } } catch (EtException $e) { Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error); if (craft()->cache->get('etConnectFailure')) { // There was an error, but at least we connected. craft()->cache->delete('etConnectFailure'); } throw $e; } catch (\Exception $e) { Craft::log('Error in ' . __METHOD__ . '. Message: ' . $e->getMessage(), LogLevel::Error); // Cache the failure for 5 minutes so we don't try again. craft()->cache->set('etConnectFailure', true, 300); } return null; }
/** * 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); } }
/** * Generate a transform by a created index. * * @param AssetTransformIndexModel $index * * @return null */ public function generateTransform(AssetTransformIndexModel $index) { // For _widthxheight_mode if (preg_match('/_(?P<width>[0-9]+|AUTO)x(?P<height>[0-9]+|AUTO)_(?P<mode>[a-z]+)_(?P<position>[a-z\\-]+)(_(?P<quality>[0-9]+))?/i', $index->location, $matches)) { $transform = new AssetTransformModel(); $transform->width = $matches['width'] != 'AUTO' ? $matches['width'] : null; $transform->height = $matches['height'] != 'AUTO' ? $matches['height'] : null; $transform->mode = $matches['mode']; $transform->position = $matches['position']; $transform->quality = isset($matches['quality']) ? $matches['quality'] : null; } else { // Load the dimensions for named transforms and merge with file-specific information. $transform = $this->normalizeTransform(mb_substr($index->location, 1)); } $index->transform = $transform; $file = craft()->assets->getFileById($index->fileId); $source = craft()->assetSources->populateSourceType($file->getSource()); $index->detectedFormat = !empty($index->format) ? $index->format : $this->detectAutoTransformFormat($file); $transformFilename = IOHelper::getFileName($file->filename, false) . '.' . $index->detectedFormat; $index->filename = $transformFilename; $matchFound = false; // If the detected format matches the file's format, we can use the old-style formats as well so we can dig // through existing files. Otherwise, delete all transforms, records of it and create new. if ($file->getExtension() == $index->detectedFormat) { $possibleLocations = array($this->_getUnnamedTransformFolderName($transform)); if ($transform->isNamedTransform()) { $possibleLocations[] = $this->_getNamedTransformFolderName($transform); } // We're looking for transforms that fit the bill and are not the one we are trying to find/create // the image for. $results = craft()->db->createCommand()->select('*')->from('assettransformindex')->where('fileId = :fileId', array(':fileId' => $file->id))->andWhere(array('in', 'location', $possibleLocations))->andWhere('id <> :indexId', array(':indexId' => $index->id))->andWhere('fileExists = 1')->queryAll(); foreach ($results as $result) { // If this is a named transform and indexed before dimensions last changed, this is a stale transform // and needs to go. if ($transform->isNamedTransform() && $result['dateIndexed'] < $transform->dimensionChangeTime) { $source->deleteTransform($file, new AssetTransformIndexModel($result)); $this->deleteTransformIndex($result['id']); } else { $matchFound = $result; } } } // If we have a match, copy the file. if ($matchFound) { $source->copyTransform($file, $file->getFolder(), new AssetTransformIndexModel($matchFound), $index); } else { $this->_createTransformForFile($file, $index); } return $source->fileExists($file->getFolder()->path . $this->getTransformSubfolder($file, $index), $this->getTransformFilename($file, $index)); }
/** * 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; } }
/** * Sends a file to the user. * * We’re overriding this from {@link \CHttpRequest::sendFile()} so we can have more control over the headers. * * @param string $path The path to the file on the server. * @param string $content The contents of the file. * @param array|null $options An array of optional options. Possible keys include 'forceDownload', 'mimeType', * and 'cache'. * @param bool|null $terminate Whether the request should be terminated after the file has been sent. * Defaults to `true`. * * @throws HttpException * @return null */ public function sendFile($path, $content, $options = array(), $terminate = true) { $fileName = IOHelper::getFileName($path, true); // Clear the output buffer to prevent corrupt downloads. Need to check the OB status first, or else some PHP // versions will throw an E_NOTICE since we have a custom error handler // (http://pear.php.net/bugs/bug.php?id=9670) if (ob_get_length() !== false) { // If zlib.output_compression is enabled, then ob_clean() will corrupt the results of output buffering. // ob_end_clean is what we want. ob_end_clean(); } // Default to disposition to 'download' $forceDownload = !isset($options['forceDownload']) || $options['forceDownload']; if ($forceDownload) { HeaderHelper::setDownload($fileName); } if (empty($options['mimeType'])) { if (($options['mimeType'] = \CFileHelper::getMimeTypeByExtension($fileName)) === null) { $options['mimeType'] = 'text/plain'; } } HeaderHelper::setHeader(array('Content-Type' => $options['mimeType'] . '; charset=utf-8')); $fileSize = mb_strlen($content, '8bit'); $contentStart = 0; $contentEnd = $fileSize - 1; $httpVersion = $this->getHttpVersion(); if (isset($_SERVER['HTTP_RANGE'])) { HeaderHelper::setHeader(array('Accept-Ranges' => 'bytes')); // Client sent us a multibyte range, can not hold this one for now if (mb_strpos($_SERVER['HTTP_RANGE'], ',') !== false) { HeaderHelper::setHeader(array('Content-Range' => 'bytes ' . $contentStart - $contentEnd / $fileSize)); throw new HttpException(416, 'Requested Range Not Satisfiable'); } $range = str_replace('bytes=', '', $_SERVER['HTTP_RANGE']); // range requests starts from "-", so it means that data must be dumped the end point. if ($range[0] === '-') { $contentStart = $fileSize - mb_substr($range, 1); } else { $range = explode('-', $range); $contentStart = $range[0]; // check if the last-byte-pos presents in header if (isset($range[1]) && is_numeric($range[1])) { $contentEnd = $range[1]; } } // Check the range and make sure it's treated according to the specs. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // End bytes can not be larger than $end. $contentEnd = $contentEnd > $fileSize ? $fileSize - 1 : $contentEnd; // Validate the requested range and return an error if it's not correct. $wrongContentStart = $contentStart > $contentEnd || $contentStart > $fileSize - 1 || $contentStart < 0; if ($wrongContentStart) { HeaderHelper::setHeader(array('Content-Range' => 'bytes ' . $contentStart - $contentEnd / $fileSize)); throw new HttpException(416, 'Requested Range Not Satisfiable'); } HeaderHelper::setHeader("HTTP/{$httpVersion} 206 Partial Content"); HeaderHelper::setHeader(array('Content-Range' => 'bytes ' . $contentStart - $contentEnd / $fileSize)); } else { HeaderHelper::setHeader("HTTP/{$httpVersion} 200 OK"); } // Calculate new content length $length = $contentEnd - $contentStart + 1; if (!empty($options['cache'])) { $cacheTime = 31536000; // 1 year HeaderHelper::setHeader(array('Expires' => gmdate('D, d M Y H:i:s', time() + $cacheTime) . ' GMT')); HeaderHelper::setHeader(array('Pragma' => 'cache')); HeaderHelper::setHeader(array('Cache-Control' => 'max-age=' . $cacheTime)); $modifiedTime = IOHelper::getLastTimeModified($path); HeaderHelper::setHeader(array('Last-Modified' => gmdate("D, d M Y H:i:s", $modifiedTime->getTimestamp()) . ' GMT')); } else { if (!$forceDownload) { HeaderHelper::setNoCache(); } else { // Fixes a bug in IE 6, 7 and 8 when trying to force download a file over SSL: // https://stackoverflow.com/questions/1218925/php-script-to-download-file-not-working-in-ie HeaderHelper::setHeader(array('Pragma' => '', 'Cache-Control' => '')); } } if ($options['mimeType'] == 'application/x-javascript' || $options['mimeType'] == 'text/css') { HeaderHelper::setHeader(array('Vary' => 'Accept-Encoding')); } if (!ob_get_length()) { HeaderHelper::setLength($length); } $content = mb_substr($content, $contentStart, $length); if ($terminate) { // Clean up the application first because the file downloading could take long time which may cause timeout // of some resources (such as DB connection) ob_start(); Craft::app()->end(0, false); ob_end_clean(); echo $content; exit(0); } else { echo $content; } }
/** * 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']; }
/** * Populates the migrations table with the base migration plus any existing ones from app/migrations. * * @throws Exception * @return null */ private function _populateMigrationTable() { $migrations = array(); // Add the base one. $migration = new MigrationRecord(); $migration->version = craft()->migrations->getBaseMigration(); $migration->applyTime = DateTimeHelper::currentUTCDateTime(); $migrations[] = $migration; $migrationsFolder = craft()->path->getAppPath() . 'migrations/'; $migrationFiles = IOHelper::getFolderContents($migrationsFolder, false, "(m(\\d{6}_\\d{6})_.*?)\\.php"); if ($migrationFiles) { foreach ($migrationFiles as $file) { if (IOHelper::fileExists($file)) { $migration = new MigrationRecord(); $migration->version = IOHelper::getFileName($file, false); $migration->applyTime = DateTimeHelper::currentUTCDateTime(); $migrations[] = $migration; } } foreach ($migrations as $migration) { if (!$migration->save()) { Craft::log('Could not populate the migration table.', LogLevel::Error); throw new Exception(Craft::t('There was a problem saving to the migrations table: ') . $this->_getFlattenedErrors($migration->getErrors())); } } } Craft::log('Migration table populated successfully.'); }