/** * Initialize search index to static property * @return Zend_Search_Lucene_Interface */ public static function initIndex() { if (self::$_index instanceof Zend_Search_Lucene_Interface) { return self::$_index; } $searchIndexPath = Zend_Controller_Action_HelperBroker::getStaticHelper('website')->getPath() . 'cache/' . Widgets_Search_Search::INDEX_FOLDER; if (!is_dir($searchIndexPath)) { if (!Tools_Filesystem_Tools::mkDir($searchIndexPath)) { Tools_System_Tools::debugMode() && error_log('Can\'t create search index folder in ' . $searchIndexPath); } } try { self::$_index = Zend_Search_Lucene::open($searchIndexPath); } catch (Exception $e) { self::$_index = Zend_Search_Lucene::create($searchIndexPath); } return self::$_index; }
private function _uploadTemplatepreview() { $miscConfig = Zend_Registry::get('misc'); $currentTheme = $this->_helper->config->getConfig('currentTheme'); $savePath = $this->_websiteConfig['path'] . $this->_themeConfig['path'] . $currentTheme . DIRECTORY_SEPARATOR . $this->_themeConfig['templatePreview']; $name = trim($this->getRequest()->getParam('templateName')); $fileMime = $this->_getMimeType(); switch ($fileMime) { case 'image/png': $newName = $name . '.png'; break; case 'image/jpg': case 'image/jpeg': $newName = $name . '.jpg'; break; case 'image/gif': $newName = $name . '.gif'; break; default: return false; break; } if (!$name || empty($name)) { return false; } $newImageFile = $savePath . $newName; //checking for existing images with same name ... if (!is_dir($savePath)) { if (!Tools_Filesystem_Tools::mkDir($savePath)) { return false; } } $existingImages = glob($savePath . $name . '.{png,jpeg,jpg,gif}', GLOB_BRACE); // ...and removing them foreach ($existingImages as $img) { Tools_Filesystem_Tools::deleteFile($img); } $this->_uploadHandler->addFilter('Rename', array('target' => $newImageFile, 'overwrite' => true)); $result = $this->_uploadImages($savePath, false); if ($result['error'] == false) { Tools_Image_Tools::resize($newImageFile, $miscConfig['templatePreviewWidth'], true); $result['thumb'] = 'data:' . $fileMime . ';base64,' . base64_encode(Tools_Filesystem_Tools::getFile($newImageFile)); } return $result; }
/** * Batch resize for image upload proccess * @param string original file * @param string desination of resized files * @return boolean|array true-on success, array when errors occur */ public static function batchResize($imageFile, $destination) { $imageFile = trim($imageFile); $destination = trim($destination); if (empty($imageFile) || empty($destination)) { return false; } $dbConfig = Zend_Registry::get('extConfig'); $iniConfig = Zend_Registry::get('misc'); $sizeConfig = array('small' => intval($dbConfig['imgSmall']), 'medium' => intval($dbConfig['imgMedium']), 'large' => intval($dbConfig['imgLarge']), 'product' => intval($iniConfig['imgProduct'])); $errors = array(); foreach ($sizeConfig as $type => $size) { if (!is_dir($destination . DIRECTORY_SEPARATOR . $type)) { Tools_Filesystem_Tools::mkDir($destination . DIRECTORY_SEPARATOR . $type); } $result = self::resize($imageFile, $size, true, $destination . DIRECTORY_SEPARATOR . $type); if ($result !== true) { array_push($errors, $result); } } return empty($result) ? true : $result; }
/** * Method exports zipped theme * @param string $themeName Theme name * @param bool $full Set true to dump data and media files */ protected function _exportTheme($themeName = '', $full = false, $noZip = false) { if (!$themeName) { $themeName = $this->_configHelper->getConfig('currentTheme'); } $themePath = $this->_websiteHelper->getPath() . $this->_themesConfig['path'] . $themeName . DIRECTORY_SEPARATOR; $websitePath = $this->_websiteHelper->getPath(); if ($full) { /** * @var $dbAdapter Zend_Db_Adapter_Abstract */ $dbAdapter = Zend_Registry::get('dbAdapter'); // exporting themes data for the full theme // init empty array for export data $data = array('page' => array()); // and for media files $mediaFiles = array(); // fetching index page and main menu pages $pagesSqlWhere = "SELECT * FROM `page` WHERE system = '0' AND draft = '0' AND (\n\t\t\turl = 'index.html' OR (parent_id = '0' AND show_in_menu = '1') OR (parent_id = '-1' AND show_in_menu = '2')\n\t\t OR (parent_id = '0' OR parent_id IN (SELECT DISTINCT `page`.`id` FROM `page` WHERE (parent_id = '0') AND (system = '0') AND (show_in_menu = '1')) )\n\t\t OR id IN ( SELECT DISTINCT `page_id` FROM `page_fa` )\n\t\t OR id IN ( SELECT DISTINCT `page_id` FROM `page_has_option` )\n\t\t ) ORDER BY `order` ASC"; $pages = $dbAdapter->fetchAll($pagesSqlWhere); if (is_array($pages) && !empty($pages)) { $data['page'] = $pages; unset($pages); } // combining list of queries for export others tables content $queryList = array(); $enabledPlugins = Tools_Plugins_Tools::getEnabledPlugins(true); foreach ($enabledPlugins as $plugin) { $pluginsData = Tools_Plugins_Tools::runStatic(self::PLUGIN_EXPORT_METHOD, $plugin); if (!$pluginsData) { continue; } if (isset($pluginsData['pages']) && is_array($pluginsData['pages']) && !empty($pluginsData['pages'])) { $data['page'] = array_merge($data['page'], $pluginsData['pages']); } if (isset($pluginsData['tables']) && is_array($pluginsData['tables']) && !empty($pluginsData['tables'])) { foreach ($pluginsData['tables'] as $table => $query) { if (array_key_exists($table, $this->_fullThemesSqlMap)) { continue; } $queryList[$table] = $query; unset($table, $query); } } if (isset($pluginsData['media']) && is_array($pluginsData['media']) && !empty($pluginsData['media'])) { $mediaFiles = array_unique(array_merge($mediaFiles, $pluginsData['media'])); } } unset($enabledPlugins); // getting list of pages ids for export $pagesIDs = array_map(function ($page) { return $page['id']; }, $data['page']); // building list of dump queries and executing it with page IDS substitution $queryList = array_merge($this->_fullThemesSqlMap, $queryList); foreach ($queryList as $table => $query) { $data[$table] = $dbAdapter->fetchAll($dbAdapter->quoteInto($query, $pagesIDs)); } unset($queryList, $pagesIDs); if (!empty($data)) { $exportData = new Zend_Config($data); $themeDataFile = new Zend_Config_Writer_Json(array('config' => $exportData, 'filename' => $themePath . self::THEME_DATA_FILE)); $themeDataFile->write(); } // exporting list of media files $totalFileSize = 0; // initializing files size counter $previewFolder = $this->_websiteHelper->getPreview(); $pagePreviews = array_filter(array_map(function ($page) use($previewFolder) { return !empty($page['preview_image']) ? $previewFolder . $page['preview_image'] : false; }, $data['page'])); $contentImages = array(); // list of images from containers if (!empty($data['container'])) { foreach ($data['container'] as $container) { preg_match_all('~media[^"\']*\\.(?:jpe?g|gif|png)~iu', $container['content'], $matches); if (!empty($matches[0])) { $contentImages = array_merge($contentImages, array_map(function ($file) { $file = explode(DIRECTORY_SEPARATOR, $file); if ($file[2] !== 'original') { $file[2] = 'original'; } return implode(DIRECTORY_SEPARATOR, $file); }, $matches[0])); } unset($matches, $container); } } $mediaFiles = array_merge($pagePreviews, $contentImages, $mediaFiles); $mediaFiles = array_unique(array_filter($mediaFiles)); if (!empty($mediaFiles)) { clearstatcache(); foreach ($mediaFiles as $key => $file) { if (!is_file($websitePath . $file)) { $mediaFiles[$key] = null; continue; } $totalFileSize += filesize($websitePath . $file); } } if ($totalFileSize > self::THEME_FULL_MAX_FILESIZE) { $this->_error('Too many images'); } else { $mediaFiles = array_filter($mediaFiles); } } // if requested name is current one we create system file with template types if ($themeName === $this->_configHelper->getConfig('currentTheme')) { // saving template types into theme.ini. @see Tools_Template_Tools::THEME_CONFIGURATION_FILE $themeIniConfig = new Zend_Config(array(), true); foreach (Application_Model_Mappers_TemplateMapper::getInstance()->fetchAll() as $template) { $themeIniConfig->{$template->getName()} = $template->getType(); } if (!empty($themeIniConfig)) { try { $iniWriter = new Zend_Config_Writer_Ini(array('config' => $themeIniConfig, 'filename' => $themePath . Tools_Template_Tools::THEME_CONFIGURATION_FILE)); $iniWriter->write(); } catch (Exception $e) { Tools_System_Tools::debugMode() && error_log($e->getMessage()); } } unset($themeIniConfig, $iniWriter); } //defining list files that needs to be excluded $excludeFiles = array(); if (!$full) { array_push($excludeFiles, self::THEME_DATA_FILE); } if ($noZip === true) { // backup media files to theme subfolder if (!empty($mediaFiles)) { if (!is_dir($themePath . 'previews')) { Tools_Filesystem_Tools::mkDir($themePath . 'previews'); } if (!is_dir($themePath . 'media')) { Tools_Filesystem_Tools::mkDir($themePath . 'media'); } foreach ($mediaFiles as $file) { if (!is_file($websitePath . $file)) { continue; } $path = explode(DIRECTORY_SEPARATOR, $file); if (!is_array($path) || empty($path)) { continue; } switch ($path[0]) { case 'previews': list($folder, $filename) = $path; break; case 'media': $folder = 'media' . DIRECTORY_SEPARATOR . $path[1]; if (!is_dir($themePath . $folder)) { Tools_Filesystem_Tools::mkDir($themePath . $folder); } $filename = end($path); break; default: continue; break; } $destination = $themePath . $folder . DIRECTORY_SEPARATOR . $filename; try { $r = Tools_Filesystem_Tools::copy($websitePath . $file, $destination); } catch (Exception $e) { Tools_System_Tools::debugMode() && error_log($e->getMessage()); } } } return true; } else { //create theme zip archive $themeArchive = Tools_Theme_Tools::zip($themeName, isset($mediaFiles) ? $mediaFiles : false, $excludeFiles); if ($themeArchive) { $body = file_get_contents($themeArchive); if (false !== $body) { Tools_Filesystem_Tools::deleteFile($themeArchive); } else { $this->_error('Unable to read website archive file'); } } else { $this->_error('Can\'t create website archive'); } //outputting theme zip $this->_response->clearAllHeaders()->clearBody(); $this->_response->setHeader('Content-Disposition', 'attachment; filename=' . $themeName . '.zip')->setHeader('Content-Type', 'application/zip', true)->setHeader('Content-Transfer-Encoding', 'binary', true)->setHeader('Expires', date(DATE_RFC1123), true)->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)->setHeader('Pragma', 'public', true)->setBody($body)->sendResponse(); exit; } }
/** * Method returns template editing screen * and saves edited template */ public function templateAction() { $templateForm = new Application_Form_Template(); $templateName = $this->getRequest()->getParam('id'); $mapper = Application_Model_Mappers_TemplateMapper::getInstance(); $currentTheme = $this->_helper->config->getConfig('currentTheme'); if (!$this->getRequest()->isPost()) { $templateForm->getElement('pageId')->setValue($this->getRequest()->getParam('pid')); if ($templateName) { $template = $mapper->find($templateName); if ($template instanceof Application_Model_Models_Template) { $templateForm->getElement('content')->setValue($template->getContent()); $templateForm->getElement('name')->setValue($template->getName()); $templateForm->getElement('id')->setValue($template->getName()); $templateForm->getElement('templateType')->setValue($template->getType()); $this->view->pagesUsingTemplate = Tools_Page_Tools::getPagesCountByTemplate($templateName); } //get template preview image try { $templatePreviewDir = $this->_websiteConfig['path'] . $this->_themeConfig['path'] . $currentTheme . DIRECTORY_SEPARATOR . $this->_themeConfig['templatePreview']; $images = Tools_Filesystem_Tools::findFilesByExtension($templatePreviewDir, '(jpg|gif|png)', false, true, false); if (isset($images[$template->getName()])) { $this->view->templatePreview = $this->_themeConfig['path'] . $currentTheme . '/' . $this->_themeConfig['templatePreview'] . $images[$template->getName()]; } } catch (Exceptions_SeotoasterException $se) { $this->view->templatePreview = 'system/images/no_preview.png'; } } } else { if ($templateForm->isValid($this->getRequest()->getPost())) { $templateData = $templateForm->getValues(); $originalName = $templateData['id']; if ($templateData['templateType'] === Application_Model_Models_Template::TYPE_MOBILE || preg_match('~^mobile_~', $templateData['name'])) { $isMobileTemplate = true; $templateData['name'] = 'mobile_' . preg_replace('~^mobile_~', '', $templateData['name']); $templateData['templateType'] = Application_Model_Models_Template::TYPE_MOBILE; } else { $isMobileTemplate = false; } //check if we received 'id' in request and try to find existing template with this id /** * @var $template Application_Model_Models_Template */ if (!empty($originalName) && null !== ($template = $mapper->find($originalName))) { $status = 'update'; // avoid renaming of system protected templates if (!in_array($template->getName(), $this->_protectedTemplates)) { $template->setOldName($originalName); $template->setName($templateData['name']); } else { // TODO throw error if trying to rename protected template } $template->setContent($templateData['content']); } else { $status = 'new'; //if ID missing and name is not exists and name is not system protected - creating new template if (in_array($templateData['name'], $this->_protectedTemplates) || null !== $mapper->find($templateData['name'])) { $this->_helper->response->response($this->_translator->translate('Template with such name already exists'), true); } $template = new Application_Model_Models_Template($templateData); } $template->setType($templateData['templateType']); // saving/updating template in db $result = $mapper->save($template); if ($result) { $this->_helper->cache->clean(false, false, array(preg_replace('/[^\\w\\d_]/', '', $template->getName()))); } // saving to file in theme folder $currentThemePath = realpath($this->_websiteConfig['path'] . $this->_themeConfig['path'] . $currentTheme); $filepath = $currentThemePath . DIRECTORY_SEPARATOR; if ($isMobileTemplate) { if (!is_dir($filepath . 'mobile')) { Tools_Filesystem_Tools::mkDir($filepath . 'mobile'); } $filepath .= preg_replace('~^mobile_~', 'mobile' . DIRECTORY_SEPARATOR, $template->getName()); } else { $filepath .= $templateData['name']; } $filepath .= '.html'; try { if ($filepath) { Tools_Filesystem_Tools::saveFile($filepath, $templateData['content']); } if ($status === 'update' && $template->getOldName() !== $template->getName()) { $oldFilename = $currentThemePath . DIRECTORY_SEPARATOR; if ($isMobileTemplate) { $oldFilename .= preg_replace('~^mobile_~', 'mobile' . DIRECTORY_SEPARATOR, $template->getOldName()); } else { $oldFilename .= $template->getOldName(); } $oldFilename .= '.html'; if (is_file($oldFilename)) { if (false === Tools_Filesystem_Tools::deleteFile($oldFilename)) { } } unset($oldFilename); } } catch (Exceptions_SeotoasterException $e) { Tools_System_Tools::debugMode() && error_log($e->getMessage()); } $this->_helper->cache->clean(Helpers_Action_Cache::KEY_PLUGINTABS, Helpers_Action_Cache::PREFIX_PLUGINTABS); $this->_helper->response->response($status, false); } else { $errorMessages = array(); $validationErrors = $templateForm->getErrors(); $messages = array('name' => array('isEmpty' => 'Template name field can\'t be empty.', 'notAlnum' => 'Template name contains characters which are non alphabetic and no digits', 'stringLengthTooLong' => 'Template name field is too long.', 'stringLengthTooShort' => 'Template name field is too short.'), 'content' => array('isEmpty' => 'Content can\'t be empty.')); foreach ($validationErrors as $element => $errors) { if (empty($errors)) { continue; } foreach ($messages[$element] as $n => $message) { if (in_array($n, $errors)) { array_push($errorMessages, $message); } } } $this->_helper->response->response($errorMessages, true); } } $this->view->helpSection = 'addtemplate'; $this->view->templateForm = $templateForm; }