Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-11-18 17:07:47 +13:00
parent f874e30ad3
commit a6898417e7
8 changed files with 3866 additions and 3595 deletions

View File

@ -2,30 +2,35 @@
/**
* @package translatable
*/
class TranslatableCMSMainExtension extends Extension {
class TranslatableCMSMainExtension extends Extension
{
private static $allowed_actions = array(
'createtranslation',
);
function init() {
public function init()
{
$req = $this->owner->getRequest();
// Ignore being called on LeftAndMain base class,
// which is the case when requests are first routed through AdminRootController
// as an intermediary rather than the endpoint controller
if(!$this->owner->stat('tree_class')) return;
if (!$this->owner->stat('tree_class')) {
return;
}
// Locale" attribute is either explicitly added by LeftAndMain Javascript logic,
// or implied on a translated record (see {@link Translatable->updateCMSFields()}).
// $Lang serves as a "context" which can be inspected by Translatable - hence it
// has the same name as the database property on Translatable.
$id = $req->param('ID');
if($req->requestVar("Locale")) {
if ($req->requestVar("Locale")) {
$this->owner->Locale = $req->requestVar("Locale");
} else if($id && is_numeric($id)) {
} elseif ($id && is_numeric($id)) {
$record = DataObject::get_by_id($this->owner->stat('tree_class'), $id);
if($record && $record->Locale) $this->owner->Locale = $record->Locale;
if ($record && $record->Locale) {
$this->owner->Locale = $record->Locale;
}
} else {
$this->owner->Locale = Translatable::default_locale();
if ($this->owner->class == 'CMSPagesController') {
@ -33,7 +38,9 @@ class TranslatableCMSMainExtension extends Extension {
// otherwise page editing will cause an extra
// ajax request which looks weird due to multiple "loading"-flashes
$getVars = $req->getVars();
if(isset($getVars['url'])) unset($getVars['url']);
if (isset($getVars['url'])) {
unset($getVars['url']);
}
return $this->owner->redirect(Controller::join_links(
$this->owner->Link(),
$req->param('Action'),
@ -48,7 +55,7 @@ class TranslatableCMSMainExtension extends Extension {
// If a locale is set, it needs to match to the current record
$requestLocale = $req->requestVar("Locale");
$page = $this->owner->currentPage();
if(
if (
$req->httpMethod() == 'GET' // leave form submissions alone
&& $requestLocale
&& $page
@ -57,14 +64,14 @@ class TranslatableCMSMainExtension extends Extension {
&& $req->latestParam('Action') != 'EditorToolbar'
) {
$transPage = $page->getTranslation($requestLocale);
if($transPage) {
if ($transPage) {
Translatable::set_current_locale($transPage->Locale);
return $this->owner->redirect(Controller::join_links(
$this->owner->Link('show'),
$transPage->ID
// ?locale will automatically be added
));
} else if ($this->owner->class != 'CMSPagesController') {
} elseif ($this->owner->class != 'CMSPagesController') {
// If the record is not translated, redirect to pages overview
return $this->owner->redirect(Controller::join_links(
singleton('CMSPagesController')->Link(),
@ -85,29 +92,36 @@ class TranslatableCMSMainExtension extends Extension {
Requirements::css('translatable/css/CMSMain.Translatable.css');
}
function updateEditForm(&$form) {
if($form->getName() == 'RootForm' && SiteConfig::has_extension("Translatable")) {
public function updateEditForm(&$form)
{
if ($form->getName() == 'RootForm' && SiteConfig::has_extension("Translatable")) {
$siteConfig = SiteConfig::current_site_config();
$form->Fields()->push(new HiddenField('Locale','', $siteConfig->Locale));
$form->Fields()->push(new HiddenField('Locale', '', $siteConfig->Locale));
}
}
function updatePageOptions(&$fields) {
public function updatePageOptions(&$fields)
{
$fields->push(new HiddenField("Locale", 'Locale', Translatable::get_current_locale()));
}
/**
* Create a new translation from an existing item, switch to this language and reload the tree.
*/
function createtranslation($data, $form) {
public function createtranslation($data, $form)
{
$request = $this->owner->getRequest();
// Protect against CSRF on destructive action
if(!SecurityToken::inst()->checkRequest($request)) return $this->owner->httpError(400);
if (!SecurityToken::inst()->checkRequest($request)) {
return $this->owner->httpError(400);
}
$langCode = Convert::raw2sql($request->postVar('NewTransLang'));
$record = $this->owner->getRecord($request->postVar('ID'));
if(!$record) return $this->owner->httpError(404);
if (!$record) {
return $this->owner->httpError(404);
}
$this->owner->Locale = $langCode;
Translatable::set_current_locale($langCode);
@ -131,24 +145,34 @@ class TranslatableCMSMainExtension extends Extension {
return $this->owner->redirect($url);
}
function updateLink(&$link) {
public function updateLink(&$link)
{
$locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
if($locale) $link = Controller::join_links($link, '?Locale=' . $locale);
if ($locale) {
$link = Controller::join_links($link, '?Locale=' . $locale);
}
}
function updateLinkWithSearch(&$link) {
public function updateLinkWithSearch(&$link)
{
$locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
if($locale) $link = Controller::join_links($link, '?Locale=' . $locale);
if ($locale) {
$link = Controller::join_links($link, '?Locale=' . $locale);
}
}
function updateExtraTreeTools(&$html) {
public function updateExtraTreeTools(&$html)
{
$locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
$html = $this->LangForm()->forTemplate() . $html;
}
function updateLinkPageAdd(&$link) {
public function updateLinkPageAdd(&$link)
{
$locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
if($locale) $link = Controller::join_links($link, '?Locale=' . $locale);
if ($locale) {
$link = Controller::join_links($link, '?Locale=' . $locale);
}
}
/**
@ -156,9 +180,10 @@ class TranslatableCMSMainExtension extends Extension {
*
* @return Form
*/
function LangForm() {
public function LangForm()
{
$member = Member::currentUser(); //check to see if the current user can switch langs or not
if(Permission::checkMember($member, 'VIEW_LANGS')) {
if (Permission::checkMember($member, 'VIEW_LANGS')) {
$field = new LanguageDropdownField(
'Locale',
_t('CMSMain.LANGUAGEDROPDOWNLABEL', 'Language'),
@ -173,7 +198,7 @@ class TranslatableCMSMainExtension extends Extension {
// so just show a string displaying current language
$field = new LiteralField(
'Locale',
i18n::get_locale_name( Translatable::get_current_locale())
i18n::get_locale_name(Translatable::get_current_locale())
);
}
@ -184,7 +209,7 @@ class TranslatableCMSMainExtension extends Extension {
$field
),
new FieldList(
new FormAction('selectlang', _t('CMSMain_left.GO','Go'))
new FormAction('selectlang', _t('CMSMain_left.GO', 'Go'))
)
);
$form->unsetValidator();
@ -193,7 +218,8 @@ class TranslatableCMSMainExtension extends Extension {
return $form;
}
function selectlang($data, $form) {
public function selectlang($data, $form)
{
return $this->owner;
}
@ -202,7 +228,8 @@ class TranslatableCMSMainExtension extends Extension {
*
* @return boolean
*/
function MultipleLanguages() {
public function MultipleLanguages()
{
$langs = Translatable::get_existing_content_languages('SiteTree');
return (count($langs) > 1);
@ -211,8 +238,8 @@ class TranslatableCMSMainExtension extends Extension {
/**
* @return boolean
*/
function IsTranslatableEnabled() {
public function IsTranslatableEnabled()
{
return SiteTree::has_extension('Translatable');
}
}

View File

@ -1,13 +1,13 @@
<?php
class TranslatableEditorToolbarExtension extends DataExtension {
function updateLinkForm(&$form) {
class TranslatableEditorToolbarExtension extends DataExtension
{
public function updateLinkForm(&$form)
{
$field = new LanguageDropdownField('Language', _t('CMSMain.LANGUAGEDROPDOWNLABEL', 'Language'));
$field->setValue(Translatable::get_current_locale());
$field->setForm($form);
$form->Fields()->insertBefore($field, 'internal');
Requirements::javascript('translatable/javascript/HtmlEditorField.Translatable.js');
}
}

View File

@ -5,8 +5,8 @@
*
* @package translatable
*/
class LanguageDropdownField extends GroupedDropdownField {
class LanguageDropdownField extends GroupedDropdownField
{
private static $allowed_actions = array(
'getLocaleForObject'
);
@ -21,27 +21,33 @@ class LanguageDropdownField extends GroupedDropdownField {
* @param string $list Indicates the source language list.
* Can be either Common-English, Common-Native, Locale-English, Locale-Native
*/
function __construct($name, $title, $excludeLocales = array(),
public function __construct($name, $title, $excludeLocales = array(),
$translatingClass = 'SiteTree', $list = 'Common-English', $instance = null
) {
$usedLocalesWithTitle = Translatable::get_existing_content_languages($translatingClass);
$usedLocalesWithTitle = array_diff_key($usedLocalesWithTitle, $excludeLocales);
if('Common-English' == $list) $allLocalesWithTitle = i18n::get_common_languages();
else if('Common-Native' == $list) $allLocalesWithTitle = i18n::get_common_languages(true);
else if('Locale-English' == $list) $allLocalesWithTitle = i18n::get_common_locales();
else if('Locale-Native' == $list) $allLocalesWithTitle = i18n::get_common_locales(true);
else $allLocalesWithTitle = i18n::config()->all_locales;
if ('Common-English' == $list) {
$allLocalesWithTitle = i18n::get_common_languages();
} elseif ('Common-Native' == $list) {
$allLocalesWithTitle = i18n::get_common_languages(true);
} elseif ('Locale-English' == $list) {
$allLocalesWithTitle = i18n::get_common_locales();
} elseif ('Locale-Native' == $list) {
$allLocalesWithTitle = i18n::get_common_locales(true);
} else {
$allLocalesWithTitle = i18n::config()->all_locales;
}
if(isset($allLocales[Translatable::default_locale()])) {
if (isset($allLocales[Translatable::default_locale()])) {
unset($allLocales[Translatable::default_locale()]);
}
// Limit to allowed locales if defined
// Check for canTranslate() if an $instance is given
$allowedLocales = Translatable::get_allowed_locales();
foreach($allLocalesWithTitle as $locale => $localeTitle) {
if(
foreach ($allLocalesWithTitle as $locale => $localeTitle) {
if (
($allowedLocales && !in_array($locale, $allowedLocales))
|| ($excludeLocales && in_array($locale, $excludeLocales))
|| ($usedLocalesWithTitle && array_key_exists($locale, $usedLocalesWithTitle))
@ -50,13 +56,13 @@ class LanguageDropdownField extends GroupedDropdownField {
}
}
// instance specific permissions
foreach($allLocalesWithTitle as $locale => $localeTitle) {
if($instance && !$instance->canTranslate(null, $locale)) {
foreach ($allLocalesWithTitle as $locale => $localeTitle) {
if ($instance && !$instance->canTranslate(null, $locale)) {
unset($allLocalesWithTitle[$locale]);
}
}
foreach($usedLocalesWithTitle as $locale => $localeTitle) {
if($instance && !$instance->canTranslate(null, $locale)) {
foreach ($usedLocalesWithTitle as $locale => $localeTitle) {
if ($instance && !$instance->canTranslate(null, $locale)) {
unset($usedLocalesWithTitle[$locale]);
}
}
@ -64,7 +70,7 @@ class LanguageDropdownField extends GroupedDropdownField {
// Sort by title (array value)
asort($allLocalesWithTitle);
if(count($usedLocalesWithTitle)) {
if (count($usedLocalesWithTitle)) {
asort($usedLocalesWithTitle);
$source = array(
_t('Form.LANGAVAIL', "Available languages") => $usedLocalesWithTitle,
@ -77,11 +83,13 @@ class LanguageDropdownField extends GroupedDropdownField {
parent::__construct($name, $title, $source);
}
function Type() {
public function Type()
{
return 'languagedropdown dropdown';
}
public function getAttributes() {
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array('data-locale-url' => $this->Link('getLocaleForObject'))
@ -93,7 +101,8 @@ class LanguageDropdownField extends GroupedDropdownField {
*
* @return locale
*/
function getLocaleForObject() {
public function getLocaleForObject()
{
$id = (int)$this->getRequest()->requestVar('id');
$class = Convert::raw2sql($this->getRequest()->requestVar('class'));
$locale = Translatable::get_current_locale();
@ -108,5 +117,4 @@ class LanguageDropdownField extends GroupedDropdownField {
}
return $locale;
}
}

View File

@ -151,8 +151,8 @@
*
* @package translatable
*/
class Translatable extends DataExtension implements PermissionProvider {
class Translatable extends DataExtension implements PermissionProvider
{
const QUERY_LOCALE_FILTER_ENABLED = 'Translatable.LocaleFilterEnabled';
/**
@ -230,7 +230,8 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* Reset static configuration variables to their default values
*/
static function reset() {
public static function reset()
{
self::enable_locale_filter();
self::$default_locale = 'en_US';
self::$current_locale = null;
@ -249,12 +250,13 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param $langsAvailable array A numerical array of languages which are valid choices (optional)
* @return string Selected language (also saved in $current_locale).
*/
static function choose_site_locale($langsAvailable = array()) {
if(self::$current_locale) {
public static function choose_site_locale($langsAvailable = array())
{
if (self::$current_locale) {
return self::$current_locale;
}
if(
if (
(isset($_REQUEST['locale']) && !$langsAvailable)
|| (isset($_REQUEST['locale'])
&& in_array($_REQUEST['locale'], $langsAvailable))
@ -275,7 +277,8 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return string
*/
static function default_locale() {
public static function default_locale()
{
return self::$default_locale;
}
@ -286,13 +289,14 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @param $locale String
*/
static function set_default_locale($locale) {
if($locale && !i18n::validate_locale($locale)) {
public static function set_default_locale($locale)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
$localeList = i18n::config()->all_locales;
if(isset($localeList[$locale])) {
if (isset($localeList[$locale])) {
self::$default_locale = $locale;
} else {
user_error(
@ -308,7 +312,8 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return string
*/
static function get_current_locale() {
public static function get_current_locale()
{
return (self::$current_locale) ? self::$current_locale : self::choose_site_locale();
}
@ -320,8 +325,9 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @param string $lang New reading language.
*/
static function set_current_locale($locale) {
if($locale && !i18n::validate_locale($locale)) {
public static function set_current_locale($locale)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
@ -337,8 +343,9 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $orderby A sort expression to be inserted into the ORDER BY clause.
* @return DataObject
*/
static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "") {
if($locale && !i18n::validate_locale($locale)) {
public static function get_one_by_locale($class, $locale, $filter = '', $cache = false, $orderby = "")
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
@ -367,18 +374,27 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $having A filter to be inserted into the HAVING clause.
* @return mixed The objects matching the conditions.
*/
static function get_by_locale($class, $locale, $filter = '', $sort = '', $join = "", $limit = "") {
if($locale && !i18n::validate_locale($locale)) {
public static function get_by_locale($class, $locale, $filter = '', $sort = '', $join = "", $limit = "")
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
$oldLang = self::get_current_locale();
self::set_current_locale($locale);
$result = $class::get();
if($filter) $result = $result->where($filter);
if($sort) $result = $result->sort($sort);
if($join) $result = $result->leftJoin($join);
if($limit) $result = $result->limit($limit);
if ($filter) {
$result = $result->where($filter);
}
if ($sort) {
$result = $result->sort($sort);
}
if ($join) {
$result = $result->leftJoin($join);
}
if ($limit) {
$result = $result->limit($limit);
}
self::set_current_locale($oldLang);
return $result;
@ -387,7 +403,8 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* @return bool
*/
public static function locale_filter_enabled() {
public static function locale_filter_enabled()
{
return self::$locale_filter_enabled;
}
@ -397,7 +414,8 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @param $enabled (default true), if false this call is a no-op - see {@link disable_locale_filter()}
*/
public static function enable_locale_filter($enabled = true) {
public static function enable_locale_filter($enabled = true)
{
if ($enabled) {
self::$locale_filter_enabled = true;
}
@ -425,7 +443,8 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return boolean true if the locale filter was enabled, false if it was not
*/
public static function disable_locale_filter() {
public static function disable_locale_filter()
{
$enabled = self::$locale_filter_enabled;
self::$locale_filter_enabled = false;
return $enabled;
@ -437,17 +456,18 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return array Numeric array of all locales, sorted alphabetically.
*/
function getTranslatedLocales() {
public function getTranslatedLocales()
{
$langs = array();
$baseDataClass = ClassInfo::baseDataClass($this->owner->class); //Base Class
$translationGroupClass = $baseDataClass . "_translationgroups";
if($this->owner->hasExtension("Versioned") && Versioned::current_stage() == "Live") {
if ($this->owner->hasExtension("Versioned") && Versioned::current_stage() == "Live") {
$baseDataClass = $baseDataClass . "_Live";
}
$translationGroupID = $this->getTranslationGroup();
if(is_numeric($translationGroupID)) {
if (is_numeric($translationGroupID)) {
$query = new SQLSelect(
'DISTINCT "Locale"',
sprintf(
@ -467,7 +487,7 @@ class Translatable extends DataExtension implements PermissionProvider {
);
$langs = $query->execute()->column();
}
if($langs) {
if ($langs) {
$langCodes = array_values($langs);
sort($langCodes);
return $langCodes;
@ -487,11 +507,18 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param Member $member
* @return array Map of locales
*/
function getAllowedLocalesForMember($member) {
public function getAllowedLocalesForMember($member)
{
$locales = self::get_allowed_locales();
if(!$locales) $locales = i18n::get_common_locales();
if($locales) foreach($locales as $k => $locale) {
if(!$this->canTranslate($member, $locale)) unset($locales[$k]);
if (!$locales) {
$locales = i18n::get_common_locales();
}
if ($locales) {
foreach ($locales as $k => $locale) {
if (!$this->canTranslate($member, $locale)) {
unset($locales[$k]);
}
}
}
return $locales;
@ -506,7 +533,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param int $id ID of the element
* @return array List of languages
*/
static function get_langs_by_id($class, $id) {
public static function get_langs_by_id($class, $id)
{
$do = DataObject::get_by_id($class, $id);
return ($do ? $do->getTranslatedLocales() : array());
}
@ -516,8 +544,11 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @deprecated 2.4 Use SiteTree::add_extension('Translatable')
*/
static function enable() {
if(class_exists('SiteTree')) SiteTree::add_extension('Translatable');
public static function enable()
{
if (class_exists('SiteTree')) {
SiteTree::add_extension('Translatable');
}
}
/**
@ -525,8 +556,11 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @deprecated 2.4 Use SiteTree::remove_extension('Translatable')
*/
static function disable() {
if(class_exists('SiteTree')) SiteTree::remove_extension('Translatable');
public static function disable()
{
if (class_exists('SiteTree')) {
SiteTree::remove_extension('Translatable');
}
}
/**
@ -535,10 +569,11 @@ class Translatable extends DataExtension implements PermissionProvider {
* @deprecated 2.4 Use SiteTree::has_extension('Translatable')
* @return boolean True if enabled
*/
static function is_enabled() {
if(class_exists('SiteTree')){
public static function is_enabled()
{
if (class_exists('SiteTree')) {
return SiteTree::has_extension('Translatable');
}else{
} else {
return false;
}
}
@ -549,7 +584,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* @var array $translatableFields The different fields of the object that can be translated.
* This is currently not implemented, all fields are marked translatable (see {@link setOwner()}).
*/
function __construct($translatableFields = null) {
public function __construct($translatableFields = null)
{
parent::__construct();
// @todo Disabled selection of translatable fields - we're setting all fields as
@ -566,14 +602,14 @@ class Translatable extends DataExtension implements PermissionProvider {
// Has to be executed even with Translatable disabled, as it overwrites the method with same name
// on Hierarchy class, and routes through to Hierarchy->doAllChildrenIncludingDeleted() instead.
// Caution: There's an additional method for augmentAllChildrenIncludingDeleted()
}
function setOwner($owner, $ownerBaseClass = null) {
public function setOwner($owner, $ownerBaseClass = null)
{
parent::setOwner($owner, $ownerBaseClass);
// setting translatable fields by inspecting owner - this should really be done in the constructor
if($this->owner && $this->translatableFields === null) {
if ($this->owner && $this->translatableFields === null) {
$this->translatableFields = array_merge(
array_keys($this->owner->db()),
array_keys($this->owner->hasMany()),
@ -585,7 +621,8 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
static function get_extra_config($class, $extensionClass, $args = null) {
public static function get_extra_config($class, $extensionClass, $args = null)
{
$config = array();
$config['defaults'] = array(
"Locale" => Translatable::default_locale() // as an overloaded getter as well: getLang()
@ -603,21 +640,24 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param SQLSelect $query
* @return boolean
*/
protected function filtersOnLocale($query) {
foreach($query->getWhere() as $condition) {
protected function filtersOnLocale($query)
{
foreach ($query->getWhere() as $condition) {
// Compat for 3.1/3.2 where syntax
if(is_array($condition)) {
if (is_array($condition)) {
// In >=3.2 each $condition is a single length array('condition' => array('params'))
reset($condition);
$condition = key($condition);
}
// >=3.2 allows conditions to be expressed as evaluatable objects
if(interface_exists('SQLConditionGroup') && ($condition instanceof SQLConditionGroup)) {
if (interface_exists('SQLConditionGroup') && ($condition instanceof SQLConditionGroup)) {
$condition = $condition->conditionSQL($params);
}
if(preg_match('/("|\'|`)Locale("|\'|`)/', $condition)) return true;
if (preg_match('/("|\'|`)Locale("|\'|`)/', $condition)) {
return true;
}
}
}
@ -629,18 +669,19 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* Use {@link disable_locale_filter()} to temporarily disable this "auto-filtering".
*/
function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) {
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
// If the record is saved (and not a singleton), and has a locale,
// limit the current call to its locale. This fixes a lot of problems
// with other extensions like Versioned
if($this->owner->ID && !empty($this->owner->Locale)) {
if ($this->owner->ID && !empty($this->owner->Locale)) {
$locale = $this->owner->Locale;
} else {
$locale = Translatable::get_current_locale();
}
$baseTable = ClassInfo::baseDataClass($this->owner->class);
if(
if (
$locale
// unless the filter has been temporarily disabled
&& self::locale_filter_enabled()
@ -655,19 +696,22 @@ class Translatable extends DataExtension implements PermissionProvider {
) {
// Or we're already filtering by Lang (either from an earlier augmentSQL()
// call or through custom SQL filters)
$filtersOnLocale = array_filter($query->getWhere(), function($predicates) {
foreach($predicates as $predicate => $params) {
if(preg_match('/("|\'|`)Locale("|\'|`)/', $predicate)) return true;
$filtersOnLocale = array_filter($query->getWhere(), function ($predicates) {
foreach ($predicates as $predicate => $params) {
if (preg_match('/("|\'|`)Locale("|\'|`)/', $predicate)) {
return true;
}
}
});
if(!$filtersOnLocale) {
if (!$filtersOnLocale) {
$qry = sprintf('"%s"."Locale" = \'%s\'', $baseTable, Convert::raw2sql($locale));
$query->addWhere($qry);
}
}
}
function augmentDataQueryCreation(SQLSelect $sqlQuery, DataQuery $dataQuery) {
public function augmentDataQueryCreation(SQLSelect $sqlQuery, DataQuery $dataQuery)
{
$enabled = self::locale_filter_enabled();
$dataQuery->setQueryParam(self::QUERY_LOCALE_FILTER_ENABLED, $enabled);
}
@ -678,9 +722,12 @@ class Translatable extends DataExtension implements PermissionProvider {
* translation of an object acts as a sibling, rather than
* a parent->child relation.
*/
function augmentDatabase() {
public function augmentDatabase()
{
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
if($this->owner->class != $baseDataClass) return;
if ($this->owner->class != $baseDataClass) {
return;
}
$fields = array(
'OriginalID' => 'Int',
@ -696,7 +743,7 @@ class Translatable extends DataExtension implements PermissionProvider {
// Remove 2.2 style tables
DB::dontRequireTable("{$baseDataClass}_lang");
if($this->owner->hasExtension('Versioned')) {
if ($this->owner->hasExtension('Versioned')) {
DB::dontRequireTable("{$baseDataClass}_lang_Live");
DB::dontRequireTable("{$baseDataClass}_lang_versions");
}
@ -705,9 +752,12 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* @todo Find more appropriate place to hook into database building
*/
public function requireDefaultRecords() {
public function requireDefaultRecords()
{
// @todo This relies on the Locale attribute being on the base data class, and not any subclasses
if($this->owner->class != ClassInfo::baseDataClass($this->owner->class)) return false;
if ($this->owner->class != ClassInfo::baseDataClass($this->owner->class)) {
return false;
}
// Permissions: If a group doesn't have any specific TRANSLATE_<locale> edit rights,
// but has CMS_ACCESS_CMSMain (general CMS access), then assign TRANSLATE_ALL permissions as a default.
@ -719,14 +769,20 @@ class Translatable extends DataExtension implements PermissionProvider {
'CMS_ACCESS_LeftAndMain',
'ADMIN'
));
if($groups) foreach($groups as $group) {
if ($groups) {
foreach ($groups as $group) {
$codes = $group->Permissions()->column('Code');
$hasTranslationCode = false;
foreach($codes as $code) {
if(preg_match('/^TRANSLATE_/', $code)) $hasTranslationCode = true;
foreach ($codes as $code) {
if (preg_match('/^TRANSLATE_/', $code)) {
$hasTranslationCode = true;
}
}
// Only add the code if no more restrictive code exists
if(!$hasTranslationCode) Permission::grant($group->ID, 'TRANSLATE_ALL');
if (!$hasTranslationCode) {
Permission::grant($group->ID, 'TRANSLATE_ALL');
}
}
}
// If the Translatable extension was added after the first records were already
@ -736,17 +792,21 @@ class Translatable extends DataExtension implements PermissionProvider {
'SELECT "ID" FROM "%s" WHERE "Locale" IS NULL OR "Locale" = \'\'',
ClassInfo::baseDataClass($this->owner->class)
))->column();
if(!$idsWithoutLocale) return;
if (!$idsWithoutLocale) {
return;
}
if(class_exists('SiteTree') && $this->owner->class == 'SiteTree') {
foreach(array('Stage', 'Live') as $stage) {
foreach($idsWithoutLocale as $id) {
if (class_exists('SiteTree') && $this->owner->class == 'SiteTree') {
foreach (array('Stage', 'Live') as $stage) {
foreach ($idsWithoutLocale as $id) {
$obj = Versioned::get_one_by_stage(
$this->owner->class,
$stage,
sprintf('"SiteTree"."ID" = %d', $id)
);
if(!$obj || $obj->ObsoleteClassName) continue;
if (!$obj || $obj->ObsoleteClassName) {
continue;
}
$obj->Locale = Translatable::default_locale();
@ -761,9 +821,11 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
} else {
foreach($idsWithoutLocale as $id) {
foreach ($idsWithoutLocale as $id) {
$obj = DataObject::get_by_id($this->owner->class, $id);
if(!$obj || $obj->ObsoleteClassName) continue;
if (!$obj || $obj->ObsoleteClassName) {
continue;
}
$obj->Locale = Translatable::default_locale();
$obj->write();
@ -773,7 +835,7 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
DB::alteration_message(sprintf(
"Added default locale '%s' to table %s","changed",
"Added default locale '%s' to table %s", "changed",
Translatable::default_locale(),
$this->owner->class
));
@ -789,14 +851,17 @@ class Translatable extends DataExtension implements PermissionProvider {
* or the primary key of this record, to create a new translation group
* @param boolean $overwrite
*/
public function addTranslationGroup($originalID, $overwrite = false) {
if(!$this->owner->exists()) return false;
public function addTranslationGroup($originalID, $overwrite = false)
{
if (!$this->owner->exists()) {
return false;
}
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
$existingGroupID = $this->getTranslationGroup($originalID);
// Remove any existing groups if overwrite flag is set
if($existingGroupID && $overwrite) {
if ($existingGroupID && $overwrite) {
$sql = sprintf(
'DELETE FROM "%s_translationgroups" WHERE "TranslationGroupID" = %d AND "OriginalID" = %d',
$baseDataClass,
@ -808,7 +873,7 @@ class Translatable extends DataExtension implements PermissionProvider {
}
// Add to group (only if not in existing group or $overwrite flag is set)
if(!$existingGroupID) {
if (!$existingGroupID) {
$sql = sprintf(
'INSERT INTO "%s_translationgroups" ("TranslationGroupID","OriginalID") VALUES (%d,%d)',
$baseDataClass,
@ -826,8 +891,11 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return int Numeric ID of the translationgroup in the <classname>_translationgroup table
*/
public function getTranslationGroup() {
if(!$this->owner->exists()) return false;
public function getTranslationGroup()
{
if (!$this->owner->exists()) {
return false;
}
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
return DB::query(
@ -845,7 +913,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* if this happens to be the last record assigned to the group,
* this group ceases to exist.
*/
public function removeTranslationGroup() {
public function removeTranslationGroup()
{
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
DB::query(
sprintf('DELETE FROM "%s_translationgroups" WHERE "OriginalID" = %d', $baseDataClass, $this->owner->ID)
@ -859,7 +928,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $table Table name
* @return boolean
*/
function isVersionedTable($table) {
public function isVersionedTable($table)
{
return false;
}
@ -867,15 +937,18 @@ class Translatable extends DataExtension implements PermissionProvider {
* Note: The bulk of logic is in ModelAsController->getNestedController()
* and ContentController->handleRequest()
*/
function contentcontrollerInit($controller) {
public function contentcontrollerInit($controller)
{
$controller->Locale = Translatable::choose_site_locale();
}
function modelascontrollerInit($controller) {
public function modelascontrollerInit($controller)
{
//$this->contentcontrollerInit($controller);
}
function initgetEditForm($controller) {
public function initgetEditForm($controller)
{
$this->contentcontrollerInit($controller);
}
@ -890,13 +963,14 @@ class Translatable extends DataExtension implements PermissionProvider {
* a unique URL across languages, by means of {@link SiteTree::get_by_link()}
* and {@link Translatable->alternateGetByURL()}.
*/
function onBeforeWrite() {
public function onBeforeWrite()
{
// If language is not set explicitly, set it to current_locale.
// This might be a bit overzealous in assuming the language
// of the content, as a "single language" website might be expanded
// later on. See {@link requireDefaultRecords()} for batch setting
// of empty Locale columns on each dev/build call.
if(!$this->owner->Locale) {
if (!$this->owner->Locale) {
$this->owner->Locale = Translatable::get_current_locale();
}
@ -906,12 +980,12 @@ class Translatable extends DataExtension implements PermissionProvider {
// Caution: This logic is very sensitve to infinite loops when translation status isn't determined properly
// If a parent for the newly written translation was existing before this
// onBeforeWrite() call, it will already have been linked correctly through createTranslation()
if(
if (
class_exists('SiteTree')
&& $this->owner->hasField('ParentID')
&& $this->owner instanceof SiteTree
) {
if(
if (
!$this->owner->ID
&& $this->owner->ParentID
&& !$this->owner->Parent()->hasTranslation($this->owner->Locale)
@ -923,7 +997,7 @@ class Translatable extends DataExtension implements PermissionProvider {
// Has to be limited to the default locale, the assumption is that the "page type"
// dropdown is readonly on all translations.
if($this->owner->ID && $this->owner->Locale == Translatable::default_locale()) {
if ($this->owner->ID && $this->owner->Locale == Translatable::default_locale()) {
$changedFields = $this->owner->getChangedFields();
$changed = isset($changedFields['ClassName']);
@ -951,11 +1025,12 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
if($changed) {
if ($changed) {
$this->owner->ClassName = $changedFields['ClassName']['before'];
$translations = $this->owner->getTranslations();
$this->owner->ClassName = $changedFields['ClassName']['after'];
if($translations) foreach($translations as $translation) {
if ($translations) {
foreach ($translations as $translation) {
$translation->setClassName($this->owner->ClassName);
$translation = $translation->newClassInstance($translation->ClassName);
$translation->populateDefaults();
@ -964,22 +1039,24 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
}
}
// see onAfterWrite()
if(!$this->owner->ID) {
if (!$this->owner->ID) {
$this->owner->_TranslatableIsNewRecord = true;
}
}
function onAfterWrite() {
public function onAfterWrite()
{
// hacky way to determine if the record was created in the database,
// or just updated
if($this->owner->_TranslatableIsNewRecord) {
if ($this->owner->_TranslatableIsNewRecord) {
// this would kick in for all new records which are NOT
// created through createTranslation(), meaning they don't
// have the translation group automatically set.
$translationGroupID = $this->getTranslationGroup();
if(!$translationGroupID) {
if (!$translationGroupID) {
$this->addTranslationGroup(
$this->owner->_TranslationGroupID ? $this->owner->_TranslationGroupID : $this->owner->ID
);
@ -987,19 +1064,19 @@ class Translatable extends DataExtension implements PermissionProvider {
unset($this->owner->_TranslatableIsNewRecord);
unset($this->owner->_TranslationGroupID);
}
}
/**
* Remove the record from the translation group mapping.
*/
function onBeforeDelete() {
public function onBeforeDelete()
{
// @todo Coupling to Versioned, we need to avoid removing
// translation groups if records are just deleted from a stage
// (="unpublished"). Ideally the translation group tables would
// be specific to different Versioned changes, making this restriction unnecessary.
// This will produce orphaned translation group records for SiteTree subclasses.
if(!$this->owner->hasExtension('Versioned')) {
if (!$this->owner->hasExtension('Versioned')) {
$this->removeTranslationGroup();
}
@ -1013,7 +1090,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param int|null $parentID
* @return SiteTree
*/
public function alternateGetByLink($URLSegment, $parentID) {
public function alternateGetByLink($URLSegment, $parentID)
{
// If the parentID value has come from a translated page,
// then we need to find the corresponding parentID value
// in the default Locale.
@ -1028,7 +1106,7 @@ class Translatable extends DataExtension implements PermissionProvider {
// Find the locale language-independent of the page
self::disable_locale_filter();
$default = SiteTree::get()->where(sprintf (
$default = SiteTree::get()->where(sprintf(
'"URLSegment" = \'%s\'%s',
Convert::raw2sql($URLSegment),
(is_int($parentID) ? " AND \"ParentID\" = $parentID" : null)
@ -1040,7 +1118,8 @@ class Translatable extends DataExtension implements PermissionProvider {
//-----------------------------------------------------------------------------------------------//
function applyTranslatableFieldsUpdate($fields, $type) {
public function applyTranslatableFieldsUpdate($fields, $type)
{
if (method_exists($this, $type)) {
$this->$type($fields);
} else {
@ -1066,7 +1145,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* readonly fields, so you can translation INTO the "default language" while
* seeing readonly fields as well.
*/
function updateCMSFields(FieldList $fields) {
public function updateCMSFields(FieldList $fields)
{
$this->addTranslatableFields($fields);
// Show a dropdown to create a new translation.
@ -1078,14 +1158,14 @@ class Translatable extends DataExtension implements PermissionProvider {
// Check if fields exist already to avoid adding them twice on repeat invocations
$tab = $fields->findOrMakeTab('Root.Translations', _t('Translatable.TRANSLATIONS', 'Translations'));
if(!$tab->fieldByName('CreateTransHeader')) {
if (!$tab->fieldByName('CreateTransHeader')) {
$tab->push(new HeaderField(
'CreateTransHeader',
_t('Translatable.CREATE', 'Create new translation'),
2
));
}
if(!$tab->fieldByName('NewTransLang') && !$tab->fieldByName('AllTransCreated')) {
if (!$tab->fieldByName('NewTransLang') && !$tab->fieldByName('AllTransCreated')) {
$langDropdown = LanguageDropdownField::create(
"NewTransLang",
_t('Translatable.NEWLANGUAGE', 'New language'),
@ -1097,7 +1177,7 @@ class Translatable extends DataExtension implements PermissionProvider {
$tab->push($langDropdown);
$canAddLocale = (count($langDropdown->getSource()) > 0);
if($canAddLocale) {
if ($canAddLocale) {
// Only add create button if new languages are available
$tab->push(
$createButton = InlineFormAction::create(
@ -1114,8 +1194,8 @@ class Translatable extends DataExtension implements PermissionProvider {
));
}
}
if($alreadyTranslatedLocales) {
if(!$tab->fieldByName('ExistingTransHeader')) {
if ($alreadyTranslatedLocales) {
if (!$tab->fieldByName('ExistingTransHeader')) {
$tab->push(new HeaderField(
'ExistingTransHeader',
_t('Translatable.EXISTING', 'Existing translations'),
@ -1144,14 +1224,16 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
function updateSettingsFields(&$fields) {
public function updateSettingsFields(&$fields)
{
$this->addTranslatableFields($fields);
}
public function updateRelativeLink(&$base, &$action) {
public function updateRelativeLink(&$base, &$action)
{
// Prevent home pages for non-default locales having their urlsegments
// reduced to the site root.
if($base === null && $this->owner->Locale != self::default_locale()){
if ($base === null && $this->owner->Locale != self::default_locale()) {
$base = $this->owner->URLSegment;
}
}
@ -1160,19 +1242,26 @@ class Translatable extends DataExtension implements PermissionProvider {
* This method can be called multiple times on the same FieldList
* because it checks which fields have already been added or modified.
*/
protected function addTranslatableFields(&$fields) {
protected function addTranslatableFields(&$fields)
{
// used in LeftAndMain->init() to set language state when reading/writing record
$fields->push(new HiddenField("Locale", "Locale", $this->owner->Locale));
// Don't apply these modifications for normal DataObjects - they rely on CMSMain logic
if(!class_exists('SiteTree')) return;
if(!($this->owner instanceof SiteTree)) return;
if (!class_exists('SiteTree')) {
return;
}
if (!($this->owner instanceof SiteTree)) {
return;
}
// Don't allow translation of virtual pages because of data inconsistencies (see #5000)
if(class_exists('VirtualPage')){
if (class_exists('VirtualPage')) {
$excludedPageTypes = array('VirtualPage');
foreach($excludedPageTypes as $excludedPageType) {
if(is_a($this->owner, $excludedPageType)) return;
foreach ($excludedPageTypes as $excludedPageType) {
if (is_a($this->owner, $excludedPageType)) {
return;
}
}
}
@ -1182,19 +1271,21 @@ class Translatable extends DataExtension implements PermissionProvider {
// if a language other than default language is used, we're in "translation mode",
// hence have to modify the original fields
$baseClass = $this->owner->class;
while( ($p = get_parent_class($baseClass)) != "DataObject") $baseClass = $p;
while (($p = get_parent_class($baseClass)) != "DataObject") {
$baseClass = $p;
}
// try to get the record in "default language"
$originalRecord = $this->owner->getTranslation(Translatable::default_locale());
// if no translation in "default language", fall back to first translation
if(!$originalRecord) {
if (!$originalRecord) {
$translations = $this->owner->getTranslations();
$originalRecord = ($translations) ? $translations->First() : null;
}
$isTranslationMode = $this->owner->Locale != Translatable::default_locale();
if($originalRecord && $isTranslationMode) {
if ($originalRecord && $isTranslationMode) {
// Remove parent page dropdown
$fields->removeByName("ParentType");
$fields->removeByName("ParentID");
@ -1206,28 +1297,37 @@ class Translatable extends DataExtension implements PermissionProvider {
// iterate through sequential list of all datafields in fieldset
// (fields are object references, so we can replace them with the translatable CompositeField)
foreach($allDataFields as $dataField) {
foreach ($allDataFields as $dataField) {
// Transformation is a visual helper for CMS authors, so ignore hidden fields
if($dataField instanceof HiddenField) continue;
if ($dataField instanceof HiddenField) {
continue;
}
// Some fields are explicitly excluded from transformation
if(in_array($dataField->getName(), $excludeFields)) continue;
if (in_array($dataField->getName(), $excludeFields)) {
continue;
}
// Readonly field which has been added previously
if(preg_match('/_original$/', $dataField->getName())) continue;
if (preg_match('/_original$/', $dataField->getName())) {
continue;
}
// Field already has been transformed
if(isset($allDataFields[$dataField->getName() . '_original'])) continue;
if (isset($allDataFields[$dataField->getName() . '_original'])) {
continue;
}
// CheckboxField which is already transformed
if(preg_match('/class=\"originalvalue\"/', $dataField->Title())) continue;
if (preg_match('/class=\"originalvalue\"/', $dataField->Title())) {
continue;
}
if(in_array($dataField->getName(), $translatableFieldNames)) {
if (in_array($dataField->getName(), $translatableFieldNames)) {
// if the field is translatable, perform transformation
$fields->replaceField($dataField->getName(), $transformation->transformFormField($dataField));
} elseif(!$dataField->isReadonly()) {
} elseif (!$dataField->isReadonly()) {
// else field shouldn't be editable in translation-mode, make readonly
$fields->replaceField($dataField->getName(), $dataField->performReadonlyTransformation());
}
}
} elseif($this->owner->isNew()) {
} elseif ($this->owner->isNew()) {
$fields->addFieldsToTab(
'Root',
new Tab(_t('Translatable.TRANSLATIONS', 'Translations'),
@ -1247,7 +1347,8 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return array
*/
function getTranslatableFields() {
public function getTranslatableFields()
{
return $this->translatableFields;
}
@ -1255,13 +1356,15 @@ class Translatable extends DataExtension implements PermissionProvider {
* Return the base table - the class that directly extends DataObject.
* @return string
*/
function baseTable($stage = null) {
public function baseTable($stage = null)
{
$tableClasses = ClassInfo::dataClassesFor($this->owner->class);
$baseClass = array_shift($tableClasses);
return (!$stage || $stage == $this->defaultStage) ? $baseClass : $baseClass . "_$stage";
}
function extendWithSuffix($table) {
public function extendWithSuffix($table)
{
return $table;
}
@ -1277,19 +1380,22 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $stage
* @return DataObjectSet
*/
function getTranslations($locale = null, $stage = null) {
if($locale && !i18n::validate_locale($locale)) {
public function getTranslations($locale = null, $stage = null)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
if(!$this->owner->exists()) return new ArrayList();
if (!$this->owner->exists()) {
return new ArrayList();
}
// HACK need to disable language filtering in augmentSQL(),
// as we purposely want to get different language
// also save state of locale-filter, revert to this state at the
// end of this method
$localeFilterEnabled = false;
if(self::locale_filter_enabled()) {
if (self::locale_filter_enabled()) {
self::disable_locale_filter();
$localeFilterEnabled = true;
}
@ -1298,7 +1404,7 @@ class Translatable extends DataExtension implements PermissionProvider {
$baseDataClass = ClassInfo::baseDataClass($this->owner->class);
$filter = sprintf('"%s_translationgroups"."TranslationGroupID" = %d', $baseDataClass, $translationGroupID);
if($locale) {
if ($locale) {
$filter .= sprintf(' AND "%s"."Locale" = \'%s\'', $baseDataClass, Convert::raw2sql($locale));
} else {
// exclude the language of the current owner
@ -1306,15 +1412,19 @@ class Translatable extends DataExtension implements PermissionProvider {
}
$currentStage = Versioned::current_stage();
$joinOnClause = sprintf('"%s_translationgroups"."OriginalID" = "%s"."ID"', $baseDataClass, $baseDataClass);
if($this->owner->hasExtension("Versioned")) {
if($stage) Versioned::reading_stage($stage);
if ($this->owner->hasExtension("Versioned")) {
if ($stage) {
Versioned::reading_stage($stage);
}
$translations = Versioned::get_by_stage(
$baseDataClass,
Versioned::current_stage(),
$filter,
null
)->leftJoin("{$baseDataClass}_translationgroups", $joinOnClause);
if($stage) Versioned::reading_stage($currentStage);
if ($stage) {
Versioned::reading_stage($currentStage);
}
} else {
$class = $this->owner->class;
$translations = $baseDataClass::get()
@ -1323,7 +1433,7 @@ class Translatable extends DataExtension implements PermissionProvider {
}
// only re-enable locale-filter if it was enabled at the beginning of this method
if($localeFilterEnabled) {
if ($localeFilterEnabled) {
self::enable_locale_filter();
}
@ -1338,8 +1448,9 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param String $locale
* @return DataObject Translated object
*/
function getTranslation($locale, $stage = null) {
if($locale && !i18n::validate_locale($locale)) {
public function getTranslation($locale, $stage = null)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
@ -1357,13 +1468,20 @@ class Translatable extends DataExtension implements PermissionProvider {
* This function DOES populate the ID field with the newly created object ID
* @see SiteConfig
*/
protected function populateSiteConfigDefaults() {
protected function populateSiteConfigDefaults()
{
// Work-around for population of defaults during database initialisation.
// When the database is being setup singleton('SiteConfig') is called.
if(!DB::getConn()->hasTable($this->owner->class)) return;
if(!DB::getConn()->hasField($this->owner->class, 'Locale')) return;
if(DB::getConn()->isSchemaUpdating()) return;
if (!DB::getConn()->hasTable($this->owner->class)) {
return;
}
if (!DB::getConn()->hasField($this->owner->class, 'Locale')) {
return;
}
if (DB::getConn()->isSchemaUpdating()) {
return;
}
// Find the best base translation for SiteConfig
$enabled = Translatable::locale_filter_enabled();
@ -1371,13 +1489,15 @@ class Translatable extends DataExtension implements PermissionProvider {
$existingConfig = SiteConfig::get()->filter(array(
'Locale' => Translatable::default_locale()
))->first();
if(!$existingConfig) $existingConfig = SiteConfig::get()->first();
if (!$existingConfig) {
$existingConfig = SiteConfig::get()->first();
}
if ($enabled) {
Translatable::enable_locale_filter();
}
// Stage this SiteConfig and copy into the current object
if(
if (
$existingConfig
// Double-up of SiteConfig in the same locale can be ignored. Often caused by singleton(SiteConfig)
&& !$existingConfig->getTranslation(Translatable::get_current_locale())
@ -1391,7 +1511,7 @@ class Translatable extends DataExtension implements PermissionProvider {
}
// Maintain single translation group for SiteConfig
if($existingConfig) {
if ($existingConfig) {
$this->owner->_TranslationGroupID = $existingConfig->getTranslationGroup();
}
@ -1408,7 +1528,8 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* Hooks into the DataObject::populateDefaults() method
*/
public function populateDefaults() {
public function populateDefaults()
{
if (
empty($this->owner->ID)
&& ($this->owner instanceof SiteConfig)
@ -1435,12 +1556,13 @@ class Translatable extends DataExtension implements PermissionProvider {
* should be saved to the database.
* @return DataObject The translated object
*/
function createTranslation($locale, $saveTranslation = true) {
if($locale && !i18n::validate_locale($locale)) {
public function createTranslation($locale, $saveTranslation = true)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
if(!$this->owner->exists()) {
if (!$this->owner->exists()) {
user_error(
'Translatable::createTranslation(): Please save your record before creating a translation',
E_USER_ERROR
@ -1448,7 +1570,7 @@ class Translatable extends DataExtension implements PermissionProvider {
}
// permission check
if(!$this->owner->canTranslate(null, $locale)) {
if (!$this->owner->canTranslate(null, $locale)) {
throw new Exception(sprintf(
'Creating a new translation in locale "%s" is not allowed for this user',
$locale
@ -1457,7 +1579,9 @@ class Translatable extends DataExtension implements PermissionProvider {
}
$existingTranslation = $this->getTranslation($locale);
if($existingTranslation) return $existingTranslation;
if ($existingTranslation) {
return $existingTranslation;
}
$class = $this->owner->class;
$newTranslation = new $class;
@ -1470,10 +1594,12 @@ class Translatable extends DataExtension implements PermissionProvider {
// their ParentID (and overwrite any existing ParentID relations
// to parents in other language). If no parent translations exist,
// they are automatically created in onBeforeWrite()
if($newTranslation->hasField('ParentID')) {
if ($newTranslation->hasField('ParentID')) {
$origParent = $this->owner->Parent();
$newTranslationParent = $origParent->getTranslation($locale);
if($newTranslationParent) $newTranslation->ParentID = $newTranslationParent->ID;
if ($newTranslationParent) {
$newTranslation->ParentID = $newTranslationParent->ID;
}
}
$newTranslation->ID = 0;
@ -1488,14 +1614,16 @@ class Translatable extends DataExtension implements PermissionProvider {
}
// Only make segment unique if it should be enforced
if(Config::inst()->get('Translatable', 'enforce_global_unique_urls')) {
if (Config::inst()->get('Translatable', 'enforce_global_unique_urls')) {
$newTranslation->URLSegment = $urlSegment . '-' . i18n::convert_rfc1766($locale);
}
// hacky way to set an existing translation group in onAfterWrite()
$translationGroupID = $this->getTranslationGroup();
$newTranslation->_TranslationGroupID = $translationGroupID ? $translationGroupID : $this->owner->ID;
if($saveTranslation) $newTranslation->write();
if ($saveTranslation) {
$newTranslation->write();
}
// run callback on page for translation related hooks
$newTranslation->invokeWithExtensions('onTranslatableCreate', $saveTranslation);
@ -1510,12 +1638,15 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $locale
* @return boolean
*/
function canTranslate($member = null, $locale) {
if($locale && !i18n::validate_locale($locale)) {
public function canTranslate($member = null, $locale)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) $member = Member::currentUser();
if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUser();
}
// check for locale
$allowedLocale = (
@ -1523,16 +1654,24 @@ class Translatable extends DataExtension implements PermissionProvider {
|| in_array($locale, self::get_allowed_locales())
);
if(!$allowedLocale) return false;
if (!$allowedLocale) {
return false;
}
// By default, anyone who can edit a page can edit the default locale
if($locale == self::default_locale()) return true;
if ($locale == self::default_locale()) {
return true;
}
// check for generic translation permission
if(Permission::checkMember($member, 'TRANSLATE_ALL')) return true;
if (Permission::checkMember($member, 'TRANSLATE_ALL')) {
return true;
}
// check for locale specific translate permission
if(!Permission::checkMember($member, 'TRANSLATE_' . $locale)) return false;
if (!Permission::checkMember($member, 'TRANSLATE_' . $locale)) {
return false;
}
return true;
}
@ -1540,8 +1679,11 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* @return boolean
*/
function canEdit($member) {
if(!$this->owner->Locale) return null;
public function canEdit($member)
{
if (!$this->owner->Locale) {
return null;
}
return $this->owner->canTranslate($member, $this->owner->Locale) ? null : false;
}
@ -1553,8 +1695,9 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $locale
* @return boolean
*/
function hasTranslation($locale) {
if($locale && !i18n::validate_locale($locale)) {
public function hasTranslation($locale)
{
if ($locale && !i18n::validate_locale($locale)) {
throw new InvalidArgumentException(sprintf('Invalid locale "%s"', $locale));
}
@ -1564,7 +1707,8 @@ class Translatable extends DataExtension implements PermissionProvider {
);
}
function AllChildrenIncludingDeleted($context = null) {
public function AllChildrenIncludingDeleted($context = null)
{
$children = $this->owner->doAllChildrenIncludingDeleted($context);
return $children;
@ -1580,14 +1724,15 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return string HTML
*/
function MetaTags(&$tags) {
public function MetaTags(&$tags)
{
$template = '<link rel="alternate" type="text/html" title="%s" hreflang="%s" href="%s" />' . "\n";
$translations = $this->owner->getTranslations();
if($translations) {
if ($translations) {
$translations = $translations->toArray();
$translations[] = $this->owner;
foreach($translations as $translation) {
foreach ($translations as $translation) {
$tags .= sprintf($template,
Convert::raw2xml($translation->Title),
i18n::convert_rfc1766($translation->Locale),
@ -1597,18 +1742,22 @@ class Translatable extends DataExtension implements PermissionProvider {
}
}
function providePermissions() {
if(!SiteTree::has_extension('Translatable') || !class_exists('SiteTree')) return false;
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) {
if (!$locales) {
$locales = DB::query('SELECT "Locale" FROM "SiteTree" GROUP BY "Locale"')->column();
}
$permissions = array();
if($locales) foreach($locales as $locale) {
if ($locales) {
foreach ($locales as $locale) {
$localeName = i18n::get_locale_name($locale);
$permissions['TRANSLATE_' . $locale] = sprintf(
_t(
@ -1619,6 +1768,7 @@ class Translatable extends DataExtension implements PermissionProvider {
$localeName
);
}
}
$permissions['TRANSLATE_ALL'] = _t(
'Translatable.TRANSLATEALLPERMISSION',
@ -1640,9 +1790,10 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param string $where Optional SQL WHERE statement
* @return array Map of languages in the form locale => langName
*/
static function get_existing_content_languages($className = 'SiteTree', $where = '') {
public static function get_existing_content_languages($className = 'SiteTree', $where = '')
{
$baseTable = ClassInfo::baseDataClass($className);
$query = new SQLSelect("Distinct \"Locale\"","\"$baseTable\"",$where, '', "\"Locale\"");
$query = new SQLSelect("Distinct \"Locale\"", "\"$baseTable\"", $where, '', "\"Locale\"");
$dbLangs = $query->execute()->column();
$langlist = array_merge((array)Translatable::default_locale(), (array)$dbLangs);
$returnMap = array();
@ -1651,8 +1802,8 @@ class Translatable extends DataExtension implements PermissionProvider {
Config::inst()->get('i18n', 'common_locales')
);
foreach ($langlist as $langCode) {
if($langCode && isset($allCodes[$langCode])) {
if(is_array($allCodes[$langCode])) {
if ($langCode && isset($allCodes[$langCode])) {
if (is_array($allCodes[$langCode])) {
$returnMap[$langCode] = $allCodes[$langCode]['name'];
} else {
$returnMap[$langCode] = $allCodes[$langCode];
@ -1668,15 +1819,18 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return string
*/
public static function get_homepage_link_by_locale($locale) {
public static function get_homepage_link_by_locale($locale)
{
$originalLocale = self::get_current_locale();
self::set_current_locale(self::default_locale());
$original = SiteTree::get_by_link(RootURLController::config()->default_homepage_link);
self::set_current_locale($originalLocale);
if($original) {
if($translation = $original->getTranslation($locale)) return trim($translation->RelativeLink(true), '/');
if ($original) {
if ($translation = $original->getTranslation($locale)) {
return trim($translation->RelativeLink(true), '/');
}
}
}
@ -1684,8 +1838,9 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* @deprecated 2.4 Use {@link Translatable::get_homepage_link_by_locale()}
*/
static function get_homepage_urlsegment_by_locale($locale) {
user_error (
public static function get_homepage_urlsegment_by_locale($locale)
{
user_error(
'Translatable::get_homepage_urlsegment_by_locale() is deprecated, please use get_homepage_link_by_locale()',
E_USER_NOTICE
);
@ -1700,7 +1855,8 @@ class Translatable extends DataExtension implements PermissionProvider {
* @param array List of allowed locale codes (see {@link i18n::$all_locales}).
* Example: array('de_DE','ja_JP')
*/
static function set_allowed_locales($locales) {
public static function set_allowed_locales($locales)
{
self::$allowed_locales = $locales;
}
@ -1711,70 +1867,79 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return array
*/
static function get_allowed_locales() {
public static function get_allowed_locales()
{
return self::$allowed_locales;
}
/**
* @deprecated 2.4 Use get_homepage_urlsegment_by_locale()
*/
static function get_homepage_urlsegment_by_language($locale) {
public static function get_homepage_urlsegment_by_language($locale)
{
return self::get_homepage_urlsegment_by_locale($locale);
}
/**
* @deprecated 2.4 Use custom check: self::$default_locale == self::get_current_locale()
*/
static function is_default_lang() {
public static function is_default_lang()
{
return (self::$default_locale == self::get_current_locale());
}
/**
* @deprecated 2.4 Use set_default_locale()
*/
static function set_default_lang($lang) {
public static function set_default_lang($lang)
{
self::set_default_locale(i18n::get_locale_from_lang($lang));
}
/**
* @deprecated 2.4 Use get_default_locale()
*/
static function get_default_lang() {
public static function get_default_lang()
{
return i18n::get_lang_from_locale(self::default_locale());
}
/**
* @deprecated 2.4 Use get_current_locale()
*/
static function current_lang() {
public static function current_lang()
{
return i18n::get_lang_from_locale(self::get_current_locale());
}
/**
* @deprecated 2.4 Use set_current_locale()
*/
static function set_reading_lang($lang) {
public static function set_reading_lang($lang)
{
self::set_current_locale(i18n::get_locale_from_lang($lang));
}
/**
* @deprecated 2.4 Use get_reading_locale()
*/
static function get_reading_lang() {
public static function get_reading_lang()
{
return i18n::get_lang_from_locale(self::get_reading_locale());
}
/**
* @deprecated 2.4 Use default_locale()
*/
static function default_lang() {
public static function default_lang()
{
return i18n::get_lang_from_locale(self::default_locale());
}
/**
* @deprecated 2.4 Use get_by_locale()
*/
static function get_by_lang($class, $lang, $filter = '', $sort = '',
public static function get_by_lang($class, $lang, $filter = '', $sort = '',
$join = "", $limit = "", $containerClass = "DataObjectSet", $having = ""
) {
return self::get_by_locale(
@ -1786,7 +1951,8 @@ class Translatable extends DataExtension implements PermissionProvider {
/**
* @deprecated 2.4 Use get_one_by_locale()
*/
static function get_one_by_lang($class, $lang, $filter = '', $cache = false, $orderby = "") {
public static function get_one_by_lang($class, $lang, $filter = '', $cache = false, $orderby = "")
{
return self::get_one_by_locale($class, i18n::get_locale_from_lang($lang), $filter, $cache, $orderby);
}
@ -1800,28 +1966,32 @@ class Translatable extends DataExtension implements PermissionProvider {
* @return boolean
* @deprecated 2.4
*/
function isTranslation() {
public function isTranslation()
{
return ($this->owner->Locale && ($this->owner->Locale != Translatable::default_locale()));
}
/**
* @deprecated 2.4 Use choose_site_locale()
*/
static function choose_site_lang($langsAvail=null) {
public static function choose_site_lang($langsAvail=null)
{
return self::choose_site_locale($langsAvail);
}
/**
* @deprecated 2.4 Use getTranslatedLocales()
*/
function getTranslatedLangs() {
public function getTranslatedLangs()
{
return $this->getTranslatedLocales();
}
/**
* Return a piece of text to keep DataObject cache keys appropriately specific
*/
function cacheKeyComponent() {
public function cacheKeyComponent()
{
return 'locale-'.self::get_current_locale();
}
@ -1831,11 +2001,12 @@ class Translatable extends DataExtension implements PermissionProvider {
*
* @return bool
*/
public function augmentValidURLSegment() {
public function augmentValidURLSegment()
{
$reEnableFilter = false;
if(!Config::inst()->get('Translatable', 'enforce_global_unique_urls')) {
if (!Config::inst()->get('Translatable', 'enforce_global_unique_urls')) {
self::enable_locale_filter();
} elseif(self::locale_filter_enabled()) {
} elseif (self::locale_filter_enabled()) {
self::disable_locale_filter();
$reEnableFilter = true;
}
@ -1844,7 +2015,7 @@ class Translatable extends DataExtension implements PermissionProvider {
$parentFilter = null;
if (Config::inst()->get('SiteTree', 'nested_urls')) {
if($this->owner->ParentID) {
if ($this->owner->ParentID) {
$parentFilter = " AND \"SiteTree\".\"ParentID\" = {$this->owner->ParentID}";
} else {
$parentFilter = ' AND "SiteTree"."ParentID" = 0';
@ -1854,12 +2025,13 @@ class Translatable extends DataExtension implements PermissionProvider {
$existingPage = SiteTree::get()
// disable get_one cache, as this otherwise may pick up results from when locale_filter was on
->where("\"URLSegment\" = '{$this->owner->URLSegment}' $IDFilter $parentFilter")->First();
if($reEnableFilter) self::enable_locale_filter();
if ($reEnableFilter) {
self::enable_locale_filter();
}
// By returning TRUE or FALSE, we overrule the base SiteTree->validateURLSegment() logic
return !$existingPage;
}
}
/**
@ -1873,14 +2045,15 @@ class Translatable extends DataExtension implements PermissionProvider {
* @package translatable
* @subpackage misc
*/
class Translatable_Transformation extends FormTransformation {
class Translatable_Transformation extends FormTransformation
{
/**
* @var DataObject
*/
private $original = null;
function __construct(DataObject $original) {
public function __construct(DataObject $original)
{
$this->original = $original;
parent::__construct();
}
@ -1890,11 +2063,13 @@ class Translatable_Transformation extends FormTransformation {
*
* @return DataObject
*/
function getOriginal() {
public function getOriginal()
{
return $this->original;
}
public function transformFormField(FormField $field) {
public function transformFormField(FormField $field)
{
$newfield = $field->performReadOnlyTransformation();
$fn = 'transform' . $field->class;
return $this->hasMethod($fn) ? $this->$fn($newfield, $field) : $this->baseTransform($newfield, $field);
@ -1908,7 +2083,8 @@ class Translatable_Transformation extends FormTransformation {
* @param FormField $originalField The original editable field containing the translated value
* @return CheckboxField The field with a modified label
*/
protected function transformCheckboxField(CheckboxField $nonEditableField, CheckboxField $originalField) {
protected function transformCheckboxField(CheckboxField $nonEditableField, CheckboxField $originalField)
{
$label = $originalField->Title();
$fieldName = $originalField->getName();
$value = ($this->original->$fieldName)
@ -1935,7 +2111,8 @@ class Translatable_Transformation extends FormTransformation {
* @param FormField $originalField The original editable field containing the translated value
* @return \CompositeField The transformed field
*/
protected function baseTransform($nonEditableField, $originalField) {
protected function baseTransform($nonEditableField, $originalField)
{
$fieldname = $originalField->getName();
$nonEditableField_holder = new CompositeField($nonEditableField);
@ -1954,5 +2131,4 @@ class Translatable_Transformation extends FormTransformation {
$nonEditableField_holder->insertBefore($originalField, $fieldname.'_original');
return $nonEditableField_holder;
}
}

View File

@ -35,19 +35,24 @@
*
* @package translatable
*/
class MigrateTranslatableTask extends BuildTask {
class MigrateTranslatableTask extends BuildTask
{
protected $title = "Migrate Translatable Task";
protected $description = "Migrates site translations from SilverStripe 2.1/2.2 to new database structure.";
function init() {
public function init()
{
parent::init();
$canAccess = (Director::isDev() || Director::is_cli() || Permission::check("ADMIN"));
if(!$canAccess) return Security::permissionFailure($this);
if (!$canAccess) {
return Security::permissionFailure($this);
}
}
function run($request) {
public function run($request)
{
$ids = array();
echo "#################################\n";
@ -55,19 +60,23 @@ class MigrateTranslatableTask extends BuildTask {
echo "#################################\n";
$allSiteTreeIDs = DB::query('SELECT "ID" FROM "SiteTree"')->column();
if($allSiteTreeIDs) foreach($allSiteTreeIDs as $id) {
if ($allSiteTreeIDs) {
foreach ($allSiteTreeIDs as $id) {
$original = DataObject::get_by_id('SiteTree', $id);
$existingGroupID = $original->getTranslationGroup();
if(!$existingGroupID) $original->addTranslationGroup($original->ID);
if (!$existingGroupID) {
$original->addTranslationGroup($original->ID);
}
$original->destroy();
unset($original);
}
}
DataObject::flush_and_destroy_cache();
echo sprintf("Created translation groups for %d records\n", count($allSiteTreeIDs));
foreach(array('Stage', 'Live') as $stage) {
foreach (array('Stage', 'Live') as $stage) {
echo "\n\n#################################\n";
echo "# Migrating stage $stage" . "\n";
echo "#################################\n";
@ -79,7 +88,7 @@ class MigrateTranslatableTask extends BuildTask {
$trans = DB::query(sprintf('SELECT * FROM "_obsolete_SiteTree_lang%s"', $suffix));
// Iterate over each translated pages
foreach($trans as $oldtrans) {
foreach ($trans as $oldtrans) {
$newLocale = i18n::get_locale_from_lang($oldtrans['Lang']);
echo sprintf(
@ -98,7 +107,7 @@ class MigrateTranslatableTask extends BuildTask {
'"SiteTree"."ID" = ' . $oldtrans['OriginalLangID']
);
if(!$original) {
if (!$original) {
echo sprintf("Couldn't find original for #%d", $oldtrans['OriginalLangID']);
continue;
}
@ -110,7 +119,7 @@ class MigrateTranslatableTask extends BuildTask {
// Clone the original, and set it up as a translation
$existingTrans = $original->getTranslation($newLocale, $stage);
if($existingTrans) {
if ($existingTrans) {
echo sprintf(
"Found existing new-style translation for #%d. Already merged? Skipping.\n",
$oldtrans['OriginalLangID']
@ -125,19 +134,19 @@ class MigrateTranslatableTask extends BuildTask {
$newtrans->OriginalID = $original->ID;
// we have to "guess" a locale based on the language
$newtrans->Locale = $newLocale;
if($stage == 'Live' && array_key_exists($original->ID, $ids)) {
if ($stage == 'Live' && array_key_exists($original->ID, $ids)) {
$newtrans->ID = $ids[$original->ID];
}
// Look at each class in the ancestry, and see if there is a _lang table for it
foreach(ClassInfo::ancestry($oldtrans['ClassName']) as $classname) {
foreach (ClassInfo::ancestry($oldtrans['ClassName']) as $classname) {
$oldtransitem = false;
// If the class is SiteTree, we already have the DB record,
// else check for the table and get the record
if($classname == 'SiteTree') {
if ($classname == 'SiteTree') {
$oldtransitem = $oldtrans;
} elseif(in_array(strtolower($classname) . '_lang', DB::tableList())) {
} elseif (in_array(strtolower($classname) . '_lang', DB::tableList())) {
$oldtransitem = DB::query(sprintf(
'SELECT * FROM "_obsolete_%s_lang%s" WHERE "OriginalLangID" = %d AND "Lang" = \'%s\'',
$classname,
@ -148,12 +157,13 @@ class MigrateTranslatableTask extends BuildTask {
}
// Copy each translated field into the new translation
if($oldtransitem) foreach($oldtransitem as $key => $value) {
if(!in_array($key, array('ID', 'OriginalLangID'))) {
if ($oldtransitem) {
foreach ($oldtransitem as $key => $value) {
if (!in_array($key, array('ID', 'OriginalLangID'))) {
$newtrans->$key = $value;
}
}
}
}
// Write the new translation to the database
@ -165,7 +175,7 @@ class MigrateTranslatableTask extends BuildTask {
$newtrans->addTranslationGroup($original->getTranslationGroup(), true);
if($stage == 'Stage') {
if ($stage == 'Stage') {
$ids[$original->ID] = $newtrans->ID;
}
}
@ -175,5 +185,3 @@ class MigrateTranslatableTask extends BuildTask {
echo "Done!\n";
}
}
?>

View File

@ -2,8 +2,8 @@
/**
* @package translatable
*/
class TranslatableSearchFormTest extends FunctionalTest {
class TranslatableSearchFormTest extends FunctionalTest
{
protected static $fixture_file = 'translatable/tests/unit/TranslatableSearchFormTest.yml';
protected $mockController;
@ -21,12 +21,16 @@ class TranslatableSearchFormTest extends FunctionalTest {
),
);
function waitUntilIndexingFinished() {
public function waitUntilIndexingFinished()
{
$db = DB::getConn();
if (method_exists($db, 'waitUntilIndexingFinished')) DB::getConn()->waitUntilIndexingFinished();
if (method_exists($db, 'waitUntilIndexingFinished')) {
DB::getConn()->waitUntilIndexingFinished();
}
}
function setUpOnce() {
public function setUpOnce()
{
// HACK Postgres doesn't refresh TSearch indexes when the schema changes after CREATE TABLE
// MySQL will need a different table type
self::kill_temp_db();
@ -36,7 +40,8 @@ class TranslatableSearchFormTest extends FunctionalTest {
parent::setUpOnce();
}
function setUp() {
public function setUp()
{
parent::setUp();
$holderPage = $this->objFromFixture('SiteTree', 'searchformholder');
@ -51,7 +56,8 @@ class TranslatableSearchFormTest extends FunctionalTest {
function testPublishedPagesMatchedByTitleInDefaultLanguage() {
public function testPublishedPagesMatchedByTitleInDefaultLanguage()
{
$sf = new SearchForm($this->mockController, 'SearchForm');
$publishedPage = $this->objFromFixture('SiteTree', 'publishedPage');
@ -96,6 +102,4 @@ class TranslatableSearchFormTest extends FunctionalTest {
'Published pages in another language are found when searching in this language'
);
}
}
?>

View File

@ -2,8 +2,8 @@
/**
* @package translatable
*/
class TranslatableSiteConfigTest extends SapphireTest {
class TranslatableSiteConfigTest extends SapphireTest
{
protected static $fixture_file = 'translatable/tests/unit/TranslatableSiteConfigTest.yml';
protected $requiredExtensions = array(
@ -17,21 +17,24 @@ class TranslatableSiteConfigTest extends SapphireTest {
private $origLocale;
function setUp() {
public function setUp()
{
parent::setUp();
$this->origLocale = Translatable::default_locale();
Translatable::set_default_locale("en_US");
}
function tearDown() {
public function tearDown()
{
Translatable::set_default_locale($this->origLocale);
Translatable::set_current_locale($this->origLocale);
parent::tearDown();
}
function testCurrentCreatesDefaultForLocale() {
public function testCurrentCreatesDefaultForLocale()
{
Translatable::set_current_locale(Translatable::default_locale());
$configEn = SiteConfig::current_site_config();
Translatable::set_current_locale('fr_FR');
@ -48,7 +51,8 @@ class TranslatableSiteConfigTest extends SapphireTest {
);
}
function testCanEditTranslatedRootPages() {
public function testCanEditTranslatedRootPages()
{
$configEn = $this->objFromFixture('SiteConfig', 'en_US');
$configDe = $this->objFromFixture('SiteConfig', 'de_DE');

View File

@ -4,8 +4,8 @@
*
* @package translatable
*/
class TranslatableTest extends FunctionalTest {
class TranslatableTest extends FunctionalTest
{
protected static $fixture_file = 'translatable/tests/unit/TranslatableTest.yml';
protected $extraDataObjects = array(
@ -25,7 +25,8 @@ class TranslatableTest extends FunctionalTest {
protected $autoFollowRedirection = false;
function setUp() {
public function setUp()
{
parent::setUp();
// whenever a translation is created, canTranslate() is checked
@ -36,20 +37,23 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_default_locale("en_US");
}
function tearDown() {
public function tearDown()
{
Translatable::set_default_locale($this->origLocale);
Translatable::set_current_locale($this->origLocale);
parent::tearDown();
}
function assertArrayEqualsAfterSort($expected, $actual, $message = null) {
public function assertArrayEqualsAfterSort($expected, $actual, $message = null)
{
sort($expected);
sort($actual);
return $this->assertEquals($expected, $actual, $message);
}
function testGetOneByLocale() {
public function testGetOneByLocale()
{
Translatable::disable_locale_filter();
$this->assertEquals(
0,
@ -102,7 +106,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::enable_locale_filter();
}
function testLocaleFilteringEnabledAndDisabled() {
public function testLocaleFilteringEnabledAndDisabled()
{
$this->assertTrue(Translatable::locale_filter_enabled());
// get our base page to use for testing
@ -140,7 +145,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertEquals(2, $dataList->count());
}
function testLocaleGetParamRedirectsToTranslation() {
public function testLocaleGetParamRedirectsToTranslation()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$origPage->publish('Stage', 'Live');
$translatedPage = $origPage->createTranslation('de_DE');
@ -164,7 +170,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testTranslationGroups() {
public function testTranslationGroups()
{
// first in french
$frPage = new SiteTree();
$frPage->Locale = 'fr_FR';
@ -179,7 +186,7 @@ class TranslatableTest extends FunctionalTest {
// test french
$this->assertArrayEqualsAfterSort(
array('en_US','es_ES'),
array('en_US', 'es_ES'),
$frPage->getTranslations()->column('Locale')
);
$this->assertNotNull($frPage->getTranslation('en_US'));
@ -226,13 +233,15 @@ class TranslatableTest extends FunctionalTest {
);
}
function assertClass($class, $node) {
public function assertClass($class, $node)
{
$this->assertNotNull($node);
$this->assertEquals($class, $node->ClassName);
$this->assertEquals($class, get_class($node));
}
function testChangingClassOfDefaultLocaleTranslationChangesOthers() {
public function testChangingClassOfDefaultLocaleTranslationChangesOthers()
{
// see https://github.com/silverstripe/silverstripe-translatable/issues/97
// create an English SiteTree
$enST = new SiteTree();
@ -272,7 +281,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testChangingClassOfDefaultLocaleTranslationChangesOthersWhenPublished() {
public function testChangingClassOfDefaultLocaleTranslationChangesOthersWhenPublished()
{
// create an English SiteTree
$enST = new SiteTree();
$enST->Locale = 'en_US';
@ -299,10 +309,10 @@ class TranslatableTest extends FunctionalTest {
// and all of the live versions of translations as well:
$this->assertClass('Page', Versioned::get_one_by_stage('SiteTree', 'Live', '"ID" = ' . $frST->ID));
$this->assertClass('Page', Versioned::get_one_by_stage('SiteTree', 'Live', '"ID" = ' . $esST->ID));
}
function testTranslationGroupsWhenTranslationIsSubclass() {
public function testTranslationGroupsWhenTranslationIsSubclass()
{
// create an English SiteTree
$enST = new SiteTree();
$enST->Locale = 'en_US';
@ -364,7 +374,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertEquals($esPg->ID, $frST->getTranslation('es_ES')->ID);
}
function testTranslationGroupNotRemovedWhenSiteTreeUnpublished() {
public function testTranslationGroupNotRemovedWhenSiteTreeUnpublished()
{
$enPage = new Page();
$enPage->Locale = 'en_US';
$enPage->write();
@ -383,7 +394,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertEquals($frPage->getTranslationGroup(), $frTranslationGroup);
}
function testGetTranslationOnSiteTree() {
public function testGetTranslationOnSiteTree()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('fr_FR');
@ -393,7 +405,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertEquals($getTranslationPage->ID, $translatedPage->ID);
}
function testGetTranslatedLanguages() {
public function testGetTranslatedLanguages()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
// through createTranslation()
@ -433,7 +446,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testTranslationCantHaveSameURLSegmentAcrossLanguages() {
public function testTranslationCantHaveSameURLSegmentAcrossLanguages()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
$this->assertEquals($translatedPage->URLSegment, 'testpage-de-de');
@ -451,7 +465,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testUpdateCMSFieldsOnSiteTree() {
public function testUpdateCMSFieldsOnSiteTree()
{
$pageOrigLang = new TranslatableTest_Page();
$pageOrigLang->write();
@ -517,10 +532,10 @@ class TranslatableTest extends FunctionalTest {
$fields->dataFieldByName('TranslatableObjectID'),
'Retains custom dropdown field as DropdownField'
);
}
function testDataObjectGetWithReadingLanguage() {
public function testDataObjectGetWithReadingLanguage()
{
$origTestPage = $this->objFromFixture('Page', 'testpage_en');
$otherTestPage = $this->objFromFixture('Page', 'othertestpage_en');
$translatedPage = $origTestPage->createTranslation('de_DE');
@ -531,8 +546,9 @@ class TranslatableTest extends FunctionalTest {
sprintf("\"SiteTree\".\"MenuTitle\" = '%s'", 'A Testpage')
);
$resultPagesDefaultLangIDs = $resultPagesDefaultLang->column('ID');
foreach($resultPagesDefaultLangIDs as $key => $val)
foreach ($resultPagesDefaultLangIDs as $key => $val) {
$resultPagesDefaultLangIDs[$key] = intval($val);
}
$this->assertEquals($resultPagesDefaultLang->Count(), 2);
$this->assertContains((int)$origTestPage->ID, $resultPagesDefaultLangIDs);
$this->assertContains((int)$otherTestPage->ID, $resultPagesDefaultLangIDs);
@ -545,8 +561,9 @@ class TranslatableTest extends FunctionalTest {
sprintf("\"SiteTree\".\"MenuTitle\" = '%s'", 'A Testpage')
);
$resultPagesCustomLangIDs = $resultPagesCustomLang->column('ID');
foreach($resultPagesCustomLangIDs as $key => $val)
foreach ($resultPagesCustomLangIDs as $key => $val) {
$resultPagesCustomLangIDs[$key] = intval($val);
}
$this->assertEquals($resultPagesCustomLang->Count(), 1);
$this->assertNotContains((int)$origTestPage->ID, $resultPagesCustomLangIDs);
$this->assertNotContains((int)$otherTestPage->ID, $resultPagesCustomLangIDs);
@ -555,7 +572,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testDataObjectGetByIdWithReadingLanguage() {
public function testDataObjectGetByIdWithReadingLanguage()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
$compareOrigPage = DataObject::get_by_id('Page', $origPage->ID);
@ -567,7 +585,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testDataObjectGetOneWithReadingLanguage() {
public function testDataObjectGetOneWithReadingLanguage()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
@ -588,7 +607,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testModifyTranslationWithDefaultReadingLang() {
public function testModifyTranslationWithDefaultReadingLang()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
@ -608,7 +628,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testSiteTreePublication() {
public function testSiteTreePublication()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
@ -627,7 +648,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testDeletingTranslationKeepsOriginal() {
public function testDeletingTranslationKeepsOriginal()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
$translatedPageID = $translatedPage->ID;
@ -640,7 +662,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertNotNull(DataObject::get_by_id('Page', $origPage->ID));
}
function testHierarchyChildren() {
public function testHierarchyChildren()
{
$parentPage = $this->objFromFixture('Page', 'parent');
$child1Page = $this->objFromFixture('Page', 'child1');
$child2Page = $this->objFromFixture('Page', 'child2');
@ -676,7 +699,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testHierarchyLiveStageChildren() {
public function testHierarchyLiveStageChildren()
{
$parentPage = $this->objFromFixture('Page', 'parent');
$child1Page = $this->objFromFixture('Page', 'child1');
$child1Page->publish('Stage', 'Live');
@ -739,7 +763,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testTranslatablePropertiesOnSiteTree() {
public function testTranslatablePropertiesOnSiteTree()
{
$origObj = $this->objFromFixture('TranslatableTest_Page', 'testpage_en');
$translatedObj = $origObj->createTranslation('fr_FR');
@ -758,7 +783,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testCreateTranslationOnSiteTree() {
public function testCreateTranslationOnSiteTree()
{
$origPage = $this->objFromFixture('Page', 'testpage_en');
$translatedPage = $origPage->createTranslation('de_DE');
@ -773,7 +799,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testTranslatablePropertiesOnDataObject() {
public function testTranslatablePropertiesOnDataObject()
{
$origObj = $this->objFromFixture('TranslatableTest_DataObject', 'testobject_en');
$translatedObj = $origObj->createTranslation('fr_FR');
$translatedObj->TranslatableProperty = 'fr_FR';
@ -802,7 +829,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testCreateTranslationWithoutOriginal() {
public function testCreateTranslationWithoutOriginal()
{
$origParentPage = $this->objFromFixture('Page', 'testpage_en');
$translatedParentPage = $origParentPage->createTranslation('de_DE');
@ -823,7 +851,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testCreateTranslationTranslatesUntranslatedParents() {
public function testCreateTranslationTranslatesUntranslatedParents()
{
$parentPage = $this->objFromFixture('Page', 'parent');
$child1Page = $this->objFromFixture('Page', 'child1');
$child1PageOrigID = $child1Page->ID;
@ -851,7 +880,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertTrue($parentPage->hasTranslation('de_DE'));
}
function testHierarchyAllChildrenIncludingDeleted() {
public function testHierarchyAllChildrenIncludingDeleted()
{
// Original tree in 'en_US':
// parent
// child1 (Live only, deleted from stage)
@ -938,7 +968,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testRootUrlDefaultsToTranslatedLink() {
public function testRootUrlDefaultsToTranslatedLink()
{
$origPage = $this->objFromFixture('Page', 'homepage_en');
$origPage->publish('Stage', 'Live');
$translationDe = $origPage->createTranslation('de_DE');
@ -969,7 +1000,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_US');
}
function testSiteTreeChangePageTypeInMaster() {
public function testSiteTreeChangePageTypeInMaster()
{
// create original
$origPage = new SiteTree();
$origPage->Locale = 'en_US';
@ -999,7 +1031,8 @@ class TranslatableTest extends FunctionalTest {
);
}
function testGetTranslationByStage() {
public function testGetTranslationByStage()
{
$publishedPage = new SiteTree();
$publishedPage->Locale = 'en_US';
$publishedPage->Title = 'Published';
@ -1024,7 +1057,8 @@ class TranslatableTest extends FunctionalTest {
$this->assertEquals($compareLive->Title, 'Publiziert');
}
function testCanTranslateAllowedLocales() {
public function testCanTranslateAllowedLocales()
{
$origAllowedLocales = Translatable::get_allowed_locales();
$cmseditor = $this->objFromFixture('Member', 'cmseditor');
@ -1054,15 +1088,17 @@ class TranslatableTest extends FunctionalTest {
try {
$testPage->createTranslation('de_DE');
$this->setExpectedException("Exception");
} catch(Exception $e) {}
} catch (Exception $e) {
}
Translatable::set_allowed_locales($origAllowedLocales);
}
function testCanTranslatePermissionCodes() {
public function testCanTranslatePermissionCodes()
{
$origAllowedLocales = Translatable::get_allowed_locales();
Translatable::set_allowed_locales(array('ja_JP','de_DE'));
Translatable::set_allowed_locales(array('ja_JP', 'de_DE'));
$cmseditor = $this->objFromFixture('Member', 'cmseditor');
@ -1088,7 +1124,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_allowed_locales($origAllowedLocales);
}
function testLocalesForMember() {
public function testLocalesForMember()
{
$origAllowedLocales = Translatable::get_allowed_locales();
Translatable::set_allowed_locales(array('de_DE', 'ja_JP'));
@ -1110,7 +1147,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_allowed_locales($origAllowedLocales);
}
function testSavePageInCMS() {
public function testSavePageInCMS()
{
$adminUser = $this->objFromFixture('Member', 'admin');
$enPage = $this->objFromFixture('Page', 'testpage_en');
@ -1141,7 +1179,8 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale($origLocale);
}
public function testAlternateGetByLink() {
public function testAlternateGetByLink()
{
$parent = $this->objFromFixture('Page', 'parent');
$child = $this->objFromFixture('Page', 'child1');
$grandchild = $this->objFromFixture('Page', 'grandchild1');
@ -1157,19 +1196,19 @@ class TranslatableTest extends FunctionalTest {
Translatable::set_current_locale('en_AU');
$this->assertEquals (
$this->assertEquals(
$parentTranslation->ID,
Sitetree::get_by_link($parentTranslation->Link())->ID,
'Top level pages can be found.'
);
$this->assertEquals (
$this->assertEquals(
$childTranslation->ID,
SiteTree::get_by_link($childTranslation->Link())->ID,
'Child pages can be found.'
);
$this->assertEquals (
$this->assertEquals(
$grandchildTranslation->ID,
SiteTree::get_by_link($grandchildTranslation->Link())->ID,
'Grandchild pages can be found.'
@ -1186,7 +1225,8 @@ class TranslatableTest extends FunctionalTest {
// );
}
public function testSiteTreeGetByLinkFindsTranslationWithoutLocale() {
public function testSiteTreeGetByLinkFindsTranslationWithoutLocale()
{
$parent = $this->objFromFixture('Page', 'parent');
$parentTranslation = $parent->createTranslation('en_AU');
@ -1206,13 +1246,15 @@ class TranslatableTest extends FunctionalTest {
}
}
class TranslatableTest_OneByLocaleDataObject extends DataObject implements TestOnly {
class TranslatableTest_OneByLocaleDataObject extends DataObject implements TestOnly
{
private static $db = array(
'TranslatableProperty' => 'Text'
);
}
class TranslatableTest_DataObject extends DataObject implements TestOnly {
class TranslatableTest_DataObject extends DataObject implements TestOnly
{
// add_extension() used to add decorator at end of file
private static $db = array(
@ -1220,15 +1262,15 @@ class TranslatableTest_DataObject extends DataObject implements TestOnly {
);
}
class TranslatableTest_Extension extends DataExtension implements TestOnly {
class TranslatableTest_Extension extends DataExtension implements TestOnly
{
private static $db = array(
'TranslatableDecoratedProperty' => 'Text'
);
}
class TranslatableTest_Page extends Page implements TestOnly {
class TranslatableTest_Page extends Page implements TestOnly
{
// static $extensions is inherited from SiteTree,
// we don't need to explicitly specify the fields
@ -1240,7 +1282,8 @@ class TranslatableTest_Page extends Page implements TestOnly {
'TranslatableObject' => 'TranslatableTest_DataObject'
);
function getCMSFields() {
public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldToTab(
'Root.Main',
@ -1258,9 +1301,10 @@ class TranslatableTest_Page extends Page implements TestOnly {
}
class EveryoneCanPublish extends DataExtension {
function canPublish($member = null) {
class EveryoneCanPublish extends DataExtension
{
public function canPublish($member = null)
{
return true;
}
}