notice ('Creating DB configuration file.'); $connection = $this->getIniParser ()->parseDatabaseConnection (); $database_php = DATADIR . '/config/database.php'; if (file_exists (DATADIR . '/config/tmp.database.php')) { $database_php = DATADIR . '/config/tmp.database.php'; } if (file_exists ($database_php)) { $result = unlink ($database_php); if (!$result) { throw new Exception ("Cannot remove file $database_php"); } } $text = << false, 'persistent' => true, 'connection' => array ( 'type' => "@type", 'user' => "@user", 'pass' => "@pass", 'host' => "@host", 'port' => "@port", 'socket' => FALSE, 'database' => "@database" ), 'character_set' => 'utf8', 'table_prefix' => '@prefix', 'object' => TRUE, 'cache' => FALSE, 'escape' => TRUE ); text; $replacements = array ( 'type' => $connection->getType (), 'user' => $connection->getUser (), 'pass' => $connection->getPassword (), 'host' => $connection->getHost (), 'port' => $connection->getPort (), 'database' => $connection->getDatabase (), 'prefix' => $connection->getTablePrefix (), ); foreach ($replacements as $key => $value) { $text = str_replace ('@' . $key, $this->escape ($value), $text); } $bytes_written = file_put_contents ($database_php, $text); if ($bytes_written !== strlen ($text)) { throw new Exception ("Can not write to file $database_php"); } } function saveThemeName ($theme) { $setting = new Setting (Setting_Model::S_THEME, $theme, 'Active theme'); $setting->setType (Setting_Model::TYPE_THEME); $setting->setExportable (false); $this->saveSetting ($setting); } function saveAdultState ($state) { $setting = new Setting (Setting_Model::S_ADULT, $state, 'Show adult templates'); $setting->setType (Setting_Model::TYPE_ADULT); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $setting->setExportable (false); $this->saveSetting ($setting); } public function updateTemplateCount () { if ($this->flagDatabaseOperation ()) { $this->notice ('Updating template counters.'); $this->updateTemplateCountDictionary ('templateauthor') ->updateTemplateCountDictionary ('templatetype') ->updateTemplateCountDictionary ('templatecategory') ->updateTemplateCountDictionary ('templatepackage'); $this->updateEnabledTemplateCounters (); } } public function updateEnabledTemplateCounters () { if ($this->flagDatabaseOperation ()) { $this->notice ('Updating enabled template counters.'); $this->updateEnabledTemplateCountDictionary ('templatetype'); $this->updateEnabledTemplateCountDictionary ('templatecategory'); { $database = Database::instance(); $database->push (); $database->delete ('settings', array ('id' => Setting_Model::S_TEMPLATE_COUNTER_UPDATE)); $database->pop (); } } } protected function updateLastTimeParameter () { $this->notice ('Updating last update time.'); $setting = ORM::factory ('setting', Setting_Model::S_LAST_UPDATE); if (!$setting->isExist ()) { throw new Exception_BadInstallation (Exception_BadInstallation::E_NO_SETTINGS, 'S_LAST_UPDATE'); } $setting->setForced (true); $setting->value = date ('r'); $setting->save (); } protected function saveAdminCredentials ($login, $password) { $setting = new Setting (Setting_Model::S_ADMIN_LOGIN, $login, 'Admin login'); $setting->setExportable (false); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_ADMIN_PASSWORD, $password, 'Admin password'); $setting->setType (Setting_Model::TYPE_PASSWORD); $setting->setExportable (false); $this->saveSetting ($setting); } protected function getDownloader () { $d = new TM_Downloader (); $d->logger ($this->logger ()); return $d; } function importInitialSettings () { ORM::factory ('discount')->delete_all (); $data = $this->parseJsonFile (DATADIR . '/setup/settings.json'); if ($data) { if (isset ($data ['preset-discount'])) { $setting = ORM::factory ('setting', Setting_Model::S_DISCOUNT_PERCENT); $setting->value = $data ['preset-discount']; $setting->save (); } if (isset ($data ['type-category-discount'])) { if (is_array ($data ['type-category-discount'])) { foreach ($data ['type-category-discount'] as $row) { list ($discounttype_id, $entity_id, $value) = $row; $discount = ORM::factory ('discount'); $discount->discounttype_id = $discounttype_id; $discount->entity_id = $entity_id; $discount->discount = $value; $discount->save (); } } } if (isset ($data ['webapi-password'])) { $setting = ORM::factory ('setting', Setting_Model::S_WEBAPIPASSWORD); $setting->value = $data ['webapi-password']; $setting->save (); } if (isset ($data ['currency-rate'])) { $setting = ORM::factory ('setting', Setting_Model::S_CURRENCY_RATE); $setting->value = $data ['currency-rate']; $setting->renew (); } } unset ($data); ORM::factory ('discount')->recalculateTemplatePrice (); } private function parseJsonFile ($filename) { try { $locale = new File ($filename); $locale->open (File::OPEN_MODE_READ); $data = json_decode ($locale->getContents (), true); if ($data) { if (is_array ($data)) { return $data; } } } catch (File_Exception $e) { } } function updateDictionaries ($initial = false) { if ($this->flagDatabaseOperation ()) { $download = $this->getDownloader ()->download (TM_Downloader::ENTITY_DICTIONARY, $this->flagForceFileDownload ()); $parser = new Parser_JSON_TMInfoDir (file_get_contents ($download)); $this->notice ('Updating authors.'); $authors = new Dictionary_Author (); $authors->update ($parser->parseAuthors ()); unset ($authors); $this->notice ('Updating software dictionary.'); $software = new Dictionary_Software (); $software->update ($parser->parseSoftwares ()); unset ($software); $this->notice ('Updating source dictionary.'); $sources = new Dictionary_Source (); $sources->update ($parser->parseSources ()); unset ($sources); $this->notice ('Updating packages.'); $packages = new Dictionary_Package (); $packages->update ($parser->parsePackages (), $initial); $this->notice('Updating package texts'); $packages->updatePackageTexts($parser->parsePackages ()); unset ($packages); $this->notice ('Updating keywords.'); $keywords = new Dictionary_Keyword (); $keywords->update ($parser->parseKeywords ()); unset ($keywords); $this->notice ('Updating styles.'); $styles = new Dictionary_Style (); $styles->update ($parser->parseStyles ()); unset ($styles); $this->notice ('Updating categories.'); $categories = new Dictionary_Category (); $categories->update ($parser->parseCategories (), $initial); unset ($categories); $this->notice ('Updating types.'); $types = new Dictionary_Type (); $types->update ($parser->parseTypes (), $initial); unset ($types); $this->notice ('Updating screenshot descriptions.'); $descriptions = new Dictionary_ScreenshotDescription (); $descriptions->update ($parser->parseScreenshotDescs ()); unset ($descriptions); $this->notice ('Updating screenshot hrefs.'); $hrefs = new Dictionary_ScreenshotHref (); $hrefs->update ($parser->parseScreenshotHrefs ()); unset ($hrefs); } } function updateLocale () { if ($this->flagDatabaseOperation ()) { $locale_id = util::getLocaleId (); if (isset ($locale_id)) { $download = $this->getDownloader ()->download (TM_Downloader::ENTITY_LOCALE, $this->flagForceFileDownload ()); $parser = new Parser_JSON_TMLocale (file_get_contents ($download), $locale_id); $rounds = array ( 'templatetype' => 'parseTypeNames', 'templatecategory' => 'parseCategoryNames', ); foreach ($rounds as $model => $function_name) { foreach ($parser->$function_name () as $primary_key => $title) { $entity = ORM::factory ($model, $primary_key); if ($entity->isExist ()) { if (! $entity->isEdited ()) { $entity->html_name = $title; $entity->list_name = $title; $entity->save (); } } } } $text = ORM::factory('text')->byName('PACKAGE_DESCRIPTION'); if ($text->isExist()) { foreach ($parser->parsePackage() as $primary_key=>$package) { $entity = ORM::factory('templatepackage', $primary_key); if ($entity->isExist() && ! $entity->isEdited()) { $title = trim($package['title']); $description = trim($package['description']); if ($title) { $entity->list_name = $title; $entity->html_name = $title; $entity->save(); } if ($description) { $text_content = ORM::factory('text_content') ->where('table', Text_content_Model::TABLE_PACKAGE) ->where('table_id', $primary_key) ->where('text_id', $text->id) ->find(); if($text_content->isExist()) { $text_content->content = $description; } else { $text_content->id = ''; $text_content->table = Text_content_Model::TABLE_PACKAGE; $text_content->table_id = $primary_key; $text_content->text_id = $text->id; $text_content->title = 'description'; $text_content->content = $package['description']; } $text_content->save(); } } } } } } } protected function cleanUpDictionaries () { $this->notice ('Cleaning dictionaries.'); $parser = $this->getIniParser (); $all_types = new Setting (Setting_Model::S_ALL_TYPES, 0, 'Install all template types'); $this->updateTemplatePropertyList ($parser->parseTemplateTypes (), $all_types, 'templatetype', array ($this, 'removeTemplatesByType')); $all_categories = new Setting (Setting_Model::S_ALL_CATEGORIES, 0, 'Install all template categories'); $this->updateTemplatePropertyList ($parser->parseTemplateCategories (), $all_categories, 'templatecategory', array ($this, 'removeTemplatesByCategory')); if (! ($all_types->getValue () && $all_categories->getValue ())) { $this->removeCategorylessTempaltes (); } $this->saveClusterVisibility ('templatetype', $parser->parseVisibleEverywhereTypes (), TemplateType_Model::STATE_VISIBLE_EVERYWHERE); $this->saveClusterVisibility ('templatetype', $parser->parseVisibleExceptHomeTypes (), TemplateType_Model::STATE_VISIBLE_IN_LIST); } protected function removeTemplatesByType ($type_id) { Database::instance()->delete ('templates', array ('templatetype_id' => $type_id)); return; if (0) { $list = ORM::factory ('template')->where ('templatetype_id', $type_id); foreach ($list->find_all () as $template) { if ($template->isExist ()) { $template->delete (); } } } } protected function removeTemplatesByCategory ($category_id) { $database = Database::instance(); $database ->select ('ct1.template_id') ->from ('templatecategories_templates AS ct1') ->join ('templatecategories_templates AS ct2', array ('ct1.template_id' => 'ct2.template_id', 'ct2.templatecategory_id !=' => $category_id), null, 'LEFT') ->where ('ct1.templatecategory_id', $category_id) ->where ('ct2.templatecategory_id', null) ; $result = $database->get (); foreach ($result as $row) { Database::instance()->delete ('templates', array ('id' => $row->template_id)); if (0) { $template = ORM::factory ('template', $row->template_id); if ($template->isExist ()) { $template->delete (); } } } } protected function removeCategorylessTempaltes () { $database = Database::instance(); $database ->select ('templates.id') ->from ('templates') ->join ('templatecategories_templates', array ('templatecategories_templates.template_id' => 'templates.id'), null, 'LEFT') ->where ('templatecategory_id IS NULL'); $result = $database->get (); foreach ($result as $row) { Database::instance()->delete ('templates', array ('id' => $row->id)); } } function clearTemplates () { ORM::factory ('template')->delete_all (); ORM::factory ('screenshot')->delete_all (); $prefix = $this->getTablePrefix (); $this->query ("DELETE FROM `{$prefix}templatecategories_templates`"); $this->query ("DELETE FROM `{$prefix}templatekeywords_templates`"); $this->query ("DELETE FROM `{$prefix}templates_templatestyles`"); $this->query ("DELETE FROM `{$prefix}templates_templatesources`"); $this->query ("DELETE FROM `{$prefix}templates_templatesoftwares`"); $this->query ("DELETE FROM `{$prefix}templatesubsections`"); $this->query ("DELETE FROM `{$prefix}screenshots_templatesubsections`"); } function updateCurrencyRate () { $currecy_id = Zend_Registry::get ('Environment')->getCurrencyId (); if ($currecy_id) { $this->notice ('Updating currency rate.'); $webapi_password_setting = ORM::factory ('setting', Setting_Model::S_WEBAPIPASSWORD); $affiliate_login_setting = ORM::factory ('setting', Setting_Model::S_AFF_LOGIN); if ($webapi_password_setting->exists ()) if ($affiliate_login_setting->exists ()) { $currency_rate_setting = ORM::factory ('setting', Setting_Model::S_CURRENCY_RATE); $webapi = new TM_Webapi ($affiliate_login_setting->value, $webapi_password_setting->value); $rates = $webapi->getCurrencyRates (); $currency_rate_setting->value = 1; if ($rates and isset ($rates [$currecy_id])) { $this->notice ('Sane response is received from the update server.'); $currency_rate_setting->value = $rates [$currecy_id] ['rate']; } else { $this->notice ('Invalid response has been received from the update server.'); } $this->notice ('Currency rate is ' . $currency_rate_setting->value); $currency_rate_setting->renew (); return; } } $this->notice ('No currency rate update was made.'); } function updateTemplates (&$installed_templates = array ()) { if ($this->flagDatabaseOperation ()) { $i = (int) $this->getIniParser ()->parseTemplatesToInstall (); $start_from = (int) $this->getIniParser ()->parseTemplateStartFrom (); if ($i > 0) { $this->notice ("Gonna install $i new templates this time (only for debug purposes). "); if ($start_from) { $this->notice ("Starting from {$start_from}."); } } elseif ($i == 0) { $this->notice ('Installing no templates.'); return; } else { $this->notice ('Updating templates.'); } $download = $this->getDownloader ()->download (TM_Downloader::ENTITY_TEMPLATE, $this->flagForceFileDownload ()); $t_info = fopen ($download, 'rt'); try { $last_processed_template_id = 0; $installed_so_far = 0; while ($line = fgets ($t_info)) { list ($template_id, $hash, $json) = explode ('=', $line, 3); $template_id = (int) $template_id; if ($start_from) { if ($start_from > $template_id) { continue; } } if (!(isset ($template_id) and isset ($hash) and isset ($json))) { throw new Exception ('Invalid template file format.'); } if ($this->getTemplatesToInstall ()) { if (!in_array ($template_id, $this->getTemplatesToInstall ())) { continue; } } $template = ORM::factory ('template', $template_id); $changed = $template->hash != $hash; if ($this->flagForceTemplateUpdated ()) { $changed = true; } if ($changed) { if ($template->isExist ()) { $template->delete (); $operation = 'Updating'; } else { $operation = 'Installing'; } $parser = new Parser_JSON_TMInfo ($json); if ($parser->parseProperty ('State') == 1) { if ($this->isTemplateEligibleToBeInstalled ($template_id, $parser)) { if (!isset ($flag_now_installing)) { $flag_now_installing = 1; $this->notice ('Installing templates.'); } $this->info ("{$operation} template {$template_id}"); if ($this->installTemplate ($template_id, $parser, $hash)) { $installed_templates[$operation][] = $template_id; $installed_so_far++; if ($i != -1) { if (--$i < 1) { break; } } if ($installed_so_far % 100 == 0) { $this->notice (sprintf ('%s templates have been installed so far.', $installed_so_far)); } } } else { $this->info ("Template $template_id is not eligible to be installed."); } } } else { $this->info ("Template {$template->id} is intact."); } if (! $this->flagNoPurgeTemplates ()) { $this->purgeRemovedTemplates ($last_processed_template_id, $template_id); } $last_processed_template_id = $template_id; } $this->notice ("$installed_so_far templates were installed."); return $installed_so_far; } catch (Kohana_Database_Exception $e) { echo 'Stopped at ' . $template_id; echo $e->getMessage (); exit; } } } function updateDiscountedPrice () { ORM::factory ('discount')->updateDiscountedTemplatePrice (); } private function purgeRemovedTemplates ($id_start, $id_finish) { $list = ORM::factory ('template') ->where ('id >', $id_start) ->where ('id <', $id_finish) ->find_all () ; if ($list->count ()) { foreach ($list as $item) { $this->info ("Template {$item->id} is no more available and has been removed."); ORM::factory('template', $item->id)->delete (); } } } private function installTemplate ($template_id, $parser, $hash) { $template = ORM::factory ('template'); $template->id = $template_id; $template->price = $parser->parseProperty ('Price'); $template->exc_price = $parser->parseProperty ('ExclusivePrice'); $template->download_count = $parser->parseProperty ('DownloadCount'); $template->is_adult = $parser->parseProperty ('AdultState'); $template->templateauthor_id = $parser->parseProperty ('AuthorId'); $template->templatepackage_id = $parser->parseProperty ('PackageId'); $template->templatetype_id = $parser->parseProperty ('TypeId'); $template->inserted_date = $parser->parseProperty ('InsertedDate'); $template->updated_date = $parser->parseProperty ('UpdatedDate') ? $parser->parseProperty ('UpdatedDate') : '0000-00-00 00:00:00'; $template->small_preview_id = $parser->parseProperty ('SmallPreviewId'); $template->large_preview_id = $parser->parseProperty ('LargePreviewId'); $template->hash = $hash; $relations = array ( array ('Styles', 'templatestyle'), array ('Softwares', 'templatesoftware'), array ('Sources', 'templatesource'), array ('Categories', 'templatecategory'), array ('Keywords', 'templatekeyword'), ); foreach ($relations as $relation) { list ($property, $model) = $relation; $model_relations = $parser->parseProperty ($property); $this->addRelations ($template, $model, $model_relations); } $pages = $parser->parseProperty ('Pages'); $screenshots = $parser->parseProperty ('ScreenshotList'); if (is_array ($screenshots)) { foreach ($screenshots as $screenshot_id => $screenshot) { $record = ORM::factory ('screenshot', $screenshot_id); $record->uri = $screenshot ['file']; $record->width = isset ($screenshot ['width']) ? $screenshot ['width'] : 0; $record->height = isset ($screenshot ['height']) ? $screenshot ['height'] : 0; $record->is_wide = $screenshot ['wide']; $record->position = $screenshot ['position']; $record->template_id = $template_id; $record->nobr = $screenshot ['no_br']; $record->screenshot_href_id = isset ($screenshot ['href_id']) ? $screenshot ['href_id'] : 0; $record->screenshot_description_id = $screenshot ['description_id']; $record->renew (); } } if ($pages) { foreach ($pages as $page_name => $page_data) { $page = ORM::factory ('templatesubsection'); $page->template_id = $template_id; $page->position = $page_data ['position']; $subsection = ORM::factory ('subsection')->where ('description', $page_name)->find (); if ($subsection->id == 0) { $subsection->description = $page_name; $subsection->save (); } $page->subsection_id = $subsection->id; foreach ($page_data ['screenshots'] as $scr_id) { $screenshot = ORM::factory ('screenshot', $scr_id); if ($screenshot->loaded) { $page->add ($screenshot); } else { $this->notice ('Warning: could not find screenshot ' . $scr_id . ' for template ' . $template_id); } } $page->save (); } } $template->save (); return true; } private function isTemplateEligibleToBeInstalled ($template_id, Parser_JSON_TMInfo $parser) { $adult_site_status = Setting_Model::get (Setting_Model::S_ADULT); $adult_template_status = $parser->parseProperty ('AdultState'); if (0 == $adult_site_status) { if (1 == $adult_template_status) { return false; } } elseif (1 == $adult_site_status) { if (0 == $adult_template_status) { return false; } } $all_types = (bool) Setting_Model::get (Setting_Model::S_ALL_TYPES); $all_categories = (bool) Setting_Model::get (Setting_Model::S_ALL_CATEGORIES); $type_id = $parser->parseProperty ('TypeId'); $categories = $parser->parseProperty ('Categories'); if ($all_types or in_array ($type_id, $this->getInstalledTypes ())) { if ($all_categories) { return true; } if (is_array ($categories)) { foreach ($categories as $category_id) { if (in_array ($category_id, $this->getInstalledCategories ())) { return true; } } } } } private function getInstalledTypes () { if (!isset ($this->installed_types)) { $this->installed_types = ORM::factory ('templatetype')->getAllPrimaryKeys (); } return $this->installed_types; } private function getInstalledCategories () { if (!isset ($this->installed_categories)) { $this->installed_categories = ORM::factory ('templatecategory')->getAllPrimaryKeys (); } return $this->installed_categories; } private function addRelations ($rec, $model_name, $model_relations) { if (!empty ($model_relations)) { foreach ($model_relations as $relative_id) { $relative = ORM::factory ($model_name, $relative_id); if ($relative->isExist ()) { $rec->add ($relative); } else { $this->warn ("No relation $relative_id for $model_name"); } } } } function saveClusterVisibility ($model_name, array $item_list, $visibility) { if ($item_list) { foreach (ORM::factory ($model_name)->in ('name', $item_list)->find_all () as $item) { $item->visibility = $visibility; $item->save (); } } } function saveScreenshotLocalState ($state) { $setting = new Setting (Setting_Model::S_SCREENSHOT_LOCAL, (int)$state, 'Images are stored locally'); $setting->setType (Setting_Model::TYPE_CHECKBOX); $setting->setExportable (false); $this->saveSetting ($setting); } function saveScreenshotRemoteUrl ($url) { $setting = new Setting (Setting_Model::S_SCREENSHOT_REMOTE_URL, $url, 'Remote screenshot URL'); $setting->setType (Setting_Model::TYPE_TEXT); $this->saveSetting ($setting); } function saveScreenshotDir ($dir) { $setting = new Setting (Setting_Model::S_SCREENSHOT_LOCAL_DIR, $dir, 'Local directory containing screenshots'); $setting->setType (Setting_Model::TYPE_LOCALDIR); $setting->setExportable (false); $this->saveSetting ($setting); } function saveAffiliateParameters ($affiliate) { extract ($affiliate); $setting = new Setting (Setting_Model::S_AFF_EMAIL, $email, "Admin's email address"); $setting->setExportable (false); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_AFF_CODE, $preset_code, 'Affiliate preset code'); $setting->setExportable (false); $setting->setReadOnly (true); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_AFF_LOGIN, $login, 'Affiliate login'); $setting->setExportable (false); $setting->setReadOnly (true); $this->saveSetting ($setting); } function saveFeaturedTemplateTypes ($types) { $record = ORM::factory ('templatetype'); $record->resetField ('position_featured'); $i = 0; foreach ($types as $type) { $record = ORM::factory ('templatetype')->where ('name', $type)->find (); if ($record->isExist ()) { $record->position_featured = ++$i; $record->save (); } } } private function updateTemplatePropertyList ($list, Setting $setting, $modelname, $callback_remove) { $all = (($list == array ('all')) || empty ($list)); $setting->setValue (intval ($all)); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $setting->setExportable (false); $this->saveSetting ($setting); if (! $all) { $list_from_db = ORM::factory ($modelname)->find_all (); array_walk ($list, array ($this, 'strLower')); foreach ($list_from_db as $record) { if (! in_array (strtolower ($record->name), $list)) { call_user_func ($callback_remove, $record->getId ()); $record->delete (); } } } } private function strLower (&$str) { $str = strtolower ($str); } function supressErrors () { $r = set_error_handler (array ($this, 'supressErrorHandler')); echo '
'; print_r ($r); echo '
'; } function restoreErrorControl () { restore_error_handler (); } function supressErrorHandler () { return true; } private function escape ($string) { $string = new String ($string); return $string->escapePhp ()->__toString (); } function patchDatabase () { $this->notice ('Looking for pending patches'); $patcher = new Update_Patcher (); $patches = $patcher->getPendingDbPatches (); if ($patches) { $this->notice (sprintf ('Found %u pending patch(es)', count ($patches))); try { foreach ($patches as $patch) { $patch->logger ($this->logger ()); $patch->apply (); $this->saveLastPatchNumber ($patch->getNumber ()); } } catch (Exception $e) { $url = url::getSiteRootUrl (); $message = $e->getMessage (); $sql = ''; try { foreach ($patches as $patch) { foreach ($patch->getQueries () as $query) { $sql .= (string) $query; $sql .= "\n\n"; } } } catch (Exception $e) { } $message = <<notice ('No pending patches found.'); } } function retainLatestPatchRevision () { $patcher = new Update_Patcher (); $max_version = 0; foreach ($patcher->getAvailableDbPatches () as $patch) { $max_version = max ($max_version, $patch->getNumber ()); } $this->saveLastPatchNumber ($max_version); } private function saveLastPatchNumber ($number) { $setting = ORM::factory ('setting', Setting_Model::S_LAST_PATCH_NUMBER); $setting->id = Setting_Model::S_LAST_PATCH_NUMBER; $setting->value = $number; $setting->save (); } function createDatabaseStructure () { if ($this->flagDatabaseOperation ()) { $this->notice ('Creating database structure.'); $sql_splitter = new SqlSplitter (); $queries = $sql_splitter->split (DATADIR . '/setup/start.sql'); foreach ($queries as $query) { $query->setPrefix ($this->getIniParser ()->parseDatabaseConnection ()->getTablePrefix ()); $this->query ($query); } } } function importInitialDataset () { if ($this->getIniParser()->parseImportInitialData ()) { $adult = (int) $this->getIniParser ()->parseAdult (); $files_to_import = array ( 'dictionaries.sql', ); if ($adult != 0) { $files_to_import [] = 'adult.sql'; } if (($adult & 1) == 0) { $files_to_import [] = 'modest.sql'; } foreach ($files_to_import as $file) { $initial = new File(DATADIR . '/setup/' . $file); $initial->open (File::OPEN_MODE_READ); while ($line = $initial->readLine ()) { $line = trim ($line); if ($line) { $this->query (new SqlQuery ($line)); } } $initial->close (); } } } function query ($query) { $db = Database::instance (); $result = $db->query ($query); if (empty ($result)) { throw new Exception (mysql_error ()); } return $result; } function getTablePrefix () { $db = Database::instance (); return $db->table_prefix(); } function saveSetting (Setting $setting) { $rec = ORM::factory ('setting', $setting->getName ()); $rec->loadSetting ($setting); $rec->setForced (true); $rec->save (); } function getSetting ($name) { $rec = ORM::factory ('setting', $name); if ($rec->isExist ()) { return $rec->value; } } function generateCronString () { $command = PHP_BINDIR . "/php -f " . DOCROOT . "update.php"; return $command; } function getCheckAffiliateUrl () { $result = Kohana::config ('core.check_affiliate_url') or $result = 'http://www.mytemplatestorage.com'; return $result . '/check_aff.php'; } function testAffiliateSettings (array $settings) { if (isset ($settings ['login']) and isset ($settings ['preset_code'])) { $params = 'aff='.urlencode ($settings ['login']).'&pr='.urlencode ($settings ['preset_code']); $params .= '&url=1'; $curl = curl_init (); curl_setopt ($curl, CURLOPT_URL, $this->getCheckAffiliateUrl ()); curl_setopt ($curl, CURLOPT_POST, 1); curl_setopt ($curl, CURLOPT_POSTFIELDS, $params); curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec ($curl); $err = curl_errno ($curl); curl_close ($curl); if ( ($err != 0) or (strlen ($data) < 2) ) { return array (false, 'Error connection to MyTemplateStorage.com'); } if ('0' == substr ($data, 0, 1)) { return array (false, 'Wrong affiliate login'); } if ('0' == substr ($data, 1, 1)) { return array (false, 'Preset code is not valid'); } return array (true, substr ($data, 2)); } else { return array (false, 'Not enough parameters'); } } function setIniParser (Parser_Ini_Setup $ini_parser) { $this->ini_parser = $ini_parser; } function getIniParser () { return $this->ini_parser; } function flagDatabaseOperation ($flag = null) { if (isset ($flag)) { $this->flag_database_operation = $flag; } else { return $this->flag_database_operation; } } function flagForceFileDownload ($flag = null) { if (isset ($flag)) { $this->flag_force_file_download = $flag; } else { return $this->flag_force_file_download; } } function flagForceTemplateUpdated ($flag = null) { if (isset ($flag)) { $this->flag_force_template_updated = $flag; } else { return $this->flag_force_template_updated; } } function flagNoPurgeTemplates ($flag = null) { if (isset ($flag)) { $this->flag_no_purge_template = $flag; } else { return $this->flag_no_purge_template; } } public function sendEmail ($subject, $message, array $headers = array ()) { $to = $this->getSetting (Setting_Model::S_AFF_EMAIL); if (isset ($to)) { if (empty ($headers)) { $headers = array ( 'Content-type: text/html' ); } mail ( $to, $subject, $message, join ("\n", $headers) ); } } protected function setupDatabase () { $this->saveDatabaseSettingsToFile (); $this->createDatabaseStructure (); $this->importInitialDataset (); $this->retainLatestPatchRevision (); } protected function setupSettings () { $this->notice ('Saving settings.'); $parser = $this->getIniParser (); $this->login = $parser->parseAdminLogin (); $this->password = $parser->parseAdminPassword (); $this->saveAdminCredentials ($this->login, $this->password); $this->saveScreenshotLocalState ($parser->parseScreenshotLocal ()); $this->saveScreenshotRemoteUrl ($parser->parseScreenshotRemoteUrl ()); $this->saveScreenshotDir ($parser->parseScreenshotDir ()); $this->saveThemeName ($parser->parseTheme ()); $this->saveAdultState ($parser->parseAdult ()); if($parser->parseFeaturedTemplateType ()) $this->saveFeaturedTemplateTypes ($parser->parseFeaturedTemplateType ()); $this->saveAffiliateParameters ($parser->parseAffiliate ()); $setting = new Setting (Setting_Model::S_CONTACT_US, $parser->parseContactUsAddress (), 'E-mail for Contact Us form.'); $setting->setExportable (false); $this->saveSetting ($setting); $this->saveRoutes (); $this->saveConventionalParametersByDefault (); $this->createSystemPages (); $this->createConventionalPages (); $this->createTextBlocks (); } protected function saveRoutes () { $route_type = new RouteMatrix_Type (); $setting = new Setting (Setting_Model::S_ROUTE_TYPE_FIRST, $route_type->getDefaultRoute (RouteMatrix::CTX_FIRST_PAGE), "First page type route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_ROUTE_TYPE_OTHER, $route_type->getDefaultRoute (RouteMatrix::CTX_OTHER_PAGES), "Other pages type route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $route_category = new RouteMatrix_Category (); $setting = new Setting (Setting_Model::S_ROUTE_CATEGORY_FIRST, $route_category->getDefaultRoute (RouteMatrix::CTX_FIRST_PAGE), "First page category route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_ROUTE_CATEGORY_OTHER, $route_category->getDefaultRoute (RouteMatrix::CTX_OTHER_PAGES), "Other pages category route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $route_package = new RouteMatrix_Package(); $setting = new Setting(Setting_Model::S_ROUTE_PACKAGE_FIRST, $route_package->getDefaultRoute(RouteMatrix::CTX_FIRST_PAGE), "First page package route"); $setting->setStatus(Setting_Model::STATUS_HIDDEN); $this->saveSetting($setting); $setting = new Setting(Setting_Model::S_ROUTE_PACKAGE_OTHER, $route_package->getDefaultRoute(RouteMatrix::CTX_OTHER_PAGES), "Other pages package route"); $setting->setStatus(Setting_Model::STATUS_HIDDEN); $this->saveSetting($setting); $route_preview = new RouteMatrix_Preview (); $setting = new Setting (Setting_Model::S_ROUTE_PREVIEW_FIRST, $route_preview->getDefaultRoute (RouteMatrix::CTX_FIRST_PAGE), "First page preview route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_ROUTE_PREVIEW_OTHER, $route_preview->getDefaultRoute (RouteMatrix::CTX_OTHER_PAGES), "Other pages preview route"); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); } protected function downloadTemplatePreviews () { $is_local = (bool) Setting_Model::get(Setting_Model::S_SCREENSHOT_LOCAL); if ($is_local) { $this->notice ('Downloading screenshots to a local file system.'); $test = new Tester_Screenshots (); $painter = new Tester_Painter_Log (); $test->setPainter ($painter); if ($test->run ()) { $templates = ORM::factory ('template') ->where ('screenshot_download_status', Theme_Template::SCREENSHOT_STATUS_NOT_DOWNLOADED) ->orderby ('id') ->find_all () ; $screenshot_dir = Setting_Model::getScreenshotLocalDir (); $downloader = new Downloader (); $downloader->setOptions (Downloader::OPTION_CREATE_DIRECTORY, Downloader::OPTION_DOWNLOAD_IF_EMPTY); $downloaded_template_count = 0; foreach ($templates as $template) { unset ($downloaded); foreach (array ($template->small_preview->uri, $template->large_preview->uri) as $screenshot_file_name) { if ($screenshot_file_name) { $local_file_name = $screenshot_dir . $screenshot_file_name; if (!file_exists ($local_file_name) || filesize ($local_file_name) == 0) { $downloader->download ( $template->getRemoteScreenshotUrl ($screenshot_file_name), $local_file_name ); $downloaded = true; } } } $template->screenshot_download_status = Theme_Template::SCREENSHOT_STATUS_DOWNLOADED_PRIMARY; $template->save (); if (isset ($downloaded)) { $downloaded_template_count ++; } if (($downloaded_template_count > 0) && ($downloaded_template_count % 100 == 0)) { $this->notice ("Screenshots for $downloaded_template_count templates have been downloaded so far."); } if ($downloaded_template_count == 1000) { break; } } } else { $this->warn ($test->getStringResult ()); } } } protected function downloadQueuedScreenshots () { $this->notice ('Downloading queued template screenshots.'); $prefix = $this->getTablePrefix (); $status = Theme_Template::SCREENSHOT_STATUS_QUEUED_FOR_FULL_DOWNLOAD; $query = <<query ($query); if (count ($result)) { $this->notice (sprintf ('%u template(s) are in the queue', count ($result))); { $download = $this->getDownloader ()->download (TM_Downloader::ENTITY_TEMPLATE); $t_info = fopen ($download, 'rt'); $t_info_template_id = -1; } { $downloader = new Downloader (); $downloader->setOptions (Downloader::OPTION_CREATE_DIRECTORY, Downloader::OPTION_DOWNLOAD_IF_EMPTY); $downloader->setSourceDir (Template_Model::SCREENSHOT_DISTRIBUTION); $downloader->setTargetDir (Setting_Model::getScreenshotLocalDir ()); } foreach ($result as $row) { while ($t_info_template_id < $row->id) { $t_info_line = fgets ($t_info); if (! $t_info_line) { break; } list ($t_info_template_id, $t_info_hash, $t_info_json) = explode ('=', $t_info_line, 3); } if ($t_info_template_id == $row->id) { $parser = new Parser_JSON_TMInfo ($t_info_json); $full_screenshot_list = $parser->parseProperty ('ScreenshotListExt'); if ($full_screenshot_list) { foreach ($full_screenshot_list as $key => $screenshot_data) { try { $this->info ($screenshot_data ['file']); $downloader->download ($screenshot_data ['file']); } catch (Downloader_Exception $e) { $this->err ('Error downloading screenshots for template ' . $row->id); $this->err (sprintf ('Failed to download screenshot %s', $screenshot_data ['file'])); } } } } $template = ORM::factory ('template', $row->id); $template->screenshot_download_status = Theme_Template::SCREENSHOT_STATUS_FULLY_DOWNLOADED; $template->save (); } } else { $this->notice ('No template screenshots were found queued for download.'); } } protected function closeUpInstallation () { $setting = new Setting (Setting_Model::S_IS_INSTALLATION_CLOSED, 1, 'Installation is finished.'); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); } private function saveConventionalParametersByDefault () { $setting = new Setting (Setting_Model::S_FEATURED_TYPE_ROWS, 1, 'Number of rows in featured product section.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_FEATURED_TYPE_COLS, 3, 'Number of columns in featured product section.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_TEMPLATE_ROWS, 3, 'Number of rows in a template list.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_TEMPLATE_COLS, 3, 'Number of columns in a template list.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_HEADLINE, '', 'Key phrase that you can use as the part of the page TITLE on shop pages.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setType(Setting_Model::TYPE_TEXT_NOTREQUIRED); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_LAST_UPDATE, 'N/A', 'The time when last update took place.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setReadOnly (true); $setting->setExportable (false); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_TTL_LOG_UPDATE, 14, 'Number of days update logs must be kept.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_HEADER_BIG_TITLE, 'Test value', 'Big title for example.'); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_HEADER_SMALL_TITLE, 'Test value', 'Small title for example.'); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_IS_INTERNAL_LINKS, 1, 'Display internal links without website domain name.'); $setting->setType (Setting_Model::TYPE_CHECKBOX); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_DISCOUNT_PERCENT, 0, 'Discount available to customers.'); $setting->setStatus (Setting_Model::STATUS_HIDDEN); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_WEBAPIPASSWORD, '', 'WebAPI password.'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setType(Setting_Model::TYPE_TEXT_NOTREQUIRED); $setting->setExportable (false); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_INCOMING_TYPE_VISIBILITY, DAL_Catalog::STATE_VISIBLE_EVERYWHERE, 'New type visibility'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setType(Setting_Model::TYPE_TEXT); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_INCOMING_CATEGORY_VISIBILITY, DAL_Catalog::STATE_VISIBLE_EVERYWHERE, 'New category visibility'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setType(Setting_Model::TYPE_TEXT); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_INCOMING_PACKAGE_VISIBILITY, DAL_Catalog::STATE_VISIBLE_EVERYWHERE, 'New package visibility'); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setType(Setting_Model::TYPE_TEXT); $this->saveSetting ($setting); $setting = new Setting (Setting_Model::S_SITE_URL, url::base (), 'Site URL.'); $setting->setType (Setting_Model::TYPE_URL); $setting->setStatus (Setting_Model::STATUS_SYSTEM); $setting->setExportable (false); $this->saveSetting ($setting); } protected function addConfigSetting ($name, $value) { $config = new File (DATADIR . '/config/config.php'); $config->open (File::OPEN_MODE_APPEND); if (is_scalar ($value)) { if (is_numeric ($value)) { $tmp_value = $value; } elseif (is_string ($value)) { $tmp_value = "'" . addcslashes ($value, "'") . "'"; } } $config->writeLine ('$config [\'' . $name . '\'] = ' . $tmp_value . ';'); $config->close (); } private function updateTemplateCountDictionary ($model) { $list = ORM::factory ($model)->find_all (); foreach ($list as $rec) { if (method_exists ($rec, 'updateTemplateCount')) { $rec->updateTemplateCount (); } else { $rec->template_count = $rec->templates->count (); } $rec->save (); } return $this; } private function updateEnabledTemplateCountDictionary ($model) { $model_instance = ORM::factory ($model); if ($model_instance instanceof Catalog_EnabledTemplateCounter) { foreach ($model_instance->find_all () as $record) { $record->updateEnabledTemplateCounter (); { if ($record->visibility == TemplateCategory_Model::STATE_HIDDEN) { if (! $record->is_edited) { $record->visibility = TemplateCategory_Model::STATE_VISIBLE_EVERYWHERE; } } } $record->save (); } } } private function createSystemPages () { ORM::factory ('systempage')->delete_all (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_INDEX; $systempage->html_name = 'Home page'; $systempage->list_name = 'Home'; $systempage->visibility = Page_Model::STATE_VISIBLE_EVERYWHERE; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_CATEGORY; $systempage->html_name = 'Category %CATEGORY%'; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_TYPE; $systempage->html_name = 'Type %TYPE%'; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_SEARCH; $systempage->html_name = 'Search result'; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_PREVIEW; $systempage->html_name = 'Template %TEMPLATE-ID%'; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_NOT_FOUND; $systempage->html_name = 'Resource not found'; $systempage->save (); $systempage = ORM::factory ('systempage'); $systempage->name = Page_Model::SYSTEM_PAGE_PACKAGE; $systempage->html_name = '%PACKAGE%'; $systempage->save (); } private function createConventionalPages () { $userpage = ORM::factory ('conventionalpage'); $userpage->name = 'faq'; $userpage->html_name = 'Frequently asked questions'; $userpage->list_name = 'FAQ'; $userpage->url_name = 'faq'; $userpage->save (); $userpage = ORM::factory ('conventionalpage'); $userpage->name = 'chat'; $userpage->html_name = 'Chat'; $userpage->list_name = 'Chat'; $userpage->url_name = 'chat'; $userpage->redirect_to = 'http://chat.template-help.com/'; $userpage->link_class = Userpage_Model::LINK_REDIRECT; $userpage->target_blank = true; $userpage->save (); $systempage = ORM::factory ('conventionalpage'); $systempage->name = Page_Model::SYSTEM_PAGE_CONTACT; $systempage->html_name = 'Contact us'; $systempage->list_name = 'Contacts'; $systempage->url_name = 'contacts.php'; $systempage->save (); } protected function createTextBlocks () { $this->notice ('Creating standard texts'); ORM::factory ('text')->delete_all (); ORM::factory ('text_content')->delete_all (); $this->createLocalTextBlock ('header'); $this->createLocalTextBlock ('footer'); $this->createLocalTextBlock ('HEAD_SCRIPT'); $this->createLocalTextBlock ('BOTTOM_SCRIPT'); $this->createLocalTextBlock ('PACKAGE_DESCRIPTION'); $this->createLocalTextBlock ('PACKAGE_SHORT_DESCRIPTION'); $this->createGlobalTextBlock ('GLOBAL_HEAD_SCRIPT'); $this->createGlobalTextBlock ('GLOBAL_BOTTOM_SCRIPT'); $this->createGlobalTextBlock ('COPYRIGHT', 'Copyright', 'Copyright © 2009 Company Name. All rights reserved.'); $this->createPageLocalText (Page_Model::SYSTEM_PAGE_NOT_FOUND, 'header', 'Page not found', 'The requested url does not exist on this server.'); $this->createPageLocalText ('faq', 'header', 'FAQ', Page_Model::DUMB_TEXT); } private function createPageLocalText ($page_name, $text_name, $title, $content) { $page = ORM::factory ('page')->where ('name', $page_name)->find (); $text = ORM::factory ('text')->where ('name', $text_name)->find (); if (!($page->isExist () and $text->isExist ())) { throw new Exception ("Invalid context."); } $text_content = ORM::factory ('text_content'); $text_content->text_id = $text->id; $text_content->table_id = $page->id; $text_content->table = Text_content_Model::TABLE_USERPAGE; $text_content->title = $title; $text_content->content = $content; $text_content->save (); } private function createLocalTextBlock ($name) { $block = ORM::factory ('text'); $block->name = $name; $block->type = Text_Model::TYPE_LOCAL; $block->save (); } private function createGlobalTextBlock ($name, $title = null, $content = null) { $block = ORM::factory ('text'); $block->name = $name; $block->type = Text_Model::TYPE_GLOBAL; $block->save (); if (isset ($title)) { if (isset ($content)) { $text_content = ORM::factory ('text_content'); $text_content->text_id = $block->id; $text_content->table_id = 0; $text_content->table = Text_content_Model::TABLE_GLOBAL; $text_content->title = $title; $text_content->content = $content; $text_content->save (); } } } function logger (Zend_Log $logger = null) { if (isset ($logger)) { $this->logger = $logger; } else { return $this->logger; } } function __call ($method, $arguments) { $logger = $this->logger (); $logger_function = array ('emerg', 'alert', 'crit', 'err', 'warn', 'notice', 'info', 'debug'); if (in_array ($method, $logger_function)) { if (isset ($logger)) { return call_user_func_array (array ($logger, $method), $arguments); } } else { throw new Exception ("Invalid access to method `$method`."); } } function setTemplatesToInstall ($templates_to_install) { $this->templates_to_install = preg_grep ('/\d+/', $templates_to_install); } function getTemplatesToInstall () { return $this->templates_to_install; } function isVirtualMenuConstantAvailable() { return (bool) Setting_Model::get (Setting_Model::S_VIRTUAL_TYPE_MENU_EXPORT_FILE); } function updateVirtualTypeMenu() { $file_data = $this->getVirtualMenuFileData(); if(is_array($file_data)) { $this->notice('Updating virtual menu.'); foreach($file_data as $virtual_menu_name => $submenu_types) { $virtual_menu = ORM::factory('virtualmenu')->where('virtualTypeName', $virtual_menu_name)->find(); if($virtual_menu->isExist()) { $this->active_virtual_menu_ids[] = $virtual_menu->id; ORM::factory('submenu')->checkVirtualMenuSubmenus($virtual_menu, $submenu_types); } else { $this->createNewVirtualMenu($virtual_menu_name, $submenu_types); } } ORM::factory('submenu')->deleteNotActiveSubmenu($this->active_virtual_menu_ids, 'menu_id'); ORM::factory('virtualmenu')->updateMenuVisibility($this->active_virtual_menu_ids); } else { $this->notice('Unable read virtual menu data file.'); } } function createNewVirtualMenu ($virtual_menu_name, $submenu_types) { $this->info("New Virtual menu {$virtual_menu_name} was created"); $menu = ORM::factory('virtualmenu'); $page = ORM::factory('userpage')->where('name', $virtual_menu_name)->find(); if (!$page->isExist()) { $menu->userpage->name = $virtual_menu_name; $menu->userpage->link_class = Userpage_Model::LINK_INTERNAL; $menu->userpage->url_name = $this->translateNameToUrl($virtual_menu_name); $menu->userpage->visibility = Userpage_Model::STATE_HIDDEN; $menu->userpage->html_name = $virtual_menu_name; $menu->userpage->list_name = $virtual_menu_name; $menu->userpage->status = Userpage_Model::STATE_HIDDEN; $menu->userpage->layout = Userpage_Model::DEFAULT_VIRTUAL_MENU_LAYOUT; $menu->userpage->target_blank = 0; $menu->userpage->save(); $page_id = $menu->userpage->id; } else { $page_id = $page->id; } $menu->virtualTypeName = $virtual_menu_name; $menu->userpage_id = $page_id; $menu->enable = Virtualmenu_Model::DISABLE_MENU; $menu->save(); $menu_id = $menu->id; $this->active_virtual_menu_ids[] = $menu->id; foreach ($submenu_types as $types) { if (ORM::factory('templatetype')->isTypeExists($types)) { $submenu = ORM::factory('submenu'); $submenu->catalog_name = 'types'; $submenu->aliasid = $types->templatetype_id; $submenu->menu_id = $menu_id; $submenu->sort = 0; $submenu->save(); } } } function translateNameToUrl ($string) { $result = strtolower ($string); $result = preg_replace ('/[^a-z\d]/', '-', $result); $result = preg_replace ('/\-+/', '-', $result); $result = trim ($result, '-'); $result .= '.html'; return $result; } function getVirtualMenuFileData () { $file_path = Setting_Model::get(Setting_Model::S_VIRTUAL_TYPE_MENU_EXPORT_FILE); $file = new File_Directory($file_path); $file_content = $file->getLines(); if (is_array($file_content)) { $content = array(); $garbage = array("\n", "\r", "\0", "\t"); foreach ($file_content as $templatetype_menu) { foreach ($garbage as $symbol) { $templatetype_menu = trim($templatetype_menu, $symbol); } list($templatetype_id, $templatetype_name, $virtualmenu_name) = explode("\t", $templatetype_menu); $type = new stdClass(); $type->templatetype_id = $templatetype_id; $type->templatetype_name = $templatetype_name; $content[$virtualmenu_name][] = $type; } return $content; } return false; } }