/** * @param string $action * @param array $params * @return bool */ public function beforeAction($action, $params) { if ($action == 'create') { // If the 1nd dimension is the 1nd index, then we know it's a plugin. No need to make them specify the path. if (isset($params[0][1])) { $plugin = $params[0][1]; $path = craft()->path->getMigrationsPath($plugin); if (!IOHelper::folderExists($path)) { echo 'The migration folder does not exist at ' . $path . ". Creating...\n"; if (!IOHelper::createFolder($path)) { echo 'Sorry... I tried to create the folder, but could not.'; return 1; } else { echo 'Successfully created.'; } } } } $yiiVersion = Craft::getYiiVersion(); echo "\nCraft Migration Tool (based on Yii v{$yiiVersion})\n\n"; return true; }
/** * Save remote photo * * @param string $photoUrl * @param UserModel $user * * @return bool */ public function saveRemotePhoto($photoUrl, UserModel $user) { $filename = 'photo'; $tempPath = craft()->path->getTempPath() . 'social/userphotos/' . $user->email . '/'; IOHelper::createFolder($tempPath); $tempFilepath = $tempPath . $filename; $client = new \Guzzle\Http\Client(); $response = $client->get($photoUrl)->setResponseBody($tempPath . $filename)->send(); $extension = substr($response->getContentType(), strpos($response->getContentType(), "/") + 1); IOHelper::rename($tempPath . $filename, $tempPath . $filename . '.' . $extension); craft()->users->deleteUserPhoto($user); $image = craft()->images->loadImage($tempPath . $filename . '.' . $extension); $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($filename . '.' . $extension, $image, $user); IOHelper::deleteFile($tempPath . $filename . '.' . $extension); return true; }
/** * @inheritDoc IZip::unzip() * * @param $srcZip * @param $destFolder * * @return bool */ public function unzip($srcZip, $destFolder) { @ini_set('memory_limit', craft()->config->get('phpMaxMemoryLimit')); $zip = new \ZipArchive(); $zipContents = $zip->open($srcZip, \ZipArchive::CHECKCONS); if ($zipContents !== true) { Craft::log('Could not open the zip file: ' . $srcZip, LogLevel::Error); return false; } for ($i = 0; $i < $zip->numFiles; $i++) { if (!($info = $zip->statIndex($i))) { Craft::log('Could not retrieve a file from the zip archive ' . $srcZip, LogLevel::Error); return false; } // normalize directory separators $info = IOHelper::normalizePathSeparators($info['name']); // found a directory if (mb_substr($info, -1) === '/') { IOHelper::createFolder($destFolder . '/' . $info); continue; } // Don't extract the OSX __MACOSX directory if (mb_substr($info, 0, 9) === '__MACOSX/') { continue; } $contents = $zip->getFromIndex($i); if ($contents === false) { Craft::log('Could not extract file from zip archive ' . $srcZip, LogLevel::Error); return false; } if (!IOHelper::writeToFile($destFolder . '/' . $info, $contents, true, true)) { Craft::log('Could not copy file to ' . $destFolder . '/' . $info . ' while unzipping from ' . $srcZip, LogLevel::Error); return false; } } $zip->close(); return true; }
/** * @param $srcZip * @param $destFolder * * @return bool */ public static function unzip($srcZip, $destFolder) { craft()->config->maxPowerCaptain(); if (IOHelper::fileExists($srcZip)) { if (IOHelper::getExtension($srcZip) == 'zip') { if (!IOHelper::folderExists($destFolder)) { if (!IOHelper::createFolder($destFolder)) { Craft::log('Tried to create the unzip destination folder, but could not: ' . $destFolder, LogLevel::Error); return false; } } else { // If the destination folder exists and it has contents, clear them. if (($conents = IOHelper::getFolderContents($destFolder)) !== false) { // Begin the great purge. if (!IOHelper::clearFolder($destFolder)) { Craft::log('Tried to clear the contents of the unzip destination folder, but could not: ' . $destFolder, LogLevel::Error); return false; } } } $zip = static::_getZipInstance($srcZip); $result = $zip->unzip($srcZip, $destFolder); if ($result === true) { return $result; } else { Craft::log('There was an error unzipping the file: ' . $srcZip, LogLevel::Error); return false; } } else { Craft::log($srcZip . ' is not a zip file and cannot be unzipped.', LogLevel::Error); return false; } } else { Craft::log('Unzipping is only available for files.', LogLevel::Error); return false; } }
/** * Attempt to backup each of the update manifest files by copying them to a file with the same name with a .bak * extension. If there is an exception thrown, we attempt to roll back all of the changes. * * @param string $unzipFolder * @param string $handle * * @return bool */ private function _backupFiles($unzipFolder, $handle) { $manifestData = UpdateHelper::getManifestData($unzipFolder, $handle); try { foreach ($manifestData as $row) { if (UpdateHelper::isManifestVersionInfoLine($row)) { continue; } // No need to back up migration files. if (UpdateHelper::isManifestMigrationLine($row)) { continue; } $rowData = explode(';', $row); $filePath = IOHelper::normalizePathSeparators(($handle == 'craft' ? craft()->path->getAppPath() : craft()->path->getPluginsPath() . $handle . '/') . $rowData[0]); // It's a folder if (UpdateHelper::isManifestLineAFolder($filePath)) { $folderPath = UpdateHelper::cleanManifestFolderLine($filePath); if (IOHelper::folderExists($folderPath)) { Craft::log('Backing up folder ' . $folderPath, LogLevel::Info, true); IOHelper::createFolder($folderPath . '.bak'); IOHelper::copyFolder($folderPath . '/', $folderPath . '.bak/'); } } else { // If the file doesn't exist, it's probably a new file. if (IOHelper::fileExists($filePath)) { Craft::log('Backing up file ' . $filePath, LogLevel::Info, true); IOHelper::copyFile($filePath, $filePath . '.bak'); } } } } catch (\Exception $e) { Craft::log('Error updating files: ' . $e->getMessage(), LogLevel::Error); UpdateHelper::rollBackFileChanges($manifestData, $handle); return false; } return true; }
/** * Makes sure a folder exists. If it does not - creates one with write permissions * * @param string $folderPath The path to the folder. * @param bool $suppressErrors Whether to suppress any PHP Notices/Warnings/Errors (usually permissions related). * * @return null */ public static function ensureFolderExists($folderPath, $suppressErrors = false) { if (!IOHelper::folderExists($folderPath, $suppressErrors)) { IOHelper::createFolder($folderPath, craft()->config->get('defaultFolderPermissions'), $suppressErrors); } }
/** * @param $manifestData * @param $sourceTempFolder * @param $handle * * @return bool */ public static function doFileUpdate($manifestData, $sourceTempFolder, $handle) { if ($handle == 'craft') { $destDirectory = craft()->path->getAppPath(); $sourceFileDirectory = 'app/'; } else { $destDirectory = craft()->path->getPluginsPath() . $handle . '/'; $sourceFileDirectory = ''; } try { foreach ($manifestData as $row) { if (static::isManifestVersionInfoLine($row)) { continue; } $folder = false; $rowData = explode(';', $row); if (static::isManifestLineAFolder($rowData[0])) { $folder = true; $tempPath = static::cleanManifestFolderLine($rowData[0]); } else { $tempPath = $rowData[0]; } $destFile = IOHelper::normalizePathSeparators($destDirectory . $tempPath); $sourceFile = IOHelper::getRealPath(IOHelper::normalizePathSeparators($sourceTempFolder . '/' . $sourceFileDirectory . $tempPath)); switch (trim($rowData[1])) { // update the file case PatchManifestFileAction::Add: if ($folder) { Craft::log('Updating folder: ' . $destFile, LogLevel::Info, true); $tempFolder = rtrim($destFile, '/') . StringHelper::UUID() . '/'; $tempTempFolder = rtrim($destFile, '/') . '-tmp/'; IOHelper::createFolder($tempFolder); IOHelper::copyFolder($sourceFile, $tempFolder); IOHelper::rename($destFile, $tempTempFolder); IOHelper::rename($tempFolder, $destFile); IOHelper::clearFolder($tempTempFolder); IOHelper::deleteFolder($tempTempFolder); } else { Craft::log('Updating file: ' . $destFile, LogLevel::Info, true); IOHelper::copyFile($sourceFile, $destFile); } break; } } } catch (\Exception $e) { Craft::log('Error updating files: ' . $e->getMessage(), LogLevel::Error); UpdateHelper::rollBackFileChanges($manifestData, $handle); return false; } return true; }
/** * @param $srcZip * @param $destFolder * @return bool */ public function unzip($srcZip, $destFolder) { $zip = new \PclZip($srcZip); $tempDestFolders = null; // check to see if it's a valid archive. if (($zipFiles = $zip->extract(PCLZIP_OPT_EXTRACT_AS_STRING)) == false) { Craft::log('Tried to unzip ' . $srcZip . ', but PclZip thinks it is not a valid zip archive.', LogLevel::Error); return false; } if (count($zipFiles) == 0) { Craft::log($srcZip . ' appears to be an empty zip archive.', LogLevel::Error); return false; } // find out which directories we need to create in the destination. foreach ($zipFiles as $zipFile) { if (substr($zipFile['filename'], 0, 9) === '__MACOSX/') { continue; } $folderName = IOHelper::getFolderName($zipFile['filename']); if ($folderName == './') { $tempDestFolders[] = $destFolder . '/'; } else { $tempDestFolders[] = $destFolder . '/' . rtrim(IOHelper::getFolderName($zipFile['filename']), '/'); } } $tempDestFolders = array_unique($tempDestFolders); $finalDestFolders = array(); foreach ($tempDestFolders as $tempDestFolder) { // Skip over the working directory if (rtrim($destFolder, '/') == rtrim($tempDestFolder, '/')) { continue; } // Make sure the current directory is within the working directory if (strpos($tempDestFolder, $destFolder) === false) { continue; } $finalDestFolders[] = $tempDestFolder; } asort($finalDestFolders); // Create the destination directories. foreach ($finalDestFolders as $finalDestFolder) { if (!IOHelper::folderExists($finalDestFolder)) { if (!IOHelper::createFolder($finalDestFolder)) { Craft::log('Could not create folder ' . $finalDestFolder . ' while unzipping: ' . $srcZip, LogLevel::Error); return false; } } } unset($finalDestFolders); // Extract the files from the zip foreach ($zipFiles as $zipFile) { // folders have already been created. if ($zipFile['folder']) { continue; } if (substr($zipFile['filename'], 0, 9) === '__MACOSX/') { continue; } $destFile = $destFolder . '/' . $zipFile['filename']; if (!IOHelper::writeToFile($destFile, $zipFile['content'], true, true)) { Craft::log('Could not copy the file ' . $destFile . ' while unziping: ' . $srcZip, LogLevel::Error); return false; } } return true; }
/** * Copies template files to templates folder * * @return null */ private function _copyTemplates() { $instaBlogFolder = trim(realpath(dirname(__FILE__)), 'services') . 'resources/_templates/'; $craftTemplateFolder = realpath(CRAFT_TEMPLATES_PATH); $instaBlogTargetFolder = $craftTemplateFolder . '/blog/'; Craft::log('Creating blog folder in templates directory.', LogLevel::Info, true, '_copyTemplates', 'InstaBlog'); IOHelper::createFolder($instaBlogTargetFolder, 0755, true); Craft::log('Copying InstaBlog templates to templates/blog directory.', LogLevel::Info, true, '_copyTemplates', 'InstaBlog'); if (IOHelper::copyFolder($instaBlogFolder, $instaBlogTargetFolder, true)) { Craft::log($instaBlogFolder . ' copied to ' . $instaBlogTargetFolder . ' successfully.', LogLevel::Info, true, '_copyTemplates', 'InstaBlog'); } else { Craft::log('Failed copying ' . $instaBlogFolder . ' to ' . $instaBlogTargetFolder, LogLevel::Error, true, '_copyTemplates', 'InstaBlog'); } }
/** * Stores a value identified by a key in cache. This is the implementation of the method declared in the parent class. * * @param string $key The key identifying the value to be cached * @param string $value The value to be cached * @param integer $expire The number of seconds in which the cached value will expire. 0 means never expire. * @return boolean true If the value is successfully stored into cache, false otherwise */ protected function setValue($key, $value, $expire) { if (!$this->_gced && mt_rand(0, 1000000) < $this->getGCProbability()) { $this->gc(); $this->_gced = true; } if ($expire <= 0) { $expire = 31536000; // 1 year } $expire += time(); $cacheFile = $this->getCacheFile($key); if ($this->directoryLevel > 0) { IOHelper::createFolder(IOHelper::getFolderName($cacheFile), IOHelper::getWritableFolderPermissions()); } if ($this->_originalKey == 'useWriteFileLock') { if (IOHelper::writeToFile($cacheFile, $value, true, false, true) !== false) { IOHelper::changePermissions($cacheFile, IOHelper::getWritableFilePermissions()); return IOHelper::touch($cacheFile, $expire); } else { return false; } } else { if (IOHelper::writeToFile($cacheFile, $value) !== false) { IOHelper::changePermissions($cacheFile, IOHelper::getWritableFilePermissions()); return IOHelper::touch($cacheFile, $expire); } else { return false; } } }
/** * 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)); }
/** * @inheritDoc BaseAssetSourceType::createSourceFolder() * * @param AssetFolderModel $parentFolder * @param string $folderName * * @return bool */ protected function createSourceFolder(AssetFolderModel $parentFolder, $folderName) { if (!IOHelper::isWritable($this->getSourceFileSystemPath() . $parentFolder->path)) { return false; } return IOHelper::createFolder($this->getSourceFileSystemPath() . $parentFolder->path . $folderName); }
/** * Get paths for an external file (really external, or on an external source type) * * @param $image * @throws Exception */ private function _getPathsForUrl($image) { $urlParts = parse_url($image); $pathParts = pathinfo($urlParts['path']); $hashRemoteUrl = craft()->imager->getSetting('hashRemoteUrl'); if ($hashRemoteUrl) { if (is_string($hashRemoteUrl) && $hashRemoteUrl == 'host') { $parsedDirname = substr(md5($urlParts['host']), 0, 10) . $pathParts['dirname']; } else { $parsedDirname = md5($urlParts['host'] . $pathParts['dirname']); } } else { $parsedDirname = str_replace('.', '_', $urlParts['host']) . $pathParts['dirname']; } $this->sourcePath = craft()->path->getRuntimePath() . 'imager/' . $parsedDirname . '/'; $this->targetPath = craft()->imager->getSetting('imagerSystemPath') . $parsedDirname . '/'; $this->targetUrl = craft()->imager->getSetting('imagerUrl') . $parsedDirname . '/'; $this->sourceFilename = $this->targetFilename = $pathParts['basename']; // check if the temp path for remote files exists or can be created. if (!IOHelper::getRealPath($this->sourcePath)) { IOHelper::createFolder($this->sourcePath, craft()->config->get('defaultFolderPermissions'), true); if (!IOHelper::getRealPath($this->sourcePath)) { throw new Exception(Craft::t('Temp folder “{sourcePath}” does not exist and could not be created', array('sourcePath' => $this->sourcePath))); } } // check if the file is already downloaded if (!IOHelper::fileExists($this->sourcePath . $this->sourceFilename) || IOHelper::getLastTimeModified($this->sourcePath . $this->sourceFilename)->format('U') + craft()->imager->getSetting('cacheDurationRemoteFiles') < time()) { $this->_downloadFile($this->sourcePath . $this->sourceFilename, $image); if (!IOHelper::fileExists($this->sourcePath . $this->sourceFilename)) { throw new Exception(Craft::t('File could not be downloaded and saved to “{sourcePath}”', array('sourcePath' => $this->sourcePath))); } } }
public function actionSendSupportRequest() { $this->requirePostRequest(); craft()->config->maxPowerCaptain(); $success = false; $errors = array(); $zipFile = null; $tempFolder = null; $getHelpModel = new FeedMe_GetHelpModel(); $getHelpModel->fromEmail = craft()->request->getPost('fromEmail'); $getHelpModel->feedIssue = craft()->request->getPost('feedIssue'); $getHelpModel->message = trim(craft()->request->getPost('message')); $getHelpModel->attachLogs = (bool) craft()->request->getPost('attachLogs'); $getHelpModel->attachSettings = (bool) craft()->request->getPost('attachSettings'); $getHelpModel->attachFeed = (bool) craft()->request->getPost('attachFeed'); $getHelpModel->attachFields = (bool) craft()->request->getPost('attachFields'); $getHelpModel->attachment = UploadedFile::getInstanceByName('attachAdditionalFile'); if ($getHelpModel->validate()) { $plugin = craft()->plugins->getPlugin('feedMe'); $feed = craft()->feedMe_feeds->getFeedById($getHelpModel->feedIssue); // Add some extra info about this install $message = $getHelpModel->message . "\n\n" . "------------------------------\n\n" . 'Craft ' . craft()->getEditionName() . ' ' . craft()->getVersion() . '.' . craft()->getBuild() . "\n\n" . 'Feed Me ' . $plugin->getVersion(); try { $zipFile = $this->_createZip(); $tempFolder = craft()->path->getTempPath() . StringHelper::UUID() . '/'; if (!IOHelper::folderExists($tempFolder)) { IOHelper::createFolder($tempFolder); } // // Attached just the Feed Me log // if ($getHelpModel->attachLogs) { if (IOHelper::folderExists(craft()->path->getLogPath())) { $logFolderContents = IOHelper::getFolderContents(craft()->path->getLogPath()); foreach ($logFolderContents as $file) { // Just grab the Feed Me log if (IOHelper::fileExists($file) && basename($file) == 'feedme.log') { Zip::add($zipFile, $file, craft()->path->getStoragePath()); } } } } // // Backup our feed settings // if ($getHelpModel->attachSettings) { if (IOHelper::folderExists(craft()->path->getDbBackupPath())) { $backup = craft()->path->getDbBackupPath() . StringHelper::toLowerCase('feedme_' . gmdate('ymd_His') . '.sql'); $feedInfo = $this->_prepareSqlFeedSettings($getHelpModel->feedIssue); IOHelper::writeToFile($backup, $feedInfo . PHP_EOL, true, true); Zip::add($zipFile, $backup, craft()->path->getStoragePath()); } } // // Save the contents of the feed // if ($getHelpModel->attachFeed) { $feedData = craft()->feedMe_feed->getRawData($feed->feedUrl); $tempFile = $tempFolder . 'feed.' . StringHelper::toLowerCase($feed->feedType); IOHelper::writeToFile($tempFile, $feedData . PHP_EOL, true, true); if (IOHelper::fileExists($tempFile)) { Zip::add($zipFile, $tempFile, $tempFolder); } } // // Get some information about the fields we're mapping to - handy to know // if ($getHelpModel->attachFields) { $fieldInfo = array(); foreach ($feed->fieldMapping as $feedHandle => $fieldHandle) { $field = craft()->fields->getFieldByHandle($fieldHandle); if ($field) { $fieldInfo[] = $this->_prepareExportField($field); } } // Support PHP <5.4, JSON_PRETTY_PRINT = 128, JSON_NUMERIC_CHECK = 32 $json = json_encode($fieldInfo, 128 | 32); $tempFile = $tempFolder . 'fields.json'; IOHelper::writeToFile($tempFile, $json . PHP_EOL, true, true); if (IOHelper::fileExists($tempFile)) { Zip::add($zipFile, $tempFile, $tempFolder); } } // // Add in any additional attachments // if ($getHelpModel->attachment) { $tempFile = $tempFolder . $getHelpModel->attachment->getName(); $getHelpModel->attachment->saveAs($tempFile); // Make sure it actually saved. if (IOHelper::fileExists($tempFile)) { Zip::add($zipFile, $tempFile, $tempFolder); } } } catch (\Exception $e) { FeedMePlugin::log('Tried to attach debug logs to a support request and something went horribly wrong: ' . $e->getMessage(), LogLevel::Warning, true); } $email = new EmailModel(); $email->fromEmail = $getHelpModel->fromEmail; $email->toEmail = "*****@*****.**"; $email->subject = "Feed Me Support"; $email->body = $message; if ($zipFile) { $email->addAttachment($zipFile, 'FeedMeSupportAttachment.zip', 'base64', 'application/zip'); } $result = craft()->email->sendEmail($email); if ($result) { if ($zipFile) { if (IOHelper::fileExists($zipFile)) { IOHelper::deleteFile($zipFile); } } if ($tempFolder) { IOHelper::clearFolder($tempFolder); IOHelper::deleteFolder($tempFolder); } $success = true; } else { $errors = array('Support' => array('Unable to contact support. Please try again soon.')); } } else { $errors = $getHelpModel->getErrors(); } $this->returnJson(array('success' => $success, 'errors' => $errors)); }
/** * Create a physical folder, return TRUE on success. * * @param AssetFolderModel $parentFolder * @param $folderName * @return boolean */ protected function _createSourceFolder(AssetFolderModel $parentFolder, $folderName) { if (!IOHelper::isWritable($this->_getSourceFileSystemPath() . $parentFolder->fullPath)) { return false; } return IOHelper::createFolder($this->_getSourceFileSystemPath() . $parentFolder->fullPath . $folderName, IOHelper::getWritableFolderPermissions()); }
/** * Makes sure a folder exists. If it does not - creates one with write permissions * * @param $folderPath * @return void */ public static function ensureFolderExists($folderPath) { if (!IOHelper::folderExists($folderPath)) { IOHelper::createFolder($folderPath, self::getWritableFolderPermissions()); } }