/**
  * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
  * link is trimmed of leading and trailing slashes before returning to ensure consistency.
  *
  * @return string
  */
 public static function get_homepage_link()
 {
     if (!self::$cached_homepage_link) {
         // @todo Move to 'homepagefordomain' module
         if (class_exists('HomepageForDomainExtension')) {
             $host = str_replace('www.', null, $_SERVER['HTTP_HOST']);
             $candidates = SiteTree::get()->where(array('"SiteTree"."HomepageForDomain" LIKE ?' => "%{$host}%"));
             if ($candidates) {
                 foreach ($candidates as $candidate) {
                     if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
                         self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
                     }
                 }
             }
         }
         if (!self::$cached_homepage_link) {
             // TODO Move to 'translatable' module
             if (class_exists('Translatable') && SiteTree::has_extension('Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) {
                 self::$cached_homepage_link = $link;
             } else {
                 self::$cached_homepage_link = Config::inst()->get('RootURLController', 'default_homepage_link');
             }
         }
     }
     return self::$cached_homepage_link;
 }
 /**
  * @uses ModelAsController::getNestedController()
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     // Check Translatable dependency
     if (!class_exists('Translatable') || !SiteTree::has_extension('Translatable') && !SiteTree::has_extension('LanguagePrefixTranslatable')) {
         throw new Exception('Dependency error: the LanguagePrefix module expects the Translatable module.');
     }
     $disablePrefixForDefaultLang = Config::inst()->get('prefixconfig', 'disable_prefix_for_default_lang');
     $firstSegment = $request->param('URLSegment');
     if ($firstSegment) {
         $prefixUsed = $this->setLocale($firstSegment);
         $defaultLocale = Translatable::default_locale();
         $isDefaultLocale = $this->locale == $defaultLocale;
         if ($prefixUsed) {
             if ($isDefaultLocale && $disablePrefixForDefaultLang) {
                 $url = substr($request->getURL(true), strlen($firstSegment));
                 return $this->redirect($url, 301);
             } else {
                 $request->shiftAllParams();
                 $request->shift(1);
             }
         } else {
             /*
              *  if no prefix is used but $disablePrefixForDefaultLang
              *  is set, we go on like nothing happened. Otherwise a
              *  404 is generated. @todo: maybe we should redirect
              *  pages that do actually exist, because this is a bit
              *  harsh?
              */
             //if (!$isDefaultLocale || !$disablePrefixForDefaultLang) {
             //	return $this->showPageNotFound();
             //}
         }
     }
     return parent::handleRequest($request, $model);
 }
 public function init()
 {
     // set reading lang
     if (SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) {
         Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
     }
     parent::init();
     Versioned::reading_stage("Stage");
     Requirements::css(CMS_DIR . '/css/screen.css');
     Requirements::customCSS($this->generatePageIconsCss());
     Requirements::combine_files('cmsmain.js', array_merge(array(CMS_DIR . '/javascript/CMSMain.js', CMS_DIR . '/javascript/CMSMain.EditForm.js', CMS_DIR . '/javascript/CMSMain.AddForm.js', CMS_DIR . '/javascript/CMSPageHistoryController.js', CMS_DIR . '/javascript/CMSMain.Tree.js', CMS_DIR . '/javascript/SilverStripeNavigator.js', CMS_DIR . '/javascript/SiteTreeURLSegmentField.js'), Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', true, true)));
     CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
     CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
     // Check legacy actions
     $legacy = $this->config()->enabled_legacy_actions;
     // Delete from live is unnecessary since we have unpublish which does the same thing
     if (in_array('CMSBatchAction_DeleteFromLive', $legacy)) {
         Deprecation::notice('4.0', 'Delete From Live is deprecated. Use Un-publish instead');
         CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
     }
     // Delete action
     if (in_array('CMSBatchAction_Delete', $legacy)) {
         Deprecation::notice('4.0', 'Delete from Stage is deprecated. Use Archive instead.');
         CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
     } else {
         CMSBatchActionHandler::register('archive', 'CMSBatchAction_Archive');
         CMSBatchActionHandler::register('restore', 'CMSBatchAction_Restore');
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws Exception
  * @returns null
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (!Check::fileToUrlMapping()) {
         die('ERROR: Please set a valid path in $_FILE_TO_URL_MAPPING before running the seeder' . PHP_EOL);
     }
     if (\SiteTree::has_extension('SiteTreeLinkTracking')) {
         \SiteTree::remove_extension('SiteTreeLinkTracking');
     }
     // Customer overrides delete to check for admin
     // major hack to enable ADMIN permissions
     // login throws cookie warning, this will hide the error message
     error_reporting(0);
     try {
         if ($admin = \Member::default_admin()) {
             $admin->logIn();
         }
     } catch (\Exception $e) {
     }
     error_reporting(E_ALL);
     $writer = new RecordWriter();
     if ($input->getOption('batch')) {
         $batchSize = intval($input->getOption('size'));
         $writer = new BatchedSeedWriter($batchSize);
     }
     $seeder = new Seeder($writer, new CliOutputFormatter());
     $className = $input->getOption('class');
     $key = $input->getOption('key');
     if ($input->getOption('force')) {
         $seeder->setIgnoreSeeds(true);
     }
     $seeder->seed($className, $key);
     return;
 }
 public function handleBatchAction($request)
 {
     // This method can't be called without ajax.
     if (!$request->isAjax()) {
         $this->parentController->redirectBack();
         return;
     }
     // Protect against CSRF on destructive action
     if (!SecurityToken::inst()->checkRequest($request)) {
         return $this->httpError(400);
     }
     $actions = $this->batchActions();
     $actionClass = $actions[$request->param('BatchAction')]['class'];
     $actionHandler = new $actionClass();
     // Sanitise ID list and query the database for apges
     $ids = preg_split('/ *, */', trim($request->requestVar('csvIDs')));
     foreach ($ids as $k => $v) {
         if (!is_numeric($v)) {
             unset($ids[$k]);
         }
     }
     if ($ids) {
         if (class_exists('Translatable') && SiteTree::has_extension('Translatable')) {
             Translatable::disable_locale_filter();
         }
         $pages = DataObject::get($this->recordClass, sprintf('"%s"."ID" IN (%s)', ClassInfo::baseDataClass($this->recordClass), implode(", ", $ids)));
         if (class_exists('Translatable') && SiteTree::has_extension('Translatable')) {
             Translatable::enable_locale_filter();
         }
         $record_class = $this->recordClass;
         if ($record_class::has_extension('Versioned')) {
             // If we didn't query all the pages, then find the rest on the live site
             if (!$pages || $pages->Count() < sizeof($ids)) {
                 foreach ($ids as $id) {
                     $idsFromLive[$id] = true;
                 }
                 if ($pages) {
                     foreach ($pages as $page) {
                         unset($idsFromLive[$page->ID]);
                     }
                 }
                 $idsFromLive = array_keys($idsFromLive);
                 $sql = sprintf('"%s"."ID" IN (%s)', $this->recordClass, implode(", ", $idsFromLive));
                 $livePages = Versioned::get_by_stage($this->recordClass, 'Live', $sql);
                 if ($pages) {
                     // Can't merge into a DataList, need to condense into an actual list first
                     // (which will retrieve all records as objects, so its an expensive operation)
                     $pages = new ArrayList($pages->toArray());
                     $pages->merge($livePages);
                 } else {
                     $pages = $livePages;
                 }
             }
         }
     } else {
         $pages = new ArrayList();
     }
     return $actionHandler->run($pages);
 }
 /**
  * @private
  * Check if the translatable module is available
  */
 private static function is_translatable_installed()
 {
     if (!class_exists('Translatable')) {
         return false;
     }
     if (!SiteTree::has_extension('Translatable')) {
         return false;
     }
     return true;
 }
 /**
  * @private
  * Check if the translatable module is available
  */
 private static function is_translatable_installed()
 {
     if (!class_exists('Translatable')) {
         return false;
     }
     if (!SiteTree::has_extension('Translatable')) {
         return false;
     }
     // check if the SiteTree table exists. This might not be there when Tests are running
     if (!DB::getConn()->hasTable('SiteTree')) {
         return false;
     }
     return true;
 }
Exemple #8
0
 public function init()
 {
     // set reading lang
     if (SiteTree::has_extension('Translatable') && !$this->request->isAjax()) {
         Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
     }
     parent::init();
     Versioned::reading_stage("Stage");
     Requirements::css(CMS_DIR . '/css/screen.css');
     Requirements::customCSS($this->generatePageIconsCss());
     Requirements::combine_files('cmsmain.js', array_merge(array(CMS_DIR . '/javascript/CMSMain.js', CMS_DIR . '/javascript/CMSMain.EditForm.js', CMS_DIR . '/javascript/CMSMain.AddForm.js', CMS_DIR . '/javascript/CMSPageHistoryController.js', CMS_DIR . '/javascript/CMSMain.Tree.js', CMS_DIR . '/javascript/SilverStripeNavigator.js', CMS_DIR . '/javascript/SiteTreeURLSegmentField.js'), Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', true, true)));
     CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish');
     CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish');
     CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete');
     CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive');
 }
 /**
  *	Apply the current user permissions against the solr query builder.
  *	@param SolrQueryBuilder
  */
 public function updateQueryBuilder($builder)
 {
     // Make sure the extension requirements have been met before enabling the custom search index.
     if (SiteTree::has_extension('SolrIndexable') && SiteTree::has_extension('SiteTreePermissionIndexExtension') && ClassInfo::exists('QueuedJob')) {
         // Define the initial user permissions using the general public access flag.
         $groups = array('anyone');
         // Apply the logged in access flag and listing of groups for the current authenticated user.
         $user = Member::currentUser();
         if ($user) {
             // Don't restrict the search results for an administrator.
             if (Permission::checkMember($user, array('ADMIN', 'SITETREE_VIEW_ALL'))) {
                 return;
             }
             $groups[] = 'logged-in';
             foreach ($user->Groups() as $group) {
                 $groups[] = (string) $group->ID;
             }
         }
         // Apply this permission filter.
         $builder->andWith('Groups_ms', $groups);
     }
 }
 public function getNestedController()
 {
     // Check Translatable dependency
     if (!class_exists('Translatable') || !SiteTree::has_extension('Translatable') && !SiteTree::has_extension('LanguagePrefixTranslatable')) {
         throw new Exception('Dependency error: the LanguagePrefix module expects the Translatable module.');
     }
     // No prefix means we're on root. set the prefix to the default
     if (!($prefix = $this->request->param('Prefix'))) {
         $prefix = LanguagePrefix::get_prefix();
     }
     // No locale means the prefix might be an old URL...
     if (!$this->setLocale($prefix)) {
         $this->Locale = Translatable::default_locale();
         return $this->showPageNotFound();
     } else {
         $URLSegment = $this->request->param('URLSegment');
     }
     // Empty URLSegment? Try and get the homepage for the current locale
     if (empty($URLSegment)) {
         PrefixRootURLController::set_is_at_root();
         // get the homepage from the defaul homepage Translation Group
         $URLSegment = LanguagePrefix::get_homepage_link_by_locale($this->locale);
         // if no homepage is found in the default translation group for this locale
         // use the first page in the tree instead
         if (empty($URLSegment)) {
             //@TODO: make 3.0
             $sitetree = SiteTree::get()->filter(array('ParentID' => '0', 'Locale' => $this->locale))->sort('Sort')->First();
             if ($sitetree) {
                 $URLSegment = $sitetree->URLSegment;
             } else {
                 // last resort
                 $URLSegment = self::$default_homepage_link;
             }
         }
     }
     // We have an URLSegment: find the page with this segment - within the current locale
     // In the original ModelAsController the locale filter is disabled for this query,
     // meaning /nl/englishHomePage/ will be found and be redirected later on
     // to /en/englishHomePage/ where I'd rather have a 404!!
     Translatable::enable_locale_filter();
     // make sure multibyte urls are supported
     $sitetree = DataObject::get_one('SiteTree', sprintf('"SiteTree"."URLSegment" = \'%s\' %s', Convert::raw2sql(rawurlencode($URLSegment)), SiteTree::config()->nested_urls ? 'AND "SiteTree"."ParentID" = 0' : null));
     // As in the original ModelAsController: if no page can be found, check if it
     // has been renamed or relocated - again: within the current locale!!!
     // If the current $URLSegment refers to an 'old page', do a 302 redirect to the
     // current version (this works for bookmarked pages)
     // Note: for this the find_old_page() function needs to be localized as well to
     // find_old_page_localized()
     if (empty($sitetree)) {
         if ($redirect = self::find_old_page_localized($URLSegment)) {
             $params = $this->request->getVars();
             if (isset($params['url'])) {
                 unset($params['url']);
             }
             $this->response = new SS_HTTPResponse();
             $this->response->redirect(Controller::join_links($redirect->Link(Controller::join_links($this->request->param('Action'), $this->request->param('ID'), $this->request->param('OtherID'))), $params ? '?' . http_build_query($params) : null), 301);
             return $this->response;
         }
         // all is now lost!
         return $this->showPageNotFound();
     }
     // This we don't really need anymore...
     // Enforce current locale setting to the loaded SiteTree object
     // if($sitetree->Locale) Translatable::set_current_locale($sitetree->Locale);
     if (isset($_REQUEST['debug'])) {
         Debug::message("Using record #{$sitetree->ID} of type {$sitetree->class} with link {$sitetree->Link()}");
     }
     return self::controller_for($sitetree, $this->request->param('Action'));
 }
 /**
  *	Index the current data object for a particular stage.
  *	@param string
  */
 public function reindex($stage = null)
 {
     // Make sure the current data object is not orphaned.
     if ($this->owner->ParentID > 0) {
         $parent = $this->owner->Parent();
         if (is_null($parent) || $parent === false) {
             return;
         }
     }
     // Make sure the extension requirements have been met before enabling the custom site tree search index,
     // since this may impact performance.
     if (ClassInfo::baseDataClass($this->owner) === 'SiteTree' && SiteTree::has_extension('SiteTreePermissionIndexExtension') && SiteTree::has_extension('SolrSearchPermissionIndexExtension') && ClassInfo::exists('QueuedJob')) {
         // Queue a job to handle the recursive indexing.
         $indexing = new SolrSiteTreePermissionIndexJob($this->owner, $stage);
         singleton('QueuedJobService')->queueJob($indexing);
     } else {
         // When the requirements haven't been met, trigger a normal index.
         $this->searchService->index($this->owner, $stage);
     }
 }
 public function translate(SS_HTTPRequest $request)
 {
     $locales = "";
     if (SiteTree::has_extension("Translatable")) {
         $locales = Translatable::get_allowed_locales();
     } else {
         $locales = array("it_IT");
     }
     $locales_list = new ArrayList();
     foreach ($locales as $key => $value) {
         $obj = new ViewableData();
         $obj->__set("Locale", $value);
         $obj->__set("LocaleName", i18n::get_locale_name($value));
         $obj->__set("Lang", i18n::get_lang_from_locale($value));
         $locales_list->push($obj);
     }
     if ($request->isAjax()) {
         if (isset($_POST["collect"])) {
             foreach ($locales as $value) {
                 $c = new TextCollector($value);
                 $c->run(LanguageAdmin::$modules, true);
             }
             die(_t("SUCCESSFULL_COLLECT", "The text was collected."));
         }
         if (isset($_POST["save"])) {
             $lang_array[$_POST["locale"]] = $_POST[$_POST["locale"]];
             $file = $_POST["file"];
             $yml_file = sfYaml::dump($lang_array);
             if ($fh = fopen($file, "w")) {
                 fwrite($fh, $yml_file);
                 fclose($fh);
                 file_get_contents("http://{$_SERVER['HTTP_HOST']}?flush");
             } else {
                 throw new LogicException("Cannot write language file! Please check permissions of {$langFile}");
             }
             die;
         }
         $files = $this->getFiles();
         if (isset($_POST["loadfiles"])) {
             //  die($this->getYaml($_POST["loadfiles"]));
             $this->customise(array("Translations" => $this->getYaml($_POST["loadfiles"]), "Modules" => $files, "Locales" => $locales_list));
             $content = $this->renderWith('LanguageAdmin_Content');
             return $content;
         } else {
             $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName));
             $content = $this->renderWith('LanguageAdmin_Content');
             return $content;
         }
     } else {
         $files = $this->getFiles();
         $this->customise(array("Modules" => $files, "Translations" => $this->getYaml($files->filter(array('Locale' => $locales_list->first()->Locale))->first()->Path), "Locales" => $locales_list, "CurrentLocale" => $locales_list->first()->LocaleName));
         $content = $this->renderWith($this->getViewer('translate'));
         return $content;
     }
 }
 /**
  * @private
  * Check if the translatable module is available
  * @return bool whether or not the Translatable module is installed
  */
 private static function is_translatable_installed()
 {
     return class_exists('Translatable') && SiteTree::has_extension('Translatable');
 }
 /**
  * Returns an RFC1766 compliant locale string, e.g. 'fr-CA'.
  * Inspects the associated {@link dataRecord} for a {@link SiteTree->Locale} value if present,
  * and falls back to {@link Translatable::get_current_locale()} or {@link i18n::default_locale()},
  * depending if Translatable is enabled.
  *
  * Suitable for insertion into lang= and xml:lang=
  * attributes in HTML or XHTML output.
  *
  * @return string
  */
 public function ContentLocale()
 {
     if ($this->dataRecord && $this->dataRecord->hasExtension('Translatable')) {
         $locale = $this->dataRecord->Locale;
     } elseif (class_exists('Translatable') && SiteTree::has_extension('Translatable')) {
         $locale = Translatable::get_current_locale();
     } else {
         $locale = i18n::get_locale();
     }
     return i18n::convert_rfc1766($locale);
 }
 /**
  * @return boolean
  */
 function IsTranslatableEnabled()
 {
     return SiteTree::has_extension('Translatable');
 }
<?php

define('INPAGE_MODULES_DIR', basename(__DIR__));
CMSMenu::remove_menu_item('ContentModuleMain');
CMSMenu::remove_menu_item('ContentModuleEditController');
CMSMenu::remove_menu_item('ContentModuleSettingsController');
CMSMenu::remove_menu_item('ContentModuleHistoryController');
//CMSMenu::remove_menu_item('CMSPageReportsController');
CMSMenu::remove_menu_item('ContentModuleAddController');
//CMSMenu::remove_menu_item('CMSFileAddController');
LeftAndMain::require_css(INPAGE_MODULES_DIR . '/css/ContentModuleField.css');
if (class_exists('Translatable') && SiteTree::has_extension('Translatable')) {
    Config::inst()->update('ContentModule', 'extensions', array('ContentModuleLanguageExtension'));
    Config::inst()->update('ContentModuleField', 'extensions', array('ContentModuleFieldTranslatableExtension'));
    Config::inst()->update('SiteTree', 'extensions', array('ContentModuleSiteTreeTranslatableExtension'));
    Config::inst()->update('ContentModuleMain', 'extensions', array('ContentModuleMainTranslatableExtension'));
}
 public function providePermissions()
 {
     if (!SiteTree::has_extension('Translatable') || !class_exists('SiteTree')) {
         return false;
     }
     $locales = self::get_allowed_locales();
     // Fall back to any locales used in existing translations (see #4939)
     if (!$locales) {
         $locales = DB::query('SELECT "Locale" FROM "SiteTree" GROUP BY "Locale"')->column();
     }
     $permissions = array();
     if ($locales) {
         foreach ($locales as $locale) {
             $localeName = i18n::get_locale_name($locale);
             $permissions['TRANSLATE_' . $locale] = sprintf(_t('Translatable.TRANSLATEPERMISSION', 'Translate %s', 'Translate pages into a language'), $localeName);
         }
     }
     $permissions['TRANSLATE_ALL'] = _t('Translatable.TRANSLATEALLPERMISSION', 'Translate into all available languages');
     $permissions['VIEW_LANGS'] = _t('Translatable.TRANSLATEVIEWLANGS', 'View language dropdown');
     return $permissions;
 }