/** * Download zipfile. * * @param array $files * @param string $filename * * @return string */ public function download($files, $filename) { // Get assets $criteria = craft()->elements->getCriteria(ElementType::Asset); $criteria->id = $files; $criteria->limit = null; $assets = $criteria->find(); // Set destination zip $destZip = craft()->path->getTempPath() . $filename . '_' . time() . '.zip'; // Create the zipfile IOHelper::createFile($destZip); // Loop through assets foreach ($assets as $asset) { // Get asset source $source = $asset->getSource(); // Get asset source type $sourceType = $source->getSourceType(); // Get asset file $file = $sourceType->getLocalCopy($asset); // Add to zip Zip::add($destZip, $file, dirname($file)); } // Return zip destination return $destZip; }
/** * 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)); } } }
/** * @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)); } } }
/** * 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); } }
/** * Creates a new support ticket for the GetHelp widget. */ public function actionSendSupportRequest() { $this->requirePostRequest(); $this->requireAjaxRequest(); craft()->config->maxPowerCaptain(); $getHelpModel = new GetHelpModel(); $getHelpModel->fromEmail = craft()->request->getPost('fromEmail'); $getHelpModel->message = craft()->request->getPost('message'); $getHelpModel->attachDebugFiles = (bool) craft()->request->getPost('attachDebugFiles'); if ($getHelpModel->validate()) { $user = craft()->userSession->getUser(); $requestParamDefaults = array('sFirstName' => $user->getFriendlyName(), 'sLastName' => $user->lastName ? $user->lastName : 'Doe', 'sEmail' => $getHelpModel->fromEmail, 'tNote' => $getHelpModel->message); $requestParams = $requestParamDefaults; $hsParams = array('helpSpotApiURL' => 'https://support.pixelandtonic.com/api/index.php'); try { if ($getHelpModel->attachDebugFiles) { $tempZipFile = craft()->path->getTempPath() . StringHelper::UUID() . '.zip'; IOHelper::createFile($tempZipFile); if (IOHelper::folderExists(craft()->path->getLogPath())) { // Grab the latest log file. Zip::add($tempZipFile, craft()->path->getLogPath() . 'craft.log', craft()->path->getStoragePath()); // Grab the most recent rolled-over log file, if one exists. if (IOHelper::fileExists(craft()->path->getLogPath() . 'craft.log.1')) { Zip::add($tempZipFile, craft()->path->getLogPath() . 'craft.log.1', craft()->path->getStoragePath()); } // Grab the phperrors log file, if it exists. if (IOHelper::fileExists(craft()->path->getLogPath() . 'phperrors.log')) { Zip::add($tempZipFile, craft()->path->getLogPath() . 'phperrors.log', craft()->path->getStoragePath()); } } if (IOHelper::folderExists(craft()->path->getDbBackupPath())) { // Make a fresh database backup of the current schema/data. craft()->db->backup(); $contents = IOHelper::getFolderContents(craft()->path->getDbBackupPath()); rsort($contents); // Only grab the most recent 3 sorted by timestamp. for ($counter = 0; $counter <= 2; $counter++) { if (isset($contents[$counter])) { Zip::add($tempZipFile, $contents[$counter], craft()->path->getStoragePath()); } } } $requestParams['File1_sFilename'] = 'SupportAttachment.zip'; $requestParams['File1_sFileMimeType'] = 'application/zip'; $requestParams['File1_bFileBody'] = base64_encode(IOHelper::getFileContents($tempZipFile)); // Bump the default timeout because of the attachment. $hsParams['callTimeout'] = 120; } } catch (\Exception $e) { Craft::log('Tried to attach debug logs to a support request and something went horribly wrong: ' . $e->getMessage(), LogLevel::Warning); // There was a problem zipping, so reset the params and just send the email without the attachment. $requestParams = $requestParamDefaults; } require_once craft()->path->getLibPath() . 'HelpSpotAPI.php'; $hsapi = new \HelpSpotAPI($hsParams); $result = $hsapi->requestCreate($requestParams); if ($result) { if ($getHelpModel->attachDebugFiles) { if (IOHelper::fileExists($tempZipFile)) { IOHelper::deleteFile($tempZipFile); } } $this->returnJson(array('success' => true)); } else { $hsErrors = array_filter(preg_split("/(\r\n|\n|\r)/", $hsapi->errors)); $this->returnJson(array('errors' => array('Support' => $hsErrors))); } } else { $this->returnJson(array('errors' => $getHelpModel->getErrors())); } }
/** * 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)); }
/** * Выгрузка файла конфигурации */ public function download_action($themes = array()) { $archive_name = 'config.zip'; $path = TEMP . DS . $archive_name; $zip = new Zip(array('file' => $path, 'create' => TRUE)); $zip->info(array('type' => 'config')); $zip->add(ROOT . DS . 'config' . EXT); $zip->close(); File::download($path, $archive_name, TRUE); }
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)); }
/** * */ public function index_action($action = 'import') { $this->hookAdminMenu(1); $this->hookAdminMenu(3); switch ($action) { case 'import': $form = new Form('Lang/forms/import'); if ($result = $form->result()) { if ($file = $result->file) { $zip = new Zip(array('file' => $file->path, 'check' => array('type' => 'lang'))); if ($zip->extract(LANG)) { $info = $zip->info(); $langs = $this->getLangs(array($info['lang'])); success(t('<b>Архив успешно распакован!</b> Индекс для языка <b>«%s»</b> установлен.', implode($langs)), '', 'content'); } $zip->close(); unlink($file->path); } } $form->show(); break; case 'export': template('Lang/templates/download')->show(); break; case 'download': $file = ROOT . $this->prepareFilePath(); $archive = TEMP . DS . pathinfo($file, PATHINFO_FILENAME) . '.zip'; $zip = new Zip(array('file' => $archive, 'create' => TRUE)); $zip->add($file); $zip->info(array('type' => 'lang', 'lang' => config('lang.lang'))); $zip->close(); File::download($archive, basename($archive), TRUE); break; } }
/** * @codeCoverageIgnore * * @param array $settings * @param string $backup * @param UserModel $currentUser * * @return string Backup filename */ protected function saveBackup($settings, $backup, $currentUser) { 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; } } return $backup; }
/** * 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); }
/** * Выгрузка шестерёнок */ public function download_action($gears = array()) { if ($gears = $this->input->get('gears', $gears)) { !is_array($gears) && ($gears = explode(',', $gears)); // Если шестерёнка одна — называем архив её именем // Если шестерёнок несколько — называем архив gears $archive_name = (1 === sizeof($gears) ? end($gears) : 'gears') . '.zip'; $path = TEMP . DS . $archive_name; $zip = new Zip(array('file' => $path, 'create' => TRUE)); foreach ($gears as $gear) { $dir = GEARS . DS . $gear; // Если директория существует и шестерёнка не относится к ядру if (is_dir($dir) && !cogear()->site->gears->findByValue($gear)) { $zip->add($dir); } } $zip->info(array('type' => 'gears', 'gears' => $gears)); $zip->close(); File::download($path, $archive_name, TRUE); } }
/** * Выгрузка тем */ public function download_action($themes = array()) { if ($themes = $this->input->get('themes', $themes)) { !is_array($themes) && ($themes = explode(',', $themes)); // Если тема одна — называем архив её именем // Если тем несколько — называем архив gears $archive_name = (1 === sizeof($themes) ? end($themes) : 'themes') . '.zip'; $path = TEMP . DS . $archive_name; $zip = new Zip(array('file' => $path, 'create' => TRUE)); foreach ($themes as $theme) { $dir = THEMES . DS . $theme; // Если директория существует и шестерёнка не относится к ядру $zip->add($dir); } $zip->info(array('type' => 'themes', 'themes' => $themes)); $zip->close(); File::download($path, $archive_name, TRUE); } }