Reformat for psr-2

This commit is contained in:
Damian Mooyman 2015-11-23 16:53:45 +13:00
parent 5f02e0c406
commit a0ede56c0e
30 changed files with 3602 additions and 3290 deletions

View File

@ -25,4 +25,3 @@ CMSMain::add_extension('SubsiteMenuExtension');
CMSPagesController::add_extension('SubsiteMenuExtension'); CMSPagesController::add_extension('SubsiteMenuExtension');
SubsiteAdmin::add_extension('SubsiteMenuExtension'); SubsiteAdmin::add_extension('SubsiteMenuExtension');
CMSSettingsController::add_extension('SubsiteMenuExtension'); CMSSettingsController::add_extension('SubsiteMenuExtension');

View File

@ -4,8 +4,8 @@
* *
* @package subsites * @package subsites
*/ */
class SubsiteAdmin extends ModelAdmin { class SubsiteAdmin extends ModelAdmin
{
private static $managed_models = array('Subsite'); private static $managed_models = array('Subsite');
private static $url_segment = 'subsites'; private static $url_segment = 'subsites';
@ -18,7 +18,8 @@ class SubsiteAdmin extends ModelAdmin {
private static $tree_class = 'Subsite'; private static $tree_class = 'Subsite';
public function getEditForm($id = null, $fields = null) { public function getEditForm($id = null, $fields = null)
{
$form = parent::getEditForm($id, $fields); $form = parent::getEditForm($id, $fields);
$grid=$form->Fields()->dataFieldByName('Subsite'); $grid=$form->Fields()->dataFieldByName('Subsite');
@ -29,5 +30,4 @@ class SubsiteAdmin extends ModelAdmin {
return $form; return $form;
} }
} }

View File

@ -4,11 +4,13 @@
* Creates a subsite-aware version of another report. * Creates a subsite-aware version of another report.
* Pass another report (or its classname) into the constructor. * Pass another report (or its classname) into the constructor.
*/ */
class SubsiteReportWrapper extends SS_ReportWrapper { class SubsiteReportWrapper extends SS_ReportWrapper
{
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Filtering // Filtering
function parameterFields() { public function parameterFields()
{
$subsites = Subsite::accessible_sites('CMS_ACCESS_CMSMain', true); $subsites = Subsite::accessible_sites('CMS_ACCESS_CMSMain', true);
$options = $subsites->toDropdownMap('ID', 'Title'); $options = $subsites->toDropdownMap('ID', 'Title');
@ -36,7 +38,8 @@ class SubsiteReportWrapper extends SS_ReportWrapper {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Columns // Columns
function columns() { public function columns()
{
$columns = parent::columns(); $columns = parent::columns();
$columns['Subsite.Title'] = "Subsite"; $columns['Subsite.Title'] = "Subsite";
return $columns; return $columns;
@ -45,7 +48,8 @@ class SubsiteReportWrapper extends SS_ReportWrapper {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Querying // Querying
function beforeQuery($params) { public function beforeQuery($params)
{
// The user has select a few specific sites // The user has select a few specific sites
if (!empty($params['Subsites'])) { if (!empty($params['Subsites'])) {
Subsite::$force_subsite = $params['Subsites']; Subsite::$force_subsite = $params['Subsites'];
@ -57,9 +61,9 @@ class SubsiteReportWrapper extends SS_ReportWrapper {
Subsite::$force_subsite = join(',', array_keys($options)); Subsite::$force_subsite = join(',', array_keys($options));
} }
} }
function afterQuery() { public function afterQuery()
{
// Manually manage the subsite filtering // Manually manage the subsite filtering
Subsite::$force_subsite = null; Subsite::$force_subsite = null;
} }
} }

View File

@ -3,15 +3,20 @@
/** /**
* Section-agnostic PJAX controller. * Section-agnostic PJAX controller.
*/ */
class SubsiteXHRController extends LeftAndMain { class SubsiteXHRController extends LeftAndMain
{
/** /**
* Relax the access permissions, so anyone who has access to any CMS subsite can access this controller. * Relax the access permissions, so anyone who has access to any CMS subsite can access this controller.
*/ */
public function canView($member = null) { public function canView($member = null)
if (parent::canView()) return true; {
if (parent::canView()) {
return true;
}
if (Subsite::all_accessible_sites()->count()>0) return true; if (Subsite::all_accessible_sites()->count()>0) {
return true;
}
return false; return false;
} }
@ -19,11 +24,15 @@ class SubsiteXHRController extends LeftAndMain {
/** /**
* Similar as above, but for the LeftAndMainSubsites - allow access if user allowed into the CMS at all. * Similar as above, but for the LeftAndMainSubsites - allow access if user allowed into the CMS at all.
*/ */
public function canAccess() { public function canAccess()
if (Subsite::all_accessible_sites()->count()>0) return true; {
if (Subsite::all_accessible_sites()->count()>0) {
return true;
}
} }
public function getResponseNegotiator() { public function getResponseNegotiator()
{
$negotiator = parent::getResponseNegotiator(); $negotiator = parent::getResponseNegotiator();
$self = $this; $self = $this;
@ -38,8 +47,8 @@ class SubsiteXHRController extends LeftAndMain {
/** /**
* Provide the list of available subsites as a cms-section-agnostic PJAX handler. * Provide the list of available subsites as a cms-section-agnostic PJAX handler.
*/ */
public function SubsiteList() { public function SubsiteList()
{
return $this->renderWith('SubsiteList'); return $this->renderWith('SubsiteList');
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
class SubsitesVirtualPage extends VirtualPage { class SubsitesVirtualPage extends VirtualPage
{
private static $description = 'Displays the content of a page on another subsite'; private static $description = 'Displays the content of a page on another subsite';
private static $db = array( private static $db = array(
@ -10,7 +10,8 @@ class SubsitesVirtualPage extends VirtualPage {
'CustomExtraMeta' => 'HTMLText' 'CustomExtraMeta' => 'HTMLText'
); );
public function getCMSFields() { public function getCMSFields()
{
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$subsites = DataObject::get('Subsite'); $subsites = DataObject::get('Subsite');
@ -100,7 +101,8 @@ class SubsitesVirtualPage extends VirtualPage {
return $fields; return $fields;
} }
public function fieldLabels($includerelations = true) { public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['CustomMetaTitle'] = _t('Subsite.CustomMetaTitle', 'Title'); $labels['CustomMetaTitle'] = _t('Subsite.CustomMetaTitle', 'Title');
$labels['CustomMetaKeywords'] = _t('Subsite.CustomMetaKeywords', 'Keywords'); $labels['CustomMetaKeywords'] = _t('Subsite.CustomMetaKeywords', 'Keywords');
@ -110,50 +112,67 @@ class SubsitesVirtualPage extends VirtualPage {
return $labels; return $labels;
} }
public function getCopyContentFromID_SubsiteID() { public function getCopyContentFromID_SubsiteID()
{
return ($this->CopyContentFromID) ? (int)$this->CopyContentFrom()->SubsiteID : (int)Session::get('SubsiteID'); return ($this->CopyContentFromID) ? (int)$this->CopyContentFrom()->SubsiteID : (int)Session::get('SubsiteID');
} }
public function getVirtualFields() { public function getVirtualFields()
{
$fields = parent::getVirtualFields(); $fields = parent::getVirtualFields();
foreach ($fields as $k => $v) { foreach ($fields as $k => $v) {
if($v == 'SubsiteID') unset($fields[$k]); if ($v == 'SubsiteID') {
unset($fields[$k]);
}
} }
foreach(self::$db as $field => $type) if (in_array($field, $fields)) unset($fields[array_search($field, $fields)]); foreach (self::$db as $field => $type) {
if (in_array($field, $fields)) {
unset($fields[array_search($field, $fields)]);
}
}
return $fields; return $fields;
} }
public function syncLinkTracking() { public function syncLinkTracking()
{
$oldState = Subsite::$disable_subsite_filter; $oldState = Subsite::$disable_subsite_filter;
Subsite::$disable_subsite_filter = true; Subsite::$disable_subsite_filter = true;
if ($this->CopyContentFromID) $this->HasBrokenLink = DataObject::get_by_id('SiteTree', $this->CopyContentFromID) ? false : true; if ($this->CopyContentFromID) {
$this->HasBrokenLink = DataObject::get_by_id('SiteTree', $this->CopyContentFromID) ? false : true;
}
Subsite::$disable_subsite_filter = $oldState; Subsite::$disable_subsite_filter = $oldState;
} }
public function onBeforeWrite() { public function onBeforeWrite()
{
parent::onBeforeWrite(); parent::onBeforeWrite();
if($this->CustomMetaTitle) $this->MetaTitle = $this->CustomMetaTitle; if ($this->CustomMetaTitle) {
else { $this->MetaTitle = $this->CustomMetaTitle;
} else {
$this->MetaTitle = $this->ContentSource()->MetaTitle ? $this->ContentSource()->MetaTitle : $this->MetaTitle; $this->MetaTitle = $this->ContentSource()->MetaTitle ? $this->ContentSource()->MetaTitle : $this->MetaTitle;
} }
if($this->CustomMetaKeywords) $this->MetaKeywords = $this->CustomMetaKeywords; if ($this->CustomMetaKeywords) {
else { $this->MetaKeywords = $this->CustomMetaKeywords;
} else {
$this->MetaKeywords = $this->ContentSource()->MetaKeywords ? $this->ContentSource()->MetaKeywords : $this->MetaKeywords; $this->MetaKeywords = $this->ContentSource()->MetaKeywords ? $this->ContentSource()->MetaKeywords : $this->MetaKeywords;
} }
if($this->CustomMetaDescription) $this->MetaDescription = $this->CustomMetaDescription; if ($this->CustomMetaDescription) {
else { $this->MetaDescription = $this->CustomMetaDescription;
} else {
$this->MetaDescription = $this->ContentSource()->MetaDescription ? $this->ContentSource()->MetaDescription : $this->MetaDescription; $this->MetaDescription = $this->ContentSource()->MetaDescription ? $this->ContentSource()->MetaDescription : $this->MetaDescription;
} }
if($this->CustomExtraMeta) $this->ExtraMeta = $this->CustomExtraMeta; if ($this->CustomExtraMeta) {
else { $this->ExtraMeta = $this->CustomExtraMeta;
} else {
$this->ExtraMeta = $this->ContentSource()->ExtraMeta ? $this->ContentSource()->ExtraMeta : $this->ExtraMeta; $this->ExtraMeta = $this->ContentSource()->ExtraMeta ? $this->ContentSource()->ExtraMeta : $this->ExtraMeta;
} }
} }
public function validURLSegment() { public function validURLSegment()
{
$isValid = parent::validURLSegment(); $isValid = parent::validURLSegment();
// Veto the validation rules if its false. In this case, some logic // Veto the validation rules if its false. In this case, some logic
@ -193,15 +212,17 @@ class SubsitesVirtualPage extends VirtualPage {
} }
} }
class SubsitesVirtualPage_Controller extends VirtualPage_Controller { class SubsitesVirtualPage_Controller extends VirtualPage_Controller
{
public function reloadContent() { public function reloadContent()
{
$this->failover->copyFrom($this->failover->CopyContentFrom()); $this->failover->copyFrom($this->failover->CopyContentFrom());
$this->failover->write(); $this->failover->write();
return; return;
} }
public function init(){ public function init()
{
$origDisableSubsiteFilter = Subsite::$disable_subsite_filter; $origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
Subsite::$disable_subsite_filter = true; Subsite::$disable_subsite_filter = true;

View File

@ -1,8 +1,8 @@
<?php <?php
class CMSPageAddControllerExtension extends Extension { class CMSPageAddControllerExtension extends Extension
{
function updatePageOptions(&$fields) { public function updatePageOptions(&$fields)
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID())); $fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }
} }

View File

@ -2,19 +2,21 @@
/** /**
* @package subsites * @package subsites
*/ */
class ControllerSubsites extends Extension { class ControllerSubsites extends Extension
function controllerAugmentInit(){ {
public function controllerAugmentInit()
{
if ($subsite = Subsite::currentSubsite()) { if ($subsite = Subsite::currentSubsite()) {
if($theme = $subsite->Theme) if ($theme = $subsite->Theme) {
SSViewer::set_theme($theme); SSViewer::set_theme($theme);
} }
} }
}
function CurrentSubsite(){ public function CurrentSubsite()
{
if ($subsite = Subsite::currentSubsite()) { if ($subsite = Subsite::currentSubsite()) {
return $subsite; return $subsite;
} }
} }
} }
?>

View File

@ -1,6 +1,6 @@
<?php <?php
class ErrorPageSubsite extends DataExtension { class ErrorPageSubsite extends DataExtension
{
/** /**
* Alter file path to generated a static (static) error page file to handle error page template on different sub-sites * Alter file path to generated a static (static) error page file to handle error page template on different sub-sites
* *
@ -9,7 +9,8 @@ class ErrorPageSubsite extends DataExtension {
* FIXME since {@link Subsite::currentSubsite()} partly relies on Session, viewing other sub-site (including main site) between * FIXME since {@link Subsite::currentSubsite()} partly relies on Session, viewing other sub-site (including main site) between
* opening ErrorPage in the CMS and publish ErrorPage causes static error page to get generated incorrectly. * opening ErrorPage in the CMS and publish ErrorPage causes static error page to get generated incorrectly.
*/ */
function alternateFilepathForErrorcode($statusCode, $locale = null) { public function alternateFilepathForErrorcode($statusCode, $locale = null)
{
$static_filepath = Config::inst()->get($this->owner->ClassName, 'static_filepath'); $static_filepath = Config::inst()->get($this->owner->ClassName, 'static_filepath');
$subdomainPart = ""; $subdomainPart = "";
@ -19,8 +20,11 @@ class ErrorPageSubsite extends DataExtension {
// since this function is called from Page class before the controller is created, we have to get subsite from domain instead // since this function is called from Page class before the controller is created, we have to get subsite from domain instead
if (!$subsite) { if (!$subsite) {
$subsiteID = Subsite::getSubsiteIDForDomain(); $subsiteID = Subsite::getSubsiteIDForDomain();
if($subsiteID != 0) $subsite = DataObject::get_by_id("Subsite", $subsiteID); if ($subsiteID != 0) {
else $subsite = null; $subsite = DataObject::get_by_id("Subsite", $subsiteID);
} else {
$subsite = null;
}
} }
if ($subsite) { if ($subsite) {
@ -36,5 +40,4 @@ class ErrorPageSubsite extends DataExtension {
return $filepath; return $filepath;
} }
} }

View File

@ -4,11 +4,11 @@
* *
* @package subsites * @package subsites
*/ */
class FileSubsites extends DataExtension { class FileSubsites extends DataExtension
{
// If this is set to true, all folders created will be default be // If this is set to true, all folders created will be default be
// considered 'global', unless set otherwise // considered 'global', unless set otherwise
static $default_root_folders_global = false; public static $default_root_folders_global = false;
private static $has_one=array( private static $has_one=array(
'Subsite' => 'Subsite', 'Subsite' => 'Subsite',
@ -18,15 +18,20 @@ class FileSubsites extends DataExtension {
* Amends the CMS tree title for folders in the Files & Images section. * Amends the CMS tree title for folders in the Files & Images section.
* Prefixes a '* ' to the folders that are accessible from all subsites. * Prefixes a '* ' to the folders that are accessible from all subsites.
*/ */
function alternateTreeTitle() { public function alternateTreeTitle()
if($this->owner->SubsiteID == 0) return " * " . $this->owner->Title; {
else return $this->owner->Title; if ($this->owner->SubsiteID == 0) {
return " * " . $this->owner->Title;
} else {
return $this->owner->Title;
}
} }
/** /**
* Add subsites-specific fields to the folder editor. * Add subsites-specific fields to the folder editor.
*/ */
function updateCMSFields(FieldList $fields) { public function updateCMSFields(FieldList $fields)
{
if ($this->owner instanceof Folder) { if ($this->owner instanceof Folder) {
$sites = Subsite::accessible_sites('CMS_ACCESS_AssetAdmin'); $sites = Subsite::accessible_sites('CMS_ACCESS_AssetAdmin');
$values = array(); $values = array();
@ -57,14 +62,19 @@ class FileSubsites extends DataExtension {
/** /**
* Update any requests to limit the results to the current site * Update any requests to limit the results to the current site
*/ */
public function augmentSQL(SQLQuery &$query) { public function augmentSQL(SQLQuery &$query)
if(Subsite::$disable_subsite_filter) return; {
if (Subsite::$disable_subsite_filter) {
return;
}
// If you're querying by ID, ignore the sub-site - this is a bit ugly... (but it was WAYYYYYYYYY worse) // If you're querying by ID, ignore the sub-site - this is a bit ugly... (but it was WAYYYYYYYYY worse)
//@TODO I don't think excluding if SiteTree_ImageTracking is a good idea however because of the SS 3.0 api and ManyManyList::removeAll() changing the from table after this function is called there isn't much of a choice //@TODO I don't think excluding if SiteTree_ImageTracking is a good idea however because of the SS 3.0 api and ManyManyList::removeAll() changing the from table after this function is called there isn't much of a choice
$from = $query->getFrom(); $from = $query->getFrom();
if(isset($from['SiteTree_ImageTracking']) || $query->filtersOnID()) return; if (isset($from['SiteTree_ImageTracking']) || $query->filtersOnID()) {
return;
}
$subsiteID = (int) Subsite::currentSubsiteID(); $subsiteID = (int) Subsite::currentSubsiteID();
@ -84,7 +94,8 @@ class FileSubsites extends DataExtension {
} }
} }
function onBeforeWrite() { public function onBeforeWrite()
{
if (!$this->owner->ID && !$this->owner->SubsiteID) { if (!$this->owner->ID && !$this->owner->SubsiteID) {
if (self::$default_root_folders_global) { if (self::$default_root_folders_global) {
$this->owner->SubsiteID = 0; $this->owner->SubsiteID = 0;
@ -94,7 +105,8 @@ class FileSubsites extends DataExtension {
} }
} }
function onAfterUpload() { public function onAfterUpload()
{
// If we have a parent, use it's subsite as our subsite // If we have a parent, use it's subsite as our subsite
if ($this->owner->Parent()) { if ($this->owner->Parent()) {
$this->owner->SubsiteID = $this->owner->Parent()->SubsiteID; $this->owner->SubsiteID = $this->owner->Parent()->SubsiteID;
@ -104,7 +116,8 @@ class FileSubsites extends DataExtension {
$this->owner->write(); $this->owner->write();
} }
function canEdit($member = null) { public function canEdit($member = null)
{
// Check the CMS_ACCESS_SecurityAdmin privileges on the subsite that owns this group // Check the CMS_ACCESS_SecurityAdmin privileges on the subsite that owns this group
$subsiteID = Session::get('SubsiteID'); $subsiteID = Session::get('SubsiteID');
if ($subsiteID&&$subsiteID == $this->owner->SubsiteID) { if ($subsiteID&&$subsiteID == $this->owner->SubsiteID) {
@ -121,9 +134,8 @@ class FileSubsites extends DataExtension {
/** /**
* Return a piece of text to keep DataObject cache keys appropriately specific * Return a piece of text to keep DataObject cache keys appropriately specific
*/ */
function cacheKeyComponent() { public function cacheKeyComponent()
{
return 'subsite-'.Subsite::currentSubsiteID(); return 'subsite-'.Subsite::currentSubsiteID();
} }
} }

View File

@ -4,8 +4,8 @@
* *
* @package subsites * @package subsites
*/ */
class GroupSubsites extends DataExtension implements PermissionProvider { class GroupSubsites extends DataExtension implements PermissionProvider
{
private static $db = array( private static $db = array(
'AccessAllSubsites' => 'Boolean' 'AccessAllSubsites' => 'Boolean'
); );
@ -21,7 +21,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
/** /**
* Migrations for GroupSubsites data. * Migrations for GroupSubsites data.
*/ */
function requireDefaultRecords() { public function requireDefaultRecords()
{
// Migration for Group.SubsiteID data from when Groups only had a single subsite // Migration for Group.SubsiteID data from when Groups only had a single subsite
$groupFields = DB::field_list('Group'); $groupFields = DB::field_list('Group');
@ -43,12 +44,12 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
LEFT JOIN "Group_Subsites" ON "Group_Subsites"."GroupID" = "Group"."ID" AND "Group_Subsites"."SubsiteID" > 0 LEFT JOIN "Group_Subsites" ON "Group_Subsites"."GroupID" = "Group"."ID" AND "Group_Subsites"."SubsiteID" > 0
WHERE "AccessAllSubsites" = 1 WHERE "AccessAllSubsites" = 1
OR "Group_Subsites"."GroupID" IS NOT NULL ')->value()) { OR "Group_Subsites"."GroupID" IS NOT NULL ')->value()) {
DB::query('UPDATE "Group" SET "AccessAllSubsites" = 1'); DB::query('UPDATE "Group" SET "AccessAllSubsites" = 1');
} }
} }
function updateCMSFields(FieldList $fields) { public function updateCMSFields(FieldList $fields)
{
if ($this->owner->canEdit()) { if ($this->owner->canEdit()) {
// i18n tab // i18n tab
$fields->findOrMakeTab('Root.Subsites', _t('GroupSubsites.SECURITYTABTITLE', 'Subsites')); $fields->findOrMakeTab('Root.Subsites', _t('GroupSubsites.SECURITYTABTITLE', 'Subsites'));
@ -73,7 +74,6 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
unset($subsiteMap[0]); unset($subsiteMap[0]);
$fields->addFieldToTab("Root.Subsites", new CheckboxSetField("Subsites", "", $fields->addFieldToTab("Root.Subsites", new CheckboxSetField("Subsites", "",
$subsiteMap)); $subsiteMap));
} else { } else {
if (sizeof($subsiteMap) <= 1) { if (sizeof($subsiteMap) <= 1) {
$fields->addFieldToTab("Root.Subsites", new ReadonlyField("SubsitesHuman", $fields->addFieldToTab("Root.Subsites", new ReadonlyField("SubsitesHuman",
@ -94,7 +94,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
* to make it easy to distinguish in the tree-view * to make it easy to distinguish in the tree-view
* of the security admin interface. * of the security admin interface.
*/ */
function alternateTreeTitle() { public function alternateTreeTitle()
{
if ($this->owner->AccessAllSubsites) { if ($this->owner->AccessAllSubsites) {
$title = _t('GroupSubsites.GlobalGroup', 'global group'); $title = _t('GroupSubsites.GlobalGroup', 'global group');
return htmlspecialchars($this->owner->Title, ENT_QUOTES) . ' <i>(' . $title . ')</i>'; return htmlspecialchars($this->owner->Title, ENT_QUOTES) . ' <i>(' . $title . ')</i>';
@ -107,9 +108,14 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
/** /**
* Update any requests to limit the results to the current site * Update any requests to limit the results to the current site
*/ */
public function augmentSQL(SQLQuery &$query) { public function augmentSQL(SQLQuery &$query)
if(Subsite::$disable_subsite_filter) return; {
if(Cookie::get('noSubsiteFilter') == 'true') return; if (Subsite::$disable_subsite_filter) {
return;
}
if (Cookie::get('noSubsiteFilter') == 'true') {
return;
}
// If you're querying by ID, ignore the sub-site - this is a bit ugly... // If you're querying by ID, ignore the sub-site - this is a bit ugly...
if (!$query->filtersOnID()) { if (!$query->filtersOnID()) {
@ -145,7 +151,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
} }
} }
function onBeforeWrite() { public function onBeforeWrite()
{
// New record test approximated by checking whether the ID has changed. // New record test approximated by checking whether the ID has changed.
// Note also that the after write test is only used when we're *not* on a subsite // Note also that the after write test is only used when we're *not* on a subsite
if ($this->owner->isChanged('ID') && !Subsite::currentSubsiteID()) { if ($this->owner->isChanged('ID') && !Subsite::currentSubsiteID()) {
@ -153,7 +160,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
} }
} }
function onAfterWrite() { public function onAfterWrite()
{
// New record test approximated by checking whether the ID has changed. // New record test approximated by checking whether the ID has changed.
// Note also that the after write test is only used when we're on a subsite // Note also that the after write test is only used when we're on a subsite
if ($this->owner->isChanged('ID') && $currentSubsiteID = Subsite::currentSubsiteID()) { if ($this->owner->isChanged('ID') && $currentSubsiteID = Subsite::currentSubsiteID()) {
@ -162,7 +170,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
} }
} }
function alternateCanEdit() { public function alternateCanEdit()
{
// Find the sites that this group belongs to and the sites where we have appropriate perm. // Find the sites that this group belongs to and the sites where we have appropriate perm.
$accessibleSites = Subsite::accessible_sites('CMS_ACCESS_SecurityAdmin')->column('ID'); $accessibleSites = Subsite::accessible_sites('CMS_ACCESS_SecurityAdmin')->column('ID');
$linkedSites = $this->owner->Subsites()->column('ID'); $linkedSites = $this->owner->Subsites()->column('ID');
@ -172,7 +181,8 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
return (bool)array_intersect($accessibleSites, $linkedSites); return (bool)array_intersect($accessibleSites, $linkedSites);
} }
function providePermissions() { public function providePermissions()
{
return array( return array(
'SECURITY_SUBSITE_GROUP' => array( 'SECURITY_SUBSITE_GROUP' => array(
'name' => _t('GroupSubsites.MANAGE_SUBSITES', 'Manage subsites for groups'), 'name' => _t('GroupSubsites.MANAGE_SUBSITES', 'Manage subsites for groups'),
@ -182,7 +192,4 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
) )
); );
} }
} }
?>

View File

@ -4,8 +4,8 @@
* *
* @package subsites * @package subsites
*/ */
class LeftAndMainSubsites extends Extension { class LeftAndMainSubsites extends Extension
{
private static $allowed_actions = array('CopyToSubsite'); private static $allowed_actions = array('CopyToSubsite');
/** /**
@ -15,7 +15,8 @@ class LeftAndMainSubsites extends Extension {
*/ */
private static $treats_subsite_0_as_global = false; private static $treats_subsite_0_as_global = false;
function init() { public function init()
{
Requirements::css('subsites/css/LeftAndMain_Subsites.css'); Requirements::css('subsites/css/LeftAndMain_Subsites.css');
Requirements::javascript('subsites/javascript/LeftAndMain_Subsites.js'); Requirements::javascript('subsites/javascript/LeftAndMain_Subsites.js');
Requirements::javascript('subsites/javascript/VirtualPage_Subsites.js'); Requirements::javascript('subsites/javascript/VirtualPage_Subsites.js');
@ -24,12 +25,14 @@ class LeftAndMainSubsites extends Extension {
/** /**
* Set the title of the CMS tree * Set the title of the CMS tree
*/ */
function getCMSTreeTitle() { public function getCMSTreeTitle()
{
$subsite = Subsite::currentSubSite(); $subsite = Subsite::currentSubSite();
return $subsite ? Convert::raw2xml($subsite->Title) : _t('LeftAndMain.SITECONTENTLEFT'); return $subsite ? Convert::raw2xml($subsite->Title) : _t('LeftAndMain.SITECONTENTLEFT');
} }
function updatePageOptions(&$fields) { public function updatePageOptions(&$fields)
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID())); $fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }
@ -38,23 +41,33 @@ class LeftAndMainSubsites extends Extension {
* *
* @return ArrayList of {@link Subsite} instances. * @return ArrayList of {@link Subsite} instances.
*/ */
function sectionSites($includeMainSite = true, $mainSiteTitle = "Main site", $member = null) { public function sectionSites($includeMainSite = true, $mainSiteTitle = "Main site", $member = null)
{
if ($mainSiteTitle == 'Main site') { if ($mainSiteTitle == 'Main site') {
$mainSiteTitle = _t('Subsites.MainSiteTitle', 'Main site'); $mainSiteTitle = _t('Subsites.MainSiteTitle', 'Main site');
} }
// Rationalise member arguments // Rationalise member arguments
if(!$member) $member = Member::currentUser(); if (!$member) {
if(!$member) return new ArrayList(); $member = Member::currentUser();
if(!is_object($member)) $member = DataObject::get_by_id('Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('Member', $member);
}
// Collect permissions - honour the LeftAndMain::required_permission_codes, current model requires // Collect permissions - honour the LeftAndMain::required_permission_codes, current model requires
// us to check if the user satisfies ALL permissions. Code partly copied from LeftAndMain::canView. // us to check if the user satisfies ALL permissions. Code partly copied from LeftAndMain::canView.
$codes = array(); $codes = array();
$extraCodes = Config::inst()->get($this->owner->class, 'required_permission_codes'); $extraCodes = Config::inst()->get($this->owner->class, 'required_permission_codes');
if ($extraCodes !== false) { if ($extraCodes !== false) {
if($extraCodes) $codes = array_merge($codes, (array)$extraCodes); if ($extraCodes) {
else $codes[] = "CMS_ACCESS_{$this->owner->class}"; $codes = array_merge($codes, (array)$extraCodes);
} else {
$codes[] = "CMS_ACCESS_{$this->owner->class}";
}
} else { } else {
// Check overriden - all subsites accessible. // Check overriden - all subsites accessible.
return Subsite::all_sites(); return Subsite::all_sites();
@ -89,7 +102,8 @@ class LeftAndMainSubsites extends Extension {
* Returns a list of the subsites accessible to the current user. * Returns a list of the subsites accessible to the current user.
* It's enough for any section to be accessible for the section to be included. * It's enough for any section to be accessible for the section to be included.
*/ */
public function Subsites() { public function Subsites()
{
return Subsite::all_accessible_sites(); return Subsite::all_accessible_sites();
} }
@ -99,7 +113,8 @@ class LeftAndMainSubsites extends Extension {
* @return ArrayList * @return ArrayList
*/ */
public function ListSubsites(){ public function ListSubsites()
{
$list = $this->Subsites(); $list = $this->Subsites();
$currentSubsiteID = Subsite::currentSubsiteID(); $currentSubsiteID = Subsite::currentSubsiteID();
@ -124,7 +139,8 @@ class LeftAndMainSubsites extends Extension {
return $output; return $output;
} }
public function alternateMenuDisplayCheck($controllerName) { public function alternateMenuDisplayCheck($controllerName)
{
if (!class_exists($controllerName)) { if (!class_exists($controllerName)) {
return false; return false;
} }
@ -146,23 +162,30 @@ class LeftAndMainSubsites extends Extension {
return false; return false;
} }
public function CanAddSubsites() { public function CanAddSubsites()
{
return Permission::check("ADMIN", "any", null, "all"); return Permission::check("ADMIN", "any", null, "all");
} }
/** /**
* Helper for testing if the subsite should be adjusted. * Helper for testing if the subsite should be adjusted.
*/ */
public function shouldChangeSubsite($adminClass, $recordSubsiteID, $currentSubsiteID) { public function shouldChangeSubsite($adminClass, $recordSubsiteID, $currentSubsiteID)
if (Config::inst()->get($adminClass, 'treats_subsite_0_as_global') && $recordSubsiteID==0) return false; {
if ($recordSubsiteID!=$currentSubsiteID) return true; if (Config::inst()->get($adminClass, 'treats_subsite_0_as_global') && $recordSubsiteID==0) {
return false;
}
if ($recordSubsiteID!=$currentSubsiteID) {
return true;
}
return false; return false;
} }
/** /**
* Check if the current controller is accessible for this user on this subsite. * Check if the current controller is accessible for this user on this subsite.
*/ */
function canAccess() { public function canAccess()
{
// Admin can access everything, no point in checking. // Admin can access everything, no point in checking.
$member = Member::currentUser(); $member = Member::currentUser();
if ($member && if ($member &&
@ -187,7 +210,8 @@ class LeftAndMainSubsites extends Extension {
* Prevent accessing disallowed resources. This happens after onBeforeInit has executed, * Prevent accessing disallowed resources. This happens after onBeforeInit has executed,
* so all redirections should've already taken place. * so all redirections should've already taken place.
*/ */
public function alternateAccessCheck() { public function alternateAccessCheck()
{
return $this->owner->canAccess(); return $this->owner->canAccess();
} }
@ -201,7 +225,8 @@ class LeftAndMainSubsites extends Extension {
* fully re-synchronised with the internal session. This is better than risking some panels * fully re-synchronised with the internal session. This is better than risking some panels
* showing data from another subsite. * showing data from another subsite.
*/ */
public function onBeforeInit() { public function onBeforeInit()
{
// We are accessing the CMS, so we need to let Subsites know we will be using the session. // We are accessing the CMS, so we need to let Subsites know we will be using the session.
Subsite::$use_session_subsiteid = true; Subsite::$use_session_subsiteid = true;
@ -230,7 +255,6 @@ class LeftAndMainSubsites extends Extension {
// This is needed to properly initialise the session in situations where someone opens the CMS via a link. // This is needed to properly initialise the session in situations where someone opens the CMS via a link.
$record = $this->owner->currentPage(); $record = $this->owner->currentPage();
if ($record && isset($record->SubsiteID) && is_numeric($record->SubsiteID) && isset($this->owner->urlParams['ID'])) { if ($record && isset($record->SubsiteID) && is_numeric($record->SubsiteID) && isset($this->owner->urlParams['ID'])) {
if ($this->shouldChangeSubsite($this->owner->class, $record->SubsiteID, Subsite::currentSubsiteID())) { if ($this->shouldChangeSubsite($this->owner->class, $record->SubsiteID, Subsite::currentSubsiteID())) {
// Update current subsite in session // Update current subsite in session
Subsite::changeSubsite($record->SubsiteID); Subsite::changeSubsite($record->SubsiteID);
@ -242,20 +266,17 @@ class LeftAndMainSubsites extends Extension {
//Redirect to the default CMS section //Redirect to the default CMS section
return $this->owner->redirect('admin/'); return $this->owner->redirect('admin/');
} }
} }
// SECOND, check if we need to change subsites due to lack of permissions. // SECOND, check if we need to change subsites due to lack of permissions.
if (!$this->owner->canAccess()) { if (!$this->owner->canAccess()) {
$member = Member::currentUser(); $member = Member::currentUser();
// Current section is not accessible, try at least to stick to the same subsite. // Current section is not accessible, try at least to stick to the same subsite.
$menu = CMSMenu::get_menu_items(); $menu = CMSMenu::get_menu_items();
foreach ($menu as $candidate) { foreach ($menu as $candidate) {
if ($candidate->controller && $candidate->controller!=$this->owner->class) { if ($candidate->controller && $candidate->controller!=$this->owner->class) {
$accessibleSites = singleton($candidate->controller)->sectionSites(true, 'Main site', $member); $accessibleSites = singleton($candidate->controller)->sectionSites(true, 'Main site', $member);
if ($accessibleSites->count() && $accessibleSites->find('ID', Subsite::currentSubsiteID())) { if ($accessibleSites->count() && $accessibleSites->find('ID', Subsite::currentSubsiteID())) {
// Section is accessible, redirect there. // Section is accessible, redirect there.
@ -277,24 +298,26 @@ class LeftAndMainSubsites extends Extension {
// We have not found any accessible section or subsite. User should be denied access. // We have not found any accessible section or subsite. User should be denied access.
return Security::permissionFailure($this->owner); return Security::permissionFailure($this->owner);
} }
// Current site is accessible. Allow through. // Current site is accessible. Allow through.
return; return;
} }
function augmentNewSiteTreeItem(&$item) { public function augmentNewSiteTreeItem(&$item)
{
$item->SubsiteID = isset($_POST['SubsiteID']) ? $_POST['SubsiteID'] : Subsite::currentSubsiteID(); $item->SubsiteID = isset($_POST['SubsiteID']) ? $_POST['SubsiteID'] : Subsite::currentSubsiteID();
} }
function onAfterSave($record) { public function onAfterSave($record)
{
if ($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) { if ($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) {
$this->owner->response->addHeader('X-Status', rawurlencode(_t('LeftAndMainSubsites.Saved', 'Saved, please update related pages.'))); $this->owner->response->addHeader('X-Status', rawurlencode(_t('LeftAndMainSubsites.Saved', 'Saved, please update related pages.')));
} }
} }
function copytosubsite($data, $form) { public function copytosubsite($data, $form)
{
$page = DataObject::get_by_id('SiteTree', $data['ID']); $page = DataObject::get_by_id('SiteTree', $data['ID']);
$subsite = DataObject::get_by_id('Subsite', $data['CopyToSubsiteID']); $subsite = DataObject::get_by_id('Subsite', $data['CopyToSubsiteID']);
$newPage = $page->duplicateToSubsite($subsite->ID, true); $newPage = $page->duplicateToSubsite($subsite->ID, true);
@ -302,5 +325,4 @@ class LeftAndMainSubsites extends Extension {
$response->addHeader('X-Reload', true); $response->addHeader('X-Reload', true);
return $this->owner->redirect(Controller::join_links($this->owner->Link('show'), $newPage->ID)); return $this->owner->redirect(Controller::join_links($this->owner->Link('show'), $newPage->ID));
} }
} }

View File

@ -3,8 +3,8 @@
/** /**
* Extension for the SiteConfig object to add subsites support * Extension for the SiteConfig object to add subsites support
*/ */
class SiteConfigSubsites extends DataExtension { class SiteConfigSubsites extends DataExtension
{
private static $has_one = array( private static $has_one = array(
'Subsite' => 'Subsite', // The subsite that this page belongs to 'Subsite' => 'Subsite', // The subsite that this page belongs to
); );
@ -12,14 +12,21 @@ class SiteConfigSubsites extends DataExtension {
/** /**
* Update any requests to limit the results to the current site * Update any requests to limit the results to the current site
*/ */
public function augmentSQL(SQLQuery &$query) { public function augmentSQL(SQLQuery &$query)
if(Subsite::$disable_subsite_filter) return; {
if (Subsite::$disable_subsite_filter) {
return;
}
// If you're querying by ID, ignore the sub-site - this is a bit ugly... // If you're querying by ID, ignore the sub-site - this is a bit ugly...
if($query->filtersOnID()) return; if ($query->filtersOnID()) {
return;
}
$regexp = '/^(.*\.)?("|`)?SubsiteID("|`)?\s?=/'; $regexp = '/^(.*\.)?("|`)?SubsiteID("|`)?\s?=/';
foreach ($query->getWhereParameterised($parameters) as $predicate) { foreach ($query->getWhereParameterised($parameters) as $predicate) {
if(preg_match($regexp, $predicate)) return; if (preg_match($regexp, $predicate)) {
return;
}
} }
/*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID; /*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
@ -28,22 +35,29 @@ class SiteConfigSubsites extends DataExtension {
$froms=$query->getFrom(); $froms=$query->getFrom();
$froms=array_keys($froms); $froms=array_keys($froms);
$tableName = array_shift($froms); $tableName = array_shift($froms);
if($tableName != 'SiteConfig') return; if ($tableName != 'SiteConfig') {
return;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
} }
function onBeforeWrite() { public function onBeforeWrite()
if((!is_numeric($this->owner->ID) || !$this->owner->ID) && !$this->owner->SubsiteID) $this->owner->SubsiteID = Subsite::currentSubsiteID(); {
if ((!is_numeric($this->owner->ID) || !$this->owner->ID) && !$this->owner->SubsiteID) {
$this->owner->SubsiteID = Subsite::currentSubsiteID();
}
} }
/** /**
* Return a piece of text to keep DataObject cache keys appropriately specific * Return a piece of text to keep DataObject cache keys appropriately specific
*/ */
function cacheKeyComponent() { public function cacheKeyComponent()
{
return 'subsite-'.Subsite::currentSubsiteID(); return 'subsite-'.Subsite::currentSubsiteID();
} }
function updateCMSFields(FieldList $fields) { public function updateCMSFields(FieldList $fields)
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID())); $fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }
} }

View File

@ -3,8 +3,8 @@
/** /**
* Extension for the SiteTree object to add subsites support * Extension for the SiteTree object to add subsites support
*/ */
class SiteTreeSubsites extends DataExtension { class SiteTreeSubsites extends DataExtension
{
private static $has_one = array( private static $has_one = array(
'Subsite' => 'Subsite', // The subsite that this page belongs to 'Subsite' => 'Subsite', // The subsite that this page belongs to
); );
@ -17,24 +17,35 @@ class SiteTreeSubsites extends DataExtension {
"CrossSubsiteLinkTracking" => array("FieldName" => "Varchar") "CrossSubsiteLinkTracking" => array("FieldName" => "Varchar")
); );
function isMainSite() { public function isMainSite()
if($this->owner->SubsiteID == 0) return true; {
if ($this->owner->SubsiteID == 0) {
return true;
}
return false; return false;
} }
/** /**
* Update any requests to limit the results to the current site * Update any requests to limit the results to the current site
*/ */
public function augmentSQL(SQLQuery &$query, DataQuery &$dataQuery = null) { public function augmentSQL(SQLQuery &$query, DataQuery &$dataQuery = null)
if(Subsite::$disable_subsite_filter) return; {
if($dataQuery->getQueryParam('Subsite.filter') === false) return; if (Subsite::$disable_subsite_filter) {
return;
}
if ($dataQuery->getQueryParam('Subsite.filter') === false) {
return;
}
// If you're querying by ID, ignore the sub-site - this is a bit ugly... // If you're querying by ID, ignore the sub-site - this is a bit ugly...
// if(!$query->where || (strpos($query->where[0], ".\"ID\" = ") === false && strpos($query->where[0], ".`ID` = ") === false && strpos($query->where[0], ".ID = ") === false && strpos($query->where[0], "ID = ") !== 0)) { // if(!$query->where || (strpos($query->where[0], ".\"ID\" = ") === false && strpos($query->where[0], ".`ID` = ") === false && strpos($query->where[0], ".ID = ") === false && strpos($query->where[0], "ID = ") !== 0)) {
if($query->filtersOnID()) return; if ($query->filtersOnID()) {
return;
}
if (Subsite::$force_subsite) $subsiteID = Subsite::$force_subsite; if (Subsite::$force_subsite) {
else { $subsiteID = Subsite::$force_subsite;
} else {
/*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID; /*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
else */$subsiteID = (int)Subsite::currentSubsiteID(); else */$subsiteID = (int)Subsite::currentSubsiteID();
} }
@ -42,19 +53,25 @@ class SiteTreeSubsites extends DataExtension {
// The foreach is an ugly way of getting the first key :-) // The foreach is an ugly way of getting the first key :-)
foreach ($query->getFrom() as $tableName => $info) { foreach ($query->getFrom() as $tableName => $info) {
// The tableName should be SiteTree or SiteTree_Live... // The tableName should be SiteTree or SiteTree_Live...
if(strpos($tableName,'SiteTree') === false) break; if (strpos($tableName, 'SiteTree') === false) {
break;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
break; break;
} }
} }
function onBeforeWrite() { public function onBeforeWrite()
if(!$this->owner->ID && !$this->owner->SubsiteID) $this->owner->SubsiteID = Subsite::currentSubsiteID(); {
if (!$this->owner->ID && !$this->owner->SubsiteID) {
$this->owner->SubsiteID = Subsite::currentSubsiteID();
}
parent::onBeforeWrite(); parent::onBeforeWrite();
} }
function updateCMSFields(FieldList $fields) { public function updateCMSFields(FieldList $fields)
{
$subsites = Subsite::accessible_sites("CMS_ACCESS_CMSMain"); $subsites = Subsite::accessible_sites("CMS_ACCESS_CMSMain");
$subsitesMap = array(); $subsitesMap = array();
if ($subsites && $subsites->Count()) { if ($subsites && $subsites->Count()) {
@ -99,8 +116,11 @@ class SiteTreeSubsites extends DataExtension {
} }
} }
function alternateSiteConfig() { public function alternateSiteConfig()
if(!$this->owner->SubsiteID) return false; {
if (!$this->owner->SubsiteID) {
return false;
}
$sc = DataObject::get_one('SiteConfig', '"SubsiteID" = ' . $this->owner->SubsiteID); $sc = DataObject::get_one('SiteConfig', '"SubsiteID" = ' . $this->owner->SubsiteID);
if (!$sc) { if (!$sc) {
$sc = new SiteConfig(); $sc = new SiteConfig();
@ -119,9 +139,11 @@ class SiteTreeSubsites extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
function canEdit($member = null) { public function canEdit($member = null)
{
if(!$member) $member = Member::currentUser(); if (!$member) {
$member = Member::currentUser();
}
// Find the sites that this user has access to // Find the sites that this user has access to
$goodSites = Subsite::accessible_sites('CMS_ACCESS_CMSMain', true, 'all', $member)->column('ID'); $goodSites = Subsite::accessible_sites('CMS_ACCESS_CMSMain', true, 'all', $member)->column('ID');
@ -138,14 +160,19 @@ class SiteTreeSubsites extends DataExtension {
} }
// Return true if they have access to this object's site // Return true if they have access to this object's site
if(!(in_array(0, $goodSites) || in_array($subsiteID, $goodSites))) return false; if (!(in_array(0, $goodSites) || in_array($subsiteID, $goodSites))) {
return false;
}
} }
/** /**
* @return boolean * @return boolean
*/ */
function canDelete($member = null) { public function canDelete($member = null)
if(!$member && $member !== FALSE) $member = Member::currentUser(); {
if (!$member && $member !== false) {
$member = Member::currentUser();
}
return $this->canEdit($member); return $this->canEdit($member);
} }
@ -153,8 +180,11 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* @return boolean * @return boolean
*/ */
function canAddChildren($member = null) { public function canAddChildren($member = null)
if(!$member && $member !== FALSE) $member = Member::currentUser(); {
if (!$member && $member !== false) {
$member = Member::currentUser();
}
return $this->canEdit($member); return $this->canEdit($member);
} }
@ -162,8 +192,11 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* @return boolean * @return boolean
*/ */
function canPublish($member = null) { public function canPublish($member = null)
if(!$member && $member !== FALSE) $member = Member::currentUser(); {
if (!$member && $member !== false) {
$member = Member::currentUser();
}
return $this->canEdit($member); return $this->canEdit($member);
} }
@ -172,11 +205,14 @@ class SiteTreeSubsites extends DataExtension {
* Create a duplicate of this page and save it to another subsite * Create a duplicate of this page and save it to another subsite
* @param $subsiteID int|Subsite The Subsite to copy to, or its ID * @param $subsiteID int|Subsite The Subsite to copy to, or its ID
*/ */
public function duplicateToSubsite($subsiteID = null) { public function duplicateToSubsite($subsiteID = null)
{
if (is_object($subsiteID)) { if (is_object($subsiteID)) {
$subsite = $subsiteID; $subsite = $subsiteID;
$subsiteID = $subsite->ID; $subsiteID = $subsite->ID;
} else $subsite = DataObject::get_by_id('Subsite', $subsiteID); } else {
$subsite = DataObject::get_by_id('Subsite', $subsiteID);
}
$oldSubsite=Subsite::currentSubsiteID(); $oldSubsite=Subsite::currentSubsiteID();
if ($subsiteID) { if ($subsiteID) {
@ -203,7 +239,8 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* Called by ContentController::init(); * Called by ContentController::init();
*/ */
static function contentcontrollerInit($controller) { public static function contentcontrollerInit($controller)
{
$subsite = Subsite::currentSubsite(); $subsite = Subsite::currentSubsite();
if ($subsite && $subsite->Theme) { if ($subsite && $subsite->Theme) {
@ -211,7 +248,8 @@ class SiteTreeSubsites extends DataExtension {
} }
} }
function alternateAbsoluteLink() { public function alternateAbsoluteLink()
{
// Generate the existing absolute URL and replace the domain with the subsite domain. // Generate the existing absolute URL and replace the domain with the subsite domain.
// This helps deal with Link() returning an absolute URL. // This helps deal with Link() returning an absolute URL.
$url = Director::absoluteURL($this->owner->Link()); $url = Director::absoluteURL($this->owner->Link());
@ -225,7 +263,8 @@ class SiteTreeSubsites extends DataExtension {
* Use the CMS domain for iframed CMS previews to prevent single-origin violations * Use the CMS domain for iframed CMS previews to prevent single-origin violations
* and SSL cert problems. * and SSL cert problems.
*/ */
function alternatePreviewLink($action = null) { public function alternatePreviewLink($action = null)
{
$url = Director::absoluteURL($this->owner->Link()); $url = Director::absoluteURL($this->owner->Link());
if ($this->owner->SubsiteID) { if ($this->owner->SubsiteID) {
$url = HTTP::setGetVar('SubsiteID', $this->owner->SubsiteID, $url); $url = HTTP::setGetVar('SubsiteID', $this->owner->SubsiteID, $url);
@ -236,7 +275,8 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* Inject the subsite ID into the content so it can be used by frontend scripts. * Inject the subsite ID into the content so it can be used by frontend scripts.
*/ */
function MetaTags(&$tags) { public function MetaTags(&$tags)
{
if ($this->owner->SubsiteID) { if ($this->owner->SubsiteID) {
$tags .= "<meta name=\"x-subsite-id\" content=\"" . $this->owner->SubsiteID . "\" />\n"; $tags .= "<meta name=\"x-subsite-id\" content=\"" . $this->owner->SubsiteID . "\" />\n";
} }
@ -244,12 +284,14 @@ class SiteTreeSubsites extends DataExtension {
return $tags; return $tags;
} }
function augmentSyncLinkTracking() { public function augmentSyncLinkTracking()
{
// Set LinkTracking appropriately // Set LinkTracking appropriately
$links = HTTP::getLinksIn($this->owner->Content); $links = HTTP::getLinksIn($this->owner->Content);
$linkedPages = array(); $linkedPages = array();
if($links) foreach($links as $link) { if ($links) {
foreach ($links as $link) {
if (substr($link, 0, strlen('http://')) == 'http://') { if (substr($link, 0, strlen('http://')) == 'http://') {
$withoutHttp = substr($link, strlen('http://')); $withoutHttp = substr($link, strlen('http://'));
if (strpos($withoutHttp, '/') && strpos($withoutHttp, '/') < strlen($withoutHttp)) { if (strpos($withoutHttp, '/') && strpos($withoutHttp, '/') < strlen($withoutHttp)) {
@ -257,7 +299,9 @@ class SiteTreeSubsites extends DataExtension {
$rest = substr($withoutHttp, strpos($withoutHttp, '/') + 1); $rest = substr($withoutHttp, strpos($withoutHttp, '/') + 1);
$subsiteID = Subsite::getSubsiteIDForDomain($domain); $subsiteID = Subsite::getSubsiteIDForDomain($domain);
if($subsiteID == 0) continue; // We have no idea what the domain for the main site is, so cant track links to it if ($subsiteID == 0) {
continue;
} // We have no idea what the domain for the main site is, so cant track links to it
$origDisableSubsiteFilter = Subsite::$disable_subsite_filter; $origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
Subsite::disable_subsite_filter(true); Subsite::disable_subsite_filter(true);
@ -272,6 +316,7 @@ class SiteTreeSubsites extends DataExtension {
} }
} }
} }
}
$this->owner->CrossSubsiteLinkTracking()->setByIDList($linkedPages); $this->owner->CrossSubsiteLinkTracking()->setByIDList($linkedPages);
} }
@ -279,7 +324,8 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* Return a piece of text to keep DataObject cache keys appropriately specific * Return a piece of text to keep DataObject cache keys appropriately specific
*/ */
function cacheKeyComponent() { public function cacheKeyComponent()
{
return 'subsite-'.Subsite::currentSubsiteID(); return 'subsite-'.Subsite::currentSubsiteID();
} }
@ -287,13 +333,16 @@ class SiteTreeSubsites extends DataExtension {
* @param Member * @param Member
* @return boolean|null * @return boolean|null
*/ */
function canCreate($member = null) { public function canCreate($member = null)
{
// Typically called on a singleton, so we're not using the Subsite() relation // Typically called on a singleton, so we're not using the Subsite() relation
$subsite = Subsite::currentSubsite(); $subsite = Subsite::currentSubsite();
if ($subsite && $subsite->exists() && $subsite->PageTypeBlacklist) { if ($subsite && $subsite->exists() && $subsite->PageTypeBlacklist) {
$blacklisted = explode(',', $subsite->PageTypeBlacklist); $blacklisted = explode(',', $subsite->PageTypeBlacklist);
// All subclasses need to be listed explicitly // All subclasses need to be listed explicitly
if(in_array($this->owner->class, $blacklisted)) return false; if (in_array($this->owner->class, $blacklisted)) {
return false;
}
} }
} }
} }

View File

@ -10,10 +10,10 @@
* Or you can include the subsiteCMSShowInMenu function in your admin class and have it return true * Or you can include the subsiteCMSShowInMenu function in your admin class and have it return true
*/ */
class SubsiteMenuExtension extends Extension{ class SubsiteMenuExtension extends Extension
{
public function subsiteCMSShowInMenu(){ public function subsiteCMSShowInMenu()
{
return true; return true;
} }
} }

View File

@ -1,10 +1,11 @@
<?php <?php
class GridFieldSubsiteDetailForm extends GridFieldDetailForm { class GridFieldSubsiteDetailForm extends GridFieldDetailForm
{
protected $itemRequestClass='GridFieldSubsiteDetailForm_ItemRequest'; protected $itemRequestClass='GridFieldSubsiteDetailForm_ItemRequest';
} }
class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest { class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
private static $allowed_actions = array( private static $allowed_actions = array(
'ItemEditForm', 'ItemEditForm',
); );
@ -20,7 +21,8 @@ class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemReq
* @return Form * @return Form
* @see GridFieldDetailForm_ItemRequest::ItemEditForm() * @see GridFieldDetailForm_ItemRequest::ItemEditForm()
*/ */
function ItemEditForm() { public function ItemEditForm()
{
$form=parent::ItemEditForm(); $form=parent::ItemEditForm();
if ($this->record->ID == 0) { if ($this->record->ID == 0) {
@ -38,7 +40,8 @@ class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemReq
return $form; return $form;
} }
function doSave($data, $form) { public function doSave($data, $form)
{
$new_record = $this->record->ID == 0; $new_record = $this->record->ID == 0;
if ($new_record && isset($data['TemplateID']) && !empty($data['TemplateID'])) { if ($new_record && isset($data['TemplateID']) && !empty($data['TemplateID'])) {
$template = Subsite::get()->byID(intval($data['TemplateID'])); $template = Subsite::get()->byID(intval($data['TemplateID']));

View File

@ -5,8 +5,8 @@
* *
* @package subsites * @package subsites
*/ */
class SubsitesTreeDropdownField extends TreeDropdownField { class SubsitesTreeDropdownField extends TreeDropdownField
{
private static $allowed_actions = array( private static $allowed_actions = array(
'tree' 'tree'
); );
@ -15,7 +15,8 @@ class SubsitesTreeDropdownField extends TreeDropdownField {
protected $extraClasses = array('SubsitesTreeDropdownField'); protected $extraClasses = array('SubsitesTreeDropdownField');
function Field($properties = array()) { public function Field($properties = array())
{
$html = parent::Field($properties); $html = parent::Field($properties);
Requirements::javascript('subsites/javascript/SubsitesTreeDropdownField.js'); Requirements::javascript('subsites/javascript/SubsitesTreeDropdownField.js');
@ -23,15 +24,18 @@ class SubsitesTreeDropdownField extends TreeDropdownField {
return $html; return $html;
} }
function setSubsiteID($id) { public function setSubsiteID($id)
{
$this->subsiteID = $id; $this->subsiteID = $id;
} }
function getSubsiteID() { public function getSubsiteID()
{
return $this->subsiteID; return $this->subsiteID;
} }
function tree(SS_HTTPRequest $request) { public function tree(SS_HTTPRequest $request)
{
$oldSubsiteID = Session::get('SubsiteID'); $oldSubsiteID = Session::get('SubsiteID');
Session::set('SubsiteID', $this->subsiteID); Session::set('SubsiteID', $this->subsiteID);

View File

@ -5,8 +5,8 @@
* *
* @package subsites * @package subsites
*/ */
class Subsite extends DataObject { class Subsite extends DataObject
{
/** /**
* @var $use_session_subsiteid Boolean Set to TRUE when using the CMS and FALSE * @var $use_session_subsiteid Boolean Set to TRUE when using the CMS and FALSE
* when browsing the frontend of a website. * when browsing the frontend of a website.
@ -72,7 +72,8 @@ class Subsite extends DataObject {
* *
* @param array $themes - Numeric array of all themes which are allowed to be selected for all subsites. * @param array $themes - Numeric array of all themes which are allowed to be selected for all subsites.
*/ */
public static function set_allowed_themes($themes) { public static function set_allowed_themes($themes)
{
self::$allowed_themes = $themes; self::$allowed_themes = $themes;
} }
@ -82,7 +83,8 @@ class Subsite extends DataObject {
* @uses ControllerSubsites->controllerAugmentInit() * @uses ControllerSubsites->controllerAugmentInit()
* @return Subsite * @return Subsite
*/ */
public static function currentSubsite() { public static function currentSubsite()
{
// get_by_id handles caching so we don't have to // get_by_id handles caching so we don't have to
return DataObject::get_by_id('Subsite', self::currentSubsiteID()); return DataObject::get_by_id('Subsite', self::currentSubsiteID());
} }
@ -100,8 +102,9 @@ class Subsite extends DataObject {
* @param boolean $cache * @param boolean $cache
* @return int ID of the current subsite instance * @return int ID of the current subsite instance
*/ */
public static function currentSubsiteID() { public static function currentSubsiteID()
$id = NULL; {
$id = null;
if (isset($_GET['SubsiteID'])) { if (isset($_GET['SubsiteID'])) {
$id = (int)$_GET['SubsiteID']; $id = (int)$_GET['SubsiteID'];
@ -109,7 +112,7 @@ class Subsite extends DataObject {
$id = Session::get('SubsiteID'); $id = Session::get('SubsiteID');
} }
if($id === NULL) { if ($id === null) {
$id = self::getSubsiteIDForDomain(); $id = self::getSubsiteIDForDomain();
} }
@ -122,13 +125,19 @@ class Subsite extends DataObject {
* *
* @param int|Subsite $subsite Either the ID of the subsite, or the subsite object itself * @param int|Subsite $subsite Either the ID of the subsite, or the subsite object itself
*/ */
public static function changeSubsite($subsite) { public static function changeSubsite($subsite)
{
// Session subsite change only meaningful if the session is active. // Session subsite change only meaningful if the session is active.
// Otherwise we risk setting it to wrong value, e.g. if we rely on currentSubsiteID. // Otherwise we risk setting it to wrong value, e.g. if we rely on currentSubsiteID.
if (!Subsite::$use_session_subsiteid) return; if (!Subsite::$use_session_subsiteid) {
return;
}
if(is_object($subsite)) $subsiteID = $subsite->ID; if (is_object($subsite)) {
else $subsiteID = $subsite; $subsiteID = $subsite->ID;
} else {
$subsiteID = $subsite;
}
Session::set('SubsiteID', (int)$subsiteID); Session::set('SubsiteID', (int)$subsiteID);
@ -152,7 +161,8 @@ class Subsite extends DataObject {
* @param $host The host to find the subsite for. If not specified, $_SERVER['HTTP_HOST'] is used. * @param $host The host to find the subsite for. If not specified, $_SERVER['HTTP_HOST'] is used.
* @return int Subsite ID * @return int Subsite ID
*/ */
public static function getSubsiteIDForDomain($host = null, $checkPermissions = true) { public static function getSubsiteIDForDomain($host = null, $checkPermissions = true)
{
if ($host == null && isset($_SERVER['HTTP_HOST'])) { if ($host == null && isset($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST']; $host = $_SERVER['HTTP_HOST'];
} }
@ -160,10 +170,14 @@ class Subsite extends DataObject {
$matchingDomains = null; $matchingDomains = null;
$cacheKey = null; $cacheKey = null;
if ($host) { if ($host) {
if(!self::$strict_subdomain_matching) $host = preg_replace('/^www\./', '', $host); if (!self::$strict_subdomain_matching) {
$host = preg_replace('/^www\./', '', $host);
}
$cacheKey = implode('_', array($host, Member::currentUserID(), self::$check_is_public)); $cacheKey = implode('_', array($host, Member::currentUserID(), self::$check_is_public));
if(isset(self::$_cache_subsite_for_domain[$cacheKey])) return self::$_cache_subsite_for_domain[$cacheKey]; if (isset(self::$_cache_subsite_for_domain[$cacheKey])) {
return self::$_cache_subsite_for_domain[$cacheKey];
}
$SQL_host = Convert::raw2sql($host); $SQL_host = Convert::raw2sql($host);
$matchingDomains = DataObject::get( $matchingDomains = DataObject::get(
@ -209,7 +223,8 @@ class Subsite extends DataObject {
* @param string $limit * @param string $limit
* @return DataList * @return DataList
*/ */
public static function get_from_all_subsites($className, $filter = "", $sort = "", $join = "", $limit = "") { public static function get_from_all_subsites($className, $filter = "", $sort = "", $join = "", $limit = "")
{
$result = DataObject::get($className, $filter, $sort, $join, $limit); $result = DataObject::get($className, $filter, $sort, $join, $limit);
$result = $result->setDataQueryParam('Subsite.filter', false); $result = $result->setDataQueryParam('Subsite.filter', false);
return $result; return $result;
@ -218,14 +233,16 @@ class Subsite extends DataObject {
/** /**
* Disable the sub-site filtering; queries will select from all subsites * Disable the sub-site filtering; queries will select from all subsites
*/ */
public static function disable_subsite_filter($disabled = true) { public static function disable_subsite_filter($disabled = true)
{
self::$disable_subsite_filter = $disabled; self::$disable_subsite_filter = $disabled;
} }
/** /**
* Flush caches on database reset * Flush caches on database reset
*/ */
public static function on_db_reset() { public static function on_db_reset()
{
self::$_cache_accessible_sites = array(); self::$_cache_accessible_sites = array();
self::$_cache_subsite_for_domain = array(); self::$_cache_subsite_for_domain = array();
} }
@ -235,7 +252,8 @@ class Subsite extends DataObject {
* *
* @return SS_List List of {@link Subsite} objects (DataList or ArrayList). * @return SS_List List of {@link Subsite} objects (DataList or ArrayList).
*/ */
public static function all_sites($includeMainSite = true, $mainSiteTitle = "Main site") { public static function all_sites($includeMainSite = true, $mainSiteTitle = "Main site")
{
$subsites = Subsite::get(); $subsites = Subsite::get();
if ($includeMainSite) { if ($includeMainSite) {
@ -257,11 +275,18 @@ class Subsite extends DataObject {
* *
* @return ArrayList of {@link Subsite} instances. * @return ArrayList of {@link Subsite} instances.
*/ */
public static function all_accessible_sites($includeMainSite = true, $mainSiteTitle = "Main site", $member = null) { public static function all_accessible_sites($includeMainSite = true, $mainSiteTitle = "Main site", $member = null)
{
// Rationalise member arguments // Rationalise member arguments
if(!$member) $member = Member::currentUser(); if (!$member) {
if(!$member) return new ArrayList(); $member = Member::currentUser();
if(!is_object($member)) $member = DataObject::get_by_id('Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('Member', $member);
}
$subsites = new ArrayList(); $subsites = new ArrayList();
@ -295,15 +320,25 @@ class Subsite extends DataObject {
* @param $member * @param $member
* @return DataList of {@link Subsite} instances * @return DataList of {@link Subsite} instances
*/ */
public static function accessible_sites($permCode, $includeMainSite = true, $mainSiteTitle = "Main site", $member = null) { public static function accessible_sites($permCode, $includeMainSite = true, $mainSiteTitle = "Main site", $member = null)
{
// Rationalise member arguments // Rationalise member arguments
if(!$member) $member = Member::currentUser(); if (!$member) {
if(!$member) return new ArrayList(); $member = Member::currentUser();
if(!is_object($member)) $member = DataObject::get_by_id('Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('Member', $member);
}
// Rationalise permCode argument // Rationalise permCode argument
if(is_array($permCode)) $SQL_codes = "'" . implode("', '", Convert::raw2sql($permCode)) . "'"; if (is_array($permCode)) {
else $SQL_codes = "'" . Convert::raw2sql($permCode) . "'"; $SQL_codes = "'" . implode("', '", Convert::raw2sql($permCode)) . "'";
} else {
$SQL_codes = "'" . Convert::raw2sql($permCode) . "'";
}
// Cache handling // Cache handling
$cacheKey = $SQL_codes . '-' . $member->ID . '-' . $includeMainSite . '-' . $mainSiteTitle; $cacheKey = $SQL_codes . '-' . $member->ID . '-' . $includeMainSite . '-' . $mainSiteTitle;
@ -318,7 +353,9 @@ class Subsite extends DataObject {
->innerJoin('Group_Members', "\"Group_Members\".\"GroupID\"=\"Group\".\"ID\" AND \"Group_Members\".\"MemberID\" = $member->ID") ->innerJoin('Group_Members', "\"Group_Members\".\"GroupID\"=\"Group\".\"ID\" AND \"Group_Members\".\"MemberID\" = $member->ID")
->innerJoin('Permission', "\"Group\".\"ID\"=\"Permission\".\"GroupID\" AND \"Permission\".\"Code\" IN ($SQL_codes, 'CMS_ACCESS_LeftAndMain', 'ADMIN')"); ->innerJoin('Permission', "\"Group\".\"ID\"=\"Permission\".\"GroupID\" AND \"Permission\".\"Code\" IN ($SQL_codes, 'CMS_ACCESS_LeftAndMain', 'ADMIN')");
if(!$subsites) $subsites = new ArrayList(); if (!$subsites) {
$subsites = new ArrayList();
}
$rolesSubsites = DataList::create('Subsite') $rolesSubsites = DataList::create('Subsite')
->where("\"Subsite\".\"Title\" != ''") ->where("\"Subsite\".\"Title\" != ''")
@ -329,18 +366,24 @@ class Subsite extends DataObject {
->innerJoin('PermissionRole', "\"Group_Roles\".\"PermissionRoleID\"=\"PermissionRole\".\"ID\"") ->innerJoin('PermissionRole', "\"Group_Roles\".\"PermissionRoleID\"=\"PermissionRole\".\"ID\"")
->innerJoin('PermissionRoleCode', "\"PermissionRole\".\"ID\"=\"PermissionRoleCode\".\"RoleID\" AND \"PermissionRoleCode\".\"Code\" IN ($SQL_codes, 'CMS_ACCESS_LeftAndMain', 'ADMIN')"); ->innerJoin('PermissionRoleCode', "\"PermissionRole\".\"ID\"=\"PermissionRoleCode\".\"RoleID\" AND \"PermissionRoleCode\".\"Code\" IN ($SQL_codes, 'CMS_ACCESS_LeftAndMain', 'ADMIN')");
if(!$subsites && $rolesSubsites) return $rolesSubsites; if (!$subsites && $rolesSubsites) {
return $rolesSubsites;
}
$subsites = new ArrayList($subsites->toArray()); $subsites = new ArrayList($subsites->toArray());
if($rolesSubsites) foreach($rolesSubsites as $subsite) { if ($rolesSubsites) {
foreach ($rolesSubsites as $subsite) {
if (!$subsites->find('ID', $subsite->ID)) { if (!$subsites->find('ID', $subsite->ID)) {
$subsites->push($subsite); $subsites->push($subsite);
} }
} }
}
if ($includeMainSite) { if ($includeMainSite) {
if(!is_array($permCode)) $permCode = array($permCode); if (!is_array($permCode)) {
$permCode = array($permCode);
}
if (self::hasMainSitePermission($member, $permCode)) { if (self::hasMainSitePermission($member, $permCode)) {
$subsites=$subsites->toArray(); $subsites=$subsites->toArray();
@ -364,22 +407,35 @@ class Subsite extends DataObject {
* @param string $file - filepath of the host map to be written * @param string $file - filepath of the host map to be written
* @return void * @return void
*/ */
public static function writeHostMap($file = null) { public static function writeHostMap($file = null)
if (!self::$write_hostmap) return; {
if (!self::$write_hostmap) {
return;
}
if (!$file) $file = Director::baseFolder().'/subsites/host-map.php'; if (!$file) {
$file = Director::baseFolder().'/subsites/host-map.php';
}
$hostmap = array(); $hostmap = array();
$subsites = DataObject::get('Subsite'); $subsites = DataObject::get('Subsite');
if ($subsites) foreach($subsites as $subsite) { if ($subsites) {
foreach ($subsites as $subsite) {
$domains = $subsite->Domains(); $domains = $subsite->Domains();
if ($domains) foreach($domains as $domain) { if ($domains) {
foreach ($domains as $domain) {
$domainStr = $domain->Domain; $domainStr = $domain->Domain;
if(!self::$strict_subdomain_matching) $domainStr = preg_replace('/^www\./', '', $domainStr); if (!self::$strict_subdomain_matching) {
$domainStr = preg_replace('/^www\./', '', $domainStr);
}
$hostmap[$domainStr] = $subsite->domain(); $hostmap[$domainStr] = $subsite->domain();
} }
if ($subsite->DefaultSite) $hostmap['default'] = $subsite->domain(); }
if ($subsite->DefaultSite) {
$hostmap['default'] = $subsite->domain();
}
}
} }
$data = "<?php \n"; $data = "<?php \n";
@ -404,15 +460,23 @@ class Subsite extends DataObject {
* @param Array Permission code strings. Defaults to "ADMIN". * @param Array Permission code strings. Defaults to "ADMIN".
* @return boolean * @return boolean
*/ */
public static function hasMainSitePermission($member = null, $permissionCodes = array('ADMIN')) { public static function hasMainSitePermission($member = null, $permissionCodes = array('ADMIN'))
if(!is_array($permissionCodes)) {
if (!is_array($permissionCodes)) {
user_error('Permissions must be passed to Subsite::hasMainSitePermission as an array', E_USER_ERROR); user_error('Permissions must be passed to Subsite::hasMainSitePermission as an array', E_USER_ERROR);
}
if(!$member && $member !== FALSE) $member = Member::currentUser(); if (!$member && $member !== false) {
$member = Member::currentUser();
}
if(!$member) return false; if (!$member) {
return false;
}
if(!in_array("ADMIN", $permissionCodes)) $permissionCodes[] = "ADMIN"; if (!in_array("ADMIN", $permissionCodes)) {
$permissionCodes[] = "ADMIN";
}
$SQLa_perm = Convert::raw2sql($permissionCodes); $SQLa_perm = Convert::raw2sql($permissionCodes);
$SQL_perms = join("','", $SQLa_perm); $SQL_perms = join("','", $SQLa_perm);
@ -508,7 +572,8 @@ class Subsite extends DataObject {
* @todo Possible security issue, don't grant edit permissions to everybody. * @todo Possible security issue, don't grant edit permissions to everybody.
* @return boolean * @return boolean
*/ */
public function canEdit($member = false) { public function canEdit($member = false)
{
return true; return true;
} }
@ -517,7 +582,8 @@ class Subsite extends DataObject {
* *
* @return FieldList * @return FieldList
*/ */
public function getCMSFields() { public function getCMSFields()
{
if ($this->ID!=0) { if ($this->ID!=0) {
$domainTable = new GridField( $domainTable = new GridField(
"Domains", "Domains",
@ -594,7 +660,8 @@ class Subsite extends DataObject {
* @param boolean $includerelations * @param boolean $includerelations
* @return array * @return array
*/ */
public function fieldLabels($includerelations = true) { public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['Title'] = _t('Subsites.TitleFieldLabel', 'Subsite Name'); $labels['Title'] = _t('Subsites.TitleFieldLabel', 'Subsite Name');
$labels['RedirectURL'] = _t('Subsites.RedirectURLFieldLabel', 'Redirect URL'); $labels['RedirectURL'] = _t('Subsites.RedirectURLFieldLabel', 'Redirect URL');
@ -613,7 +680,8 @@ class Subsite extends DataObject {
* *
* @return array * @return array
*/ */
public function summaryFields() { public function summaryFields()
{
return array( return array(
'Title' => $this->fieldLabel('Title'), 'Title' => $this->fieldLabel('Title'),
'PrimaryDomain' => $this->fieldLabel('PrimaryDomain'), 'PrimaryDomain' => $this->fieldLabel('PrimaryDomain'),
@ -626,14 +694,17 @@ class Subsite extends DataObject {
* *
* @return array * @return array
*/ */
public function allowedThemes() { public function allowedThemes()
{
if ($themes = $this->stat('allowed_themes')) { if ($themes = $this->stat('allowed_themes')) {
return ArrayLib::valuekey($themes); return ArrayLib::valuekey($themes);
} else { } else {
$themes = array(); $themes = array();
if (is_dir('../themes/')) { if (is_dir('../themes/')) {
foreach (scandir('../themes/') as $theme) { foreach (scandir('../themes/') as $theme) {
if($theme[0] == '.') continue; if ($theme[0] == '.') {
continue;
}
$theme = strtok($theme, '_'); $theme = strtok($theme, '_');
$themes[$theme] = $theme; $themes[$theme] = $theme;
} }
@ -646,7 +717,8 @@ class Subsite extends DataObject {
/** /**
* @return string Current locale of the subsite * @return string Current locale of the subsite
*/ */
public function getLanguage() { public function getLanguage()
{
if ($this->getField('Language')) { if ($this->getField('Language')) {
return $this->getField('Language'); return $this->getField('Language');
} else { } else {
@ -658,7 +730,8 @@ class Subsite extends DataObject {
* *
* @return ValidationResult * @return ValidationResult
*/ */
public function validate() { public function validate()
{
$result = parent::validate(); $result = parent::validate();
if (!$this->Title) { if (!$this->Title) {
$result->error(_t('Subsite.ValidateTitle', 'Please add a "Title"')); $result->error(_t('Subsite.ValidateTitle', 'Please add a "Title"'));
@ -671,7 +744,8 @@ class Subsite extends DataObject {
* *
* @return void * @return void
*/ */
public function onAfterWrite() { public function onAfterWrite()
{
Subsite::writeHostMap(); Subsite::writeHostMap();
parent::onAfterWrite(); parent::onAfterWrite();
} }
@ -682,7 +756,8 @@ class Subsite extends DataObject {
* *
* @return string The full domain name of this subsite (without protocol prefix) * @return string The full domain name of this subsite (without protocol prefix)
*/ */
public function domain() { public function domain()
{
if ($this->ID) { if ($this->ID) {
$domains = DataObject::get("SubsiteDomain", "\"SubsiteID\" = $this->ID", "\"IsPrimary\" DESC", "", 1); $domains = DataObject::get("SubsiteDomain", "\"SubsiteID\" = $this->ID", "\"IsPrimary\" DESC", "", 1);
if ($domains && $domains->Count()>0) { if ($domains && $domains->Count()>0) {
@ -709,7 +784,8 @@ class Subsite extends DataObject {
* *
* @return string - The full domain name of this subsite (without protocol prefix) * @return string - The full domain name of this subsite (without protocol prefix)
*/ */
public function getPrimaryDomain() { public function getPrimaryDomain()
{
return $this->domain(); return $this->domain();
} }
@ -717,14 +793,16 @@ class Subsite extends DataObject {
* *
* @return string * @return string
*/ */
public function absoluteBaseURL() { public function absoluteBaseURL()
{
return "http://" . $this->domain() . Director::baseURL(); return "http://" . $this->domain() . Director::baseURL();
} }
/** /**
* @todo getClassName is redundant, already stored as a database field? * @todo getClassName is redundant, already stored as a database field?
*/ */
public function getClassName() { public function getClassName()
{
return $this->class; return $this->class;
} }
@ -733,7 +811,8 @@ class Subsite extends DataObject {
* *
* @return string - javascript * @return string - javascript
*/ */
public function adminDuplicate() { public function adminDuplicate()
{
$newItem = $this->duplicate(); $newItem = $this->duplicate();
$message = _t( $message = _t(
'Subsite.CopyMessage', 'Subsite.CopyMessage',
@ -750,7 +829,8 @@ JS;
/** /**
* Make this subsite the current one * Make this subsite the current one
*/ */
public function activate() { public function activate()
{
Subsite::changeSubsite($this); Subsite::changeSubsite($this);
} }
@ -759,9 +839,11 @@ JS;
* @param array $permissionCodes * @param array $permissionCodes
* @return DataList * @return DataList
*/ */
public function getMembersByPermission($permissionCodes = array('ADMIN')){ public function getMembersByPermission($permissionCodes = array('ADMIN'))
if(!is_array($permissionCodes)) {
if (!is_array($permissionCodes)) {
user_error('Permissions must be passed to Subsite::getMembersByPermission as an array', E_USER_ERROR); user_error('Permissions must be passed to Subsite::getMembersByPermission as an array', E_USER_ERROR);
}
$SQL_permissionCodes = Convert::raw2sql($permissionCodes); $SQL_permissionCodes = Convert::raw2sql($permissionCodes);
$SQL_permissionCodes = join("','", $SQL_permissionCodes); $SQL_permissionCodes = join("','", $SQL_permissionCodes);
@ -774,13 +856,13 @@ JS;
LEFT JOIN \"Group\" ON \"Group\".\"ID\" = \"Group_Members\".\"GroupID\" LEFT JOIN \"Group\" ON \"Group\".\"ID\" = \"Group_Members\".\"GroupID\"
LEFT JOIN \"Permission\" ON \"Permission\".\"GroupID\" = \"Group\".\"ID\"" LEFT JOIN \"Permission\" ON \"Permission\".\"GroupID\" = \"Group\".\"ID\""
); );
} }
/** /**
* Duplicate this subsite * Duplicate this subsite
*/ */
public function duplicate($doWrite = true) { public function duplicate($doWrite = true)
{
$duplicate = parent::duplicate($doWrite); $duplicate = parent::duplicate($doWrite);
$oldSubsiteID = Session::get('SubsiteID'); $oldSubsiteID = Session::get('SubsiteID');

View File

@ -4,8 +4,8 @@
* @property text Domain domain name of this subsite. Do not include the URL scheme here * @property text Domain domain name of this subsite. Do not include the URL scheme here
* @property bool IsPrimary Is this the primary subdomain? * @property bool IsPrimary Is this the primary subdomain?
*/ */
class SubsiteDomain extends DataObject { class SubsiteDomain extends DataObject
{
/** /**
* *
* @var array * @var array
@ -37,7 +37,8 @@ class SubsiteDomain extends DataObject {
* *
* @return void * @return void
*/ */
public function onAfterWrite() { public function onAfterWrite()
{
Subsite::writeHostMap(); Subsite::writeHostMap();
} }
@ -45,7 +46,8 @@ class SubsiteDomain extends DataObject {
* *
* @return \FieldList * @return \FieldList
*/ */
public function getCMSFields() { public function getCMSFields()
{
$fields = new FieldList( $fields = new FieldList(
new TextField('Domain', $this->fieldLabel('Domain'), null, 255), new TextField('Domain', $this->fieldLabel('Domain'), null, 255),
new CheckboxField('IsPrimary', $this->fieldLabel('IsPrimary')) new CheckboxField('IsPrimary', $this->fieldLabel('IsPrimary'))
@ -60,7 +62,8 @@ class SubsiteDomain extends DataObject {
* @param bool $includerelations * @param bool $includerelations
* @return array * @return array
*/ */
public function fieldLabels($includerelations = true) { public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['Domain'] = _t('SubsiteDomain.DOMAIN', 'Domain'); $labels['Domain'] = _t('SubsiteDomain.DOMAIN', 'Domain');
$labels['IsPrimary'] = _t('SubsiteDomain.IS_PRIMARY', 'Is Primary Domain'); $labels['IsPrimary'] = _t('SubsiteDomain.IS_PRIMARY', 'Is Primary Domain');
@ -72,7 +75,8 @@ class SubsiteDomain extends DataObject {
* Before writing the Subsite Domain, strip out any HTML the user has entered. * Before writing the Subsite Domain, strip out any HTML the user has entered.
* @return void * @return void
*/ */
public function onBeforeWrite() { public function onBeforeWrite()
{
parent::onBeforeWrite(); parent::onBeforeWrite();
//strip out any HTML to avoid XSS attacks //strip out any HTML to avoid XSS attacks

View File

@ -6,22 +6,31 @@
* *
* Example: sake dev/tasks/SubsiteCopyPagesTask from=<subsite-source> to=<subsite-target> * Example: sake dev/tasks/SubsiteCopyPagesTask from=<subsite-source> to=<subsite-target>
*/ */
class SubsiteCopyPagesTask extends BuildTask { class SubsiteCopyPagesTask extends BuildTask
{
protected $title = 'Copy pages to different subsite'; protected $title = 'Copy pages to different subsite';
protected $description = ''; protected $description = '';
function run($request) { public function run($request)
{
$subsiteFromId = $request->getVar('from'); $subsiteFromId = $request->getVar('from');
if(!is_numeric($subsiteFromId)) throw new InvalidArgumentException('Missing "from" parameter'); if (!is_numeric($subsiteFromId)) {
throw new InvalidArgumentException('Missing "from" parameter');
}
$subsiteFrom = DataObject::get_by_id('Subsite', $subsiteFromId); $subsiteFrom = DataObject::get_by_id('Subsite', $subsiteFromId);
if(!$subsiteFrom) throw new InvalidArgumentException('Subsite not found'); if (!$subsiteFrom) {
throw new InvalidArgumentException('Subsite not found');
}
$subsiteToId = $request->getVar('to'); $subsiteToId = $request->getVar('to');
if(!is_numeric($subsiteToId)) throw new InvalidArgumentException('Missing "to" parameter'); if (!is_numeric($subsiteToId)) {
throw new InvalidArgumentException('Missing "to" parameter');
}
$subsiteTo = DataObject::get_by_id('Subsite', $subsiteToId); $subsiteTo = DataObject::get_by_id('Subsite', $subsiteToId);
if(!$subsiteTo) throw new InvalidArgumentException('Subsite not found'); if (!$subsiteTo) {
throw new InvalidArgumentException('Subsite not found');
}
$useVirtualPages = (bool)$request->getVar('virtual'); $useVirtualPages = (bool)$request->getVar('virtual');
@ -61,7 +70,8 @@ class SubsiteCopyPagesTask extends BuildTask {
} }
} }
function log($msg) { public function log($msg)
{
echo $msg . "\n"; echo $msg . "\n";
} }
} }

View File

@ -1,7 +1,8 @@
<?php <?php
class BaseSubsiteTest extends SapphireTest { class BaseSubsiteTest extends SapphireTest
{
function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Subsite::$use_session_subsiteid = true; Subsite::$use_session_subsiteid = true;
@ -10,7 +11,8 @@ class BaseSubsiteTest extends SapphireTest {
/** /**
* Avoid subsites filtering on fixture fetching. * Avoid subsites filtering on fixture fetching.
*/ */
function objFromFixture($class, $id) { public function objFromFixture($class, $id)
{
Subsite::disable_subsite_filter(true); Subsite::disable_subsite_filter(true);
$obj = parent::objFromFixture($class, $id); $obj = parent::objFromFixture($class, $id);
Subsite::disable_subsite_filter(false); Subsite::disable_subsite_filter(false);
@ -21,8 +23,8 @@ class BaseSubsiteTest extends SapphireTest {
/** /**
* Tests the initial state of disable_subsite_filter * Tests the initial state of disable_subsite_filter
*/ */
function testDisableSubsiteFilter() { public function testDisableSubsiteFilter()
{
$this->assertFalse(Subsite::$disable_subsite_filter); $this->assertFalse(Subsite::$disable_subsite_filter);
} }
} }

View File

@ -1,9 +1,11 @@
<?php <?php
class FileSubsitesTest extends BaseSubsiteTest { class FileSubsitesTest extends BaseSubsiteTest
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; {
public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function testTrivialFeatures() { public function testTrivialFeatures()
{
$this->assertTrue(is_array(singleton('FileSubsites')->extraStatics())); $this->assertTrue(is_array(singleton('FileSubsites')->extraStatics()));
$file = new File(); $file = new File();
$file->Name = 'FileTitle'; $file->Name = 'FileTitle';
@ -16,7 +18,8 @@ class FileSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($file->cacheKeyComponent(), 'subsite-1'); $this->assertEquals($file->cacheKeyComponent(), 'subsite-1');
} }
function testWritingSubsiteID() { public function testWritingSubsiteID()
{
$this->objFromFixture('Member', 'admin')->logIn(); $this->objFromFixture('Member', 'admin')->logIn();
$subsite = $this->objFromFixture('Subsite', 'domaintest1'); $subsite = $this->objFromFixture('Subsite', 'domaintest1');
@ -54,7 +57,8 @@ class FileSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($folder->SubsiteID, $file->SubsiteID); $this->assertEquals($folder->SubsiteID, $file->SubsiteID);
} }
function testSubsitesFolderDropdown() { public function testSubsitesFolderDropdown()
{
$this->objFromFixture('Member', 'admin')->logIn(); $this->objFromFixture('Member', 'admin')->logIn();
$file = new Folder(); $file = new Folder();
@ -72,5 +76,4 @@ class FileSubsitesTest extends BaseSubsiteTest {
'Test 3' 'Test 3'
), $source); ), $source);
} }
} }

View File

@ -1,17 +1,20 @@
<?php <?php
class GroupSubsitesTest extends BaseSubsiteTest { class GroupSubsitesTest extends BaseSubsiteTest
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; {
public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
protected $requireDefaultRecordsFrom = array('GroupSubsites'); protected $requireDefaultRecordsFrom = array('GroupSubsites');
function testTrivialFeatures() { public function testTrivialFeatures()
{
$this->assertTrue(is_array(singleton('GroupSubsites')->extraStatics())); $this->assertTrue(is_array(singleton('GroupSubsites')->extraStatics()));
$this->assertTrue(is_array(singleton('GroupSubsites')->providePermissions())); $this->assertTrue(is_array(singleton('GroupSubsites')->providePermissions()));
$this->assertTrue(singleton('Group')->getCMSFields() instanceof FieldList); $this->assertTrue(singleton('Group')->getCMSFields() instanceof FieldList);
} }
function testAlternateTreeTitle() { public function testAlternateTreeTitle()
{
$group = new Group(); $group = new Group();
$group->Title = 'The A Team'; $group->Title = 'The A Team';
$group->AccessAllSubsites = true; $group->AccessAllSubsites = true;

View File

@ -1,13 +1,14 @@
<?php <?php
class LeftAndMainSubsitesTest extends FunctionalTest { class LeftAndMainSubsitesTest extends FunctionalTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
/** /**
* Avoid subsites filtering on fixture fetching. * Avoid subsites filtering on fixture fetching.
*/ */
function objFromFixture($class, $id) { public function objFromFixture($class, $id)
{
Subsite::disable_subsite_filter(true); Subsite::disable_subsite_filter(true);
$obj = parent::objFromFixture($class, $id); $obj = parent::objFromFixture($class, $id);
Subsite::disable_subsite_filter(false); Subsite::disable_subsite_filter(false);
@ -15,7 +16,8 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
return $obj; return $obj;
} }
function testSectionSites() { public function testSectionSites()
{
$member = $this->objFromFixture('Member', 'subsite1member'); $member = $this->objFromFixture('Member', 'subsite1member');
$cmsmain = singleton('CMSMain'); $cmsmain = singleton('CMSMain');
@ -37,7 +39,8 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
), $subsites, 'Includes the main site for members who can access all sites.'); ), $subsites, 'Includes the main site for members who can access all sites.');
} }
function testAccessChecksDontChangeCurrentSubsite() { public function testAccessChecksDontChangeCurrentSubsite()
{
$admin = $this->objFromFixture("Member", "admin"); $admin = $this->objFromFixture("Member", "admin");
$this->loginAs($admin); $this->loginAs($admin);
$ids = array(); $ids = array();
@ -63,10 +66,10 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
$this->assertEquals($id, Subsite::currentSubsiteID(), $this->assertEquals($id, Subsite::currentSubsiteID(),
"The current subsite has not been changed in the process of checking permissions for admin user."); "The current subsite has not been changed in the process of checking permissions for admin user.");
} }
} }
function testShouldChangeSubsite() { public function testShouldChangeSubsite()
{
$l = new LeftAndMain(); $l = new LeftAndMain();
Config::inst()->nest(); Config::inst()->nest();
@ -84,5 +87,4 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
Config::inst()->unnest(); Config::inst()->unnest();
} }
} }

View File

@ -1,9 +1,11 @@
<?php <?php
class SiteConfigSubsitesTest extends BaseSubsiteTest { class SiteConfigSubsitesTest extends BaseSubsiteTest
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; {
public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function testEachSubsiteHasAUniqueSiteConfig() { public function testEachSubsiteHasAUniqueSiteConfig()
{
$subsite1 = $this->objFromFixture('Subsite', 'domaintest1'); $subsite1 = $this->objFromFixture('Subsite', 'domaintest1');
$subsite2 = $this->objFromFixture('Subsite', 'domaintest2'); $subsite2 = $this->objFromFixture('Subsite', 'domaintest2');
@ -34,5 +36,4 @@ class SiteConfigSubsitesTest extends BaseSubsiteTest {
$keys = SiteConfig::current_site_config()->extend('cacheKeyComponent'); $keys = SiteConfig::current_site_config()->extend('cacheKeyComponent');
$this->assertContains('subsite-' . $subsite2->ID, $keys); $this->assertContains('subsite-' . $subsite2->ID, $keys);
} }
} }

View File

@ -1,8 +1,8 @@
<?php <?php
class SiteTreeSubsitesTest extends BaseSubsiteTest { class SiteTreeSubsitesTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
protected $extraDataObjects = array( protected $extraDataObjects = array(
'SiteTreeSubsitesTest_ClassA', 'SiteTreeSubsitesTest_ClassA',
@ -13,7 +13,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
'SiteTree' => array('Translatable') 'SiteTree' => array('Translatable')
); );
function testPagesInDifferentSubsitesCanShareURLSegment() { public function testPagesInDifferentSubsitesCanShareURLSegment()
{
$subsiteMain = $this->objFromFixture('Subsite', 'main'); $subsiteMain = $this->objFromFixture('Subsite', 'main');
$subsite1 = $this->objFromFixture('Subsite', 'subsite1'); $subsite1 = $this->objFromFixture('Subsite', 'subsite1');
@ -43,7 +44,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
); );
} }
function testBasicSanity() { public function testBasicSanity()
{
$this->assertTrue(singleton('SiteTree')->getSiteConfig() instanceof SiteConfig); $this->assertTrue(singleton('SiteTree')->getSiteConfig() instanceof SiteConfig);
// The following assert is breaking in Translatable. // The following assert is breaking in Translatable.
$this->assertTrue(singleton('SiteTree')->getCMSFields() instanceof FieldList); $this->assertTrue(singleton('SiteTree')->getCMSFields() instanceof FieldList);
@ -51,7 +53,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
$this->assertTrue(is_array(singleton('SiteTreeSubsites')->extraStatics())); $this->assertTrue(is_array(singleton('SiteTreeSubsites')->extraStatics()));
} }
function testErrorPageLocations() { public function testErrorPageLocations()
{
$subsite1 = $this->objFromFixture('Subsite', 'domaintest1'); $subsite1 = $this->objFromFixture('Subsite', 'domaintest1');
Subsite::changeSubsite($subsite1->ID); Subsite::changeSubsite($subsite1->ID);
@ -62,7 +65,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($expected_path, $path); $this->assertEquals($expected_path, $path);
} }
function testCanEditSiteTree() { public function testCanEditSiteTree()
{
$admin = $this->objFromFixture('Member', 'admin'); $admin = $this->objFromFixture('Member', 'admin');
$subsite1member = $this->objFromFixture('Member', 'subsite1member'); $subsite1member = $this->objFromFixture('Member', 'subsite1member');
$subsite2member = $this->objFromFixture('Member', 'subsite2member'); $subsite2member = $this->objFromFixture('Member', 'subsite2member');
@ -105,7 +109,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
/** /**
* Similar to {@link SubsitesVirtualPageTest->testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()}. * Similar to {@link SubsitesVirtualPageTest->testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()}.
*/ */
function testTwoPagesWithSameURLOnDifferentSubsites() { public function testTwoPagesWithSameURLOnDifferentSubsites()
{
// Set up a couple of pages with the same URL on different subsites // Set up a couple of pages with the same URL on different subsites
$s1 = $this->objFromFixture('Subsite', 'domaintest1'); $s1 = $this->objFromFixture('Subsite', 'domaintest1');
$s2 = $this->objFromFixture('Subsite', 'domaintest2'); $s2 = $this->objFromFixture('Subsite', 'domaintest2');
@ -132,7 +137,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($p2->ID, SiteTree::get_by_link('test-page')->ID); $this->assertEquals($p2->ID, SiteTree::get_by_link('test-page')->ID);
} }
function testPageTypesBlacklistInClassDropdown() { public function testPageTypesBlacklistInClassDropdown()
{
$editor = $this->objFromFixture('Member', 'editor'); $editor = $this->objFromFixture('Member', 'editor');
Session::set("loggedInAs", $editor->ID); Session::set("loggedInAs", $editor->ID);
@ -169,7 +175,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
); );
} }
function testPageTypesBlacklistInCMSMain() { public function testPageTypesBlacklistInCMSMain()
{
$editor = $this->objFromFixture('Member', 'editor'); $editor = $this->objFromFixture('Member', 'editor');
Session::set("loggedInAs", $editor->ID); Session::set("loggedInAs", $editor->ID);
@ -195,9 +202,12 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
$this->assertNotContains('SiteTreeSubsitesTest_ClassA', $classes); $this->assertNotContains('SiteTreeSubsitesTest_ClassA', $classes);
$this->assertNotContains('SiteTreeSubsitesTest_ClassB', $classes); $this->assertNotContains('SiteTreeSubsitesTest_ClassB', $classes);
} }
} }
class SiteTreeSubsitesTest_ClassA extends SiteTree implements TestOnly {} class SiteTreeSubsitesTest_ClassA extends SiteTree implements TestOnly
{
}
class SiteTreeSubsitesTest_ClassB extends SiteTree implements TestOnly {} class SiteTreeSubsitesTest_ClassB extends SiteTree implements TestOnly
{
}

View File

@ -1,15 +1,17 @@
<?php <?php
class SubsiteAdminFunctionalTest extends FunctionalTest { class SubsiteAdminFunctionalTest extends FunctionalTest
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; {
static $use_draft_site = true; public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
public static $use_draft_site = true;
protected $autoFollowRedirection = false; protected $autoFollowRedirection = false;
/** /**
* Helper: FunctionalTest is only able to follow redirection once, we want to go all the way. * Helper: FunctionalTest is only able to follow redirection once, we want to go all the way.
*/ */
function getAndFollowAll($url) { public function getAndFollowAll($url)
{
$response = $this->get($url); $response = $this->get($url);
while ($location = $response->getHeader('Location')) { while ($location = $response->getHeader('Location')) {
$response = $this->mainSession->followRedirection(); $response = $this->mainSession->followRedirection();
@ -22,7 +24,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
/** /**
* Anonymous user cannot access anything. * Anonymous user cannot access anything.
*/ */
function testAnonymousIsForbiddenAdminAccess() { public function testAnonymousIsForbiddenAdminAccess()
{
$response = $this->getAndFollowAll('admin/pages/?SubsiteID=0'); $response = $this->getAndFollowAll('admin/pages/?SubsiteID=0');
$this->assertRegExp('#^Security/login.*#', $this->mainSession->lastUrl(), 'Admin is disallowed'); $this->assertRegExp('#^Security/login.*#', $this->mainSession->lastUrl(), 'Admin is disallowed');
@ -38,7 +41,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
/** /**
* Admin should be able to access all subsites and the main site * Admin should be able to access all subsites and the main site
*/ */
function testAdminCanAccessAllSubsites() { public function testAdminCanAccessAllSubsites()
{
$member = $this->objFromFixture('Member', 'admin'); $member = $this->objFromFixture('Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -56,7 +60,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
'SubsiteXHRController is reachable'); 'SubsiteXHRController is reachable');
} }
function testAdminIsRedirectedToObjectsSubsite() { public function testAdminIsRedirectedToObjectsSubsite()
{
$member = $this->objFromFixture('Member', 'admin'); $member = $this->objFromFixture('Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -88,7 +93,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
* User which has AccessAllSubsites set to 1 should be able to access all subsites and main site, * User which has AccessAllSubsites set to 1 should be able to access all subsites and main site,
* even though he does not have the ADMIN permission. * even though he does not have the ADMIN permission.
*/ */
function testEditorCanAccessAllSubsites() { public function testEditorCanAccessAllSubsites()
{
$member = $this->objFromFixture('Member', 'editor'); $member = $this->objFromFixture('Member', 'editor');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -109,7 +115,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
/** /**
* Test a member who only has access to one subsite (subsite1) and only some sections (pages and security). * Test a member who only has access to one subsite (subsite1) and only some sections (pages and security).
*/ */
function testSubsiteAdmin() { public function testSubsiteAdmin()
{
$member = $this->objFromFixture('Member', 'subsite1member'); $member = $this->objFromFixture('Member', 'subsite1member');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);

View File

@ -1,9 +1,11 @@
<?php <?php
class SubsiteAdminTest extends BaseSubsiteTest { class SubsiteAdminTest extends BaseSubsiteTest
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; {
public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function adminLoggedInSession() { public function adminLoggedInSession()
{
return new Session(array( return new Session(array(
'loggedInAs' => $this->idFromFixture('Member', 'admin') 'loggedInAs' => $this->idFromFixture('Member', 'admin')
)); ));
@ -12,7 +14,8 @@ class SubsiteAdminTest extends BaseSubsiteTest {
/** /**
* Test generation of the view * Test generation of the view
*/ */
function testBasicView() { public function testBasicView()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite1ID = $this->objFromFixture('Subsite', 'domaintest1')->ID; $subsite1ID = $this->objFromFixture('Subsite', 'domaintest1')->ID;
@ -30,7 +33,8 @@ class SubsiteAdminTest extends BaseSubsiteTest {
* Test that the main-site user with ADMIN permissions can access all subsites, regardless * Test that the main-site user with ADMIN permissions can access all subsites, regardless
* of whether he is in a subsite-specific group or not. * of whether he is in a subsite-specific group or not.
*/ */
function testMainsiteAdminCanAccessAllSubsites() { public function testMainsiteAdminCanAccessAllSubsites()
{
$member = $this->objFromFixture('Member', 'admin'); $member = $this->objFromFixture('Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -44,7 +48,4 @@ class SubsiteAdminTest extends BaseSubsiteTest {
$this->assertArrayHasKey($this->idFromFixture('Subsite', 'subsite1'), $ids, "Subsite1 Template inaccessible"); $this->assertArrayHasKey($this->idFromFixture('Subsite', 'subsite1'), $ids, "Subsite1 Template inaccessible");
$this->assertArrayHasKey($this->idFromFixture('Subsite', 'subsite2'), $ids, "Subsite2 Template inaccessible"); $this->assertArrayHasKey($this->idFromFixture('Subsite', 'subsite2'), $ids, "Subsite2 Template inaccessible");
} }
} }

View File

@ -1,17 +1,19 @@
<?php <?php
class SubsiteTest extends BaseSubsiteTest { class SubsiteTest extends BaseSubsiteTest
{
public static $fixture_file = 'subsites/tests/SubsiteTest.yml';
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; public function setUp()
{
function setUp() {
parent::setUp(); parent::setUp();
$this->origStrictSubdomainMatching = Subsite::$strict_subdomain_matching; $this->origStrictSubdomainMatching = Subsite::$strict_subdomain_matching;
Subsite::$strict_subdomain_matching = false; Subsite::$strict_subdomain_matching = false;
} }
function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Subsite::$strict_subdomain_matching = $this->origStrictSubdomainMatching; Subsite::$strict_subdomain_matching = $this->origStrictSubdomainMatching;
@ -20,7 +22,8 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Create a new subsite from the template and verify that all the template's pages are copied * Create a new subsite from the template and verify that all the template's pages are copied
*/ */
function testSubsiteCreation() { public function testSubsiteCreation()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
// Create the instance // Create the instance
@ -60,10 +63,15 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Confirm that domain lookup is working * Confirm that domain lookup is working
*/ */
function testDomainLookup() { public function testDomainLookup()
{
// Clear existing fixtures // Clear existing fixtures
foreach(DataObject::get('Subsite') as $subsite) $subsite->delete(); foreach (DataObject::get('Subsite') as $subsite) {
foreach(DataObject::get('SubsiteDomain') as $domain) $domain->delete(); $subsite->delete();
}
foreach (DataObject::get('SubsiteDomain') as $domain) {
$domain->delete();
}
// Much more expressive than YML in this case // Much more expressive than YML in this case
$subsite1 = $this->createSubsiteWithDomains(array( $subsite1 = $this->createSubsiteWithDomains(array(
@ -127,13 +135,17 @@ class SubsiteTest extends BaseSubsiteTest {
Subsite::getSubsiteIDForDomain('unknown.madeup.com'), Subsite::getSubsiteIDForDomain('unknown.madeup.com'),
"Doesn't match unknown subsite" "Doesn't match unknown subsite"
); );
} }
function testStrictSubdomainMatching() { public function testStrictSubdomainMatching()
{
// Clear existing fixtures // Clear existing fixtures
foreach(DataObject::get('Subsite') as $subsite) $subsite->delete(); foreach (DataObject::get('Subsite') as $subsite) {
foreach(DataObject::get('SubsiteDomain') as $domain) $domain->delete(); $subsite->delete();
}
foreach (DataObject::get('SubsiteDomain') as $domain) {
$domain->delete();
}
// Much more expressive than YML in this case // Much more expressive than YML in this case
$subsite1 = $this->createSubsiteWithDomains(array( $subsite1 = $this->createSubsiteWithDomains(array(
@ -196,10 +208,10 @@ class SubsiteTest extends BaseSubsiteTest {
$failed, $failed,
'Fails on multiple matches with strict checking and wildcard vs. www' 'Fails on multiple matches with strict checking and wildcard vs. www'
); );
} }
protected function createSubsiteWithDomains($domains) { protected function createSubsiteWithDomains($domains)
{
$subsite = new Subsite(array( $subsite = new Subsite(array(
'Title' => 'My Subsite' 'Title' => 'My Subsite'
)); ));
@ -219,7 +231,8 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Test the Subsite->domain() method * Test the Subsite->domain() method
*/ */
function testDefaultDomain() { public function testDefaultDomain()
{
$this->assertEquals('one.example.org', $this->assertEquals('one.example.org',
$this->objFromFixture('Subsite', 'domaintest1')->domain()); $this->objFromFixture('Subsite', 'domaintest1')->domain());
@ -242,7 +255,8 @@ class SubsiteTest extends BaseSubsiteTest {
$_SERVER['HTTP_HOST'] = $originalHTTPHost; $_SERVER['HTTP_HOST'] = $originalHTTPHost;
} }
function testAllSites() { public function testAllSites()
{
$subsites = Subsite::all_sites(); $subsites = Subsite::all_sites();
$this->assertDOSEquals(array( $this->assertDOSEquals(array(
array('Title' =>'Main site'), array('Title' =>'Main site'),
@ -255,7 +269,8 @@ class SubsiteTest extends BaseSubsiteTest {
), $subsites, 'Lists all subsites'); ), $subsites, 'Lists all subsites');
} }
function testAllAccessibleSites() { public function testAllAccessibleSites()
{
$member = $this->objFromFixture('Member', 'subsite1member'); $member = $this->objFromFixture('Member', 'subsite1member');
$subsites = Subsite::all_accessible_sites(true, 'Main site', $member); $subsites = Subsite::all_accessible_sites(true, 'Main site', $member);
@ -267,7 +282,8 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Test Subsite::accessible_sites() * Test Subsite::accessible_sites()
*/ */
function testAccessibleSites() { public function testAccessibleSites()
{
$member1Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null, $member1Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null,
$this->objFromFixture('Member', 'subsite1member')); $this->objFromFixture('Member', 'subsite1member'));
$member1SiteTitles = $member1Sites->column("Title"); $member1SiteTitles = $member1Sites->column("Title");
@ -294,7 +310,8 @@ class SubsiteTest extends BaseSubsiteTest {
$this->assertEquals('Subsite1 Template', $member2SiteTitles[0], 'Member can get to subsite via a group role'); $this->assertEquals('Subsite1 Template', $member2SiteTitles[0], 'Member can get to subsite via a group role');
} }
function testhasMainSitePermission() { public function testhasMainSitePermission()
{
$admin = $this->objFromFixture('Member', 'admin'); $admin = $this->objFromFixture('Member', 'admin');
$subsite1member = $this->objFromFixture('Member', 'subsite1member'); $subsite1member = $this->objFromFixture('Member', 'subsite1member');
$subsite1admin = $this->objFromFixture('Member', 'subsite1admin'); $subsite1admin = $this->objFromFixture('Member', 'subsite1admin');
@ -334,7 +351,8 @@ class SubsiteTest extends BaseSubsiteTest {
); );
} }
function testDuplicateSubsite() { public function testDuplicateSubsite()
{
// get subsite1 & create page // get subsite1 & create page
$subsite1 = $this->objFromFixture('Subsite', 'domaintest1'); $subsite1 = $this->objFromFixture('Subsite', 'domaintest1');
$subsite1->activate(); $subsite1->activate();

View File

@ -1,12 +1,14 @@
<?php <?php
class SubsitesVirtualPageTest extends BaseSubsiteTest { class SubsitesVirtualPageTest extends BaseSubsiteTest
static $fixture_file = array( {
public static $fixture_file = array(
'subsites/tests/SubsiteTest.yml', 'subsites/tests/SubsiteTest.yml',
'subsites/tests/SubsitesVirtualPageTest.yml', 'subsites/tests/SubsitesVirtualPageTest.yml',
); );
function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
@ -15,7 +17,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
fclose($fh); fclose($fh);
} }
function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
$testFiles = array( $testFiles = array(
'/assets/testscript-test-file.pdf', '/assets/testscript-test-file.pdf',
@ -23,12 +26,15 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
'/assets/renamed-test-file-second-time.pdf', '/assets/renamed-test-file-second-time.pdf',
); );
foreach ($testFiles as $file) { foreach ($testFiles as $file) {
if(file_exists(Director::baseFolder().$file)) unlink(Director::baseFolder().$file); if (file_exists(Director::baseFolder().$file)) {
unlink(Director::baseFolder().$file);
}
} }
} }
// Attempt to bring main:linky to subsite2:linky // Attempt to bring main:linky to subsite2:linky
function testVirtualPageFromAnotherSubsite() { public function testVirtualPageFromAnotherSubsite()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite = $this->objFromFixture('Subsite', 'subsite2'); $subsite = $this->objFromFixture('Subsite', 'subsite2');
@ -49,7 +55,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
$this->assertEquals($svp->Title, $linky->Title); $this->assertEquals($svp->Title, $linky->Title);
} }
function testFileLinkRewritingOnVirtualPages() { public function testFileLinkRewritingOnVirtualPages()
{
// File setup // File setup
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
touch(Director::baseFolder() . '/assets/testscript-test-file.pdf'); touch(Director::baseFolder() . '/assets/testscript-test-file.pdf');
@ -81,11 +88,14 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
'/assets/renamed-test-file.pdf', '/assets/renamed-test-file.pdf',
); );
foreach ($testFiles as $file) { foreach ($testFiles as $file) {
if(file_exists(Director::baseFolder().$file)) unlink(Director::baseFolder().$file); if (file_exists(Director::baseFolder().$file)) {
unlink(Director::baseFolder().$file);
}
} }
} }
function testSubsiteVirtualPagesArentInappropriatelyPublished() { public function testSubsiteVirtualPagesArentInappropriatelyPublished()
{
// Fixture // Fixture
$p = new Page(); $p = new Page();
$p->Content = "test content"; $p->Content = "test content";
@ -143,7 +153,7 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
* is in a different subsite to the page you are editing and republishing, * is in a different subsite to the page you are editing and republishing,
* otherwise the test will pass falsely due to current subsite ID being the same. * otherwise the test will pass falsely due to current subsite ID being the same.
*/ */
function testPublishedSubsiteVirtualPagesUpdateIfTargetPageUpdates() public function testPublishedSubsiteVirtualPagesUpdateIfTargetPageUpdates()
{ {
// create page // create page
$p = new Page(); $p = new Page();
@ -185,7 +195,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
$this->assertEquals($svpdb->Title, $p->Title); $this->assertEquals($svpdb->Title, $p->Title);
} }
function testUnpublishingParentPageUnpublishesSubsiteVirtualPages() { public function testUnpublishingParentPageUnpublishesSubsiteVirtualPages()
{
Config::inst()->update('StaticPublisher', 'disable_realtime', true); Config::inst()->update('StaticPublisher', 'disable_realtime', true);
// Go to main site, get parent page // Go to main site, get parent page
@ -228,7 +239,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
* Similar to {@link SiteTreeSubsitesTest->testTwoPagesWithSameURLOnDifferentSubsites()} * Similar to {@link SiteTreeSubsitesTest->testTwoPagesWithSameURLOnDifferentSubsites()}
* and {@link SiteTreeSubsitesTest->testPagesInDifferentSubsitesCanShareURLSegment()}. * and {@link SiteTreeSubsitesTest->testPagesInDifferentSubsitesCanShareURLSegment()}.
*/ */
function testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite() { public function testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite1 = $this->objFromFixture('Subsite', 'subsite1'); $subsite1 = $this->objFromFixture('Subsite', 'subsite1');
$subsite2 = $this->objFromFixture('Subsite', 'subsite2'); $subsite2 = $this->objFromFixture('Subsite', 'subsite2');
@ -265,12 +277,12 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
); );
} }
function fixVersionNumberCache($page) { public function fixVersionNumberCache($page)
{
$pages = func_get_args(); $pages = func_get_args();
foreach ($pages as $p) { foreach ($pages as $p) {
Versioned::prepopulate_versionnumber_cache('SiteTree', 'Stage', array($p->ID)); Versioned::prepopulate_versionnumber_cache('SiteTree', 'Stage', array($p->ID));
Versioned::prepopulate_versionnumber_cache('SiteTree', 'Live', array($p->ID)); Versioned::prepopulate_versionnumber_cache('SiteTree', 'Live', array($p->ID));
} }
} }
} }

View File

@ -2,15 +2,17 @@
namespace Subsites\Test\Behaviour; namespace Subsites\Test\Behaviour;
if(!class_exists('SilverStripe\BehatExtension\Context\SilverStripeContext')) return; if (!class_exists('SilverStripe\BehatExtension\Context\SilverStripeContext')) {
return;
}
use SilverStripe\BehatExtension\Context\SilverStripeContext, use SilverStripe\BehatExtension\Context\SilverStripeContext;
SilverStripe\BehatExtension\Context\BasicContext, use SilverStripe\BehatExtension\Context\BasicContext;
SilverStripe\BehatExtension\Context\LoginContext, use SilverStripe\BehatExtension\Context\LoginContext;
SilverStripe\BehatExtension\Context\FixtureContext, use SilverStripe\BehatExtension\Context\FixtureContext;
SilverStripe\Framework\Test\Behaviour\CmsFormsContext, use SilverStripe\Framework\Test\Behaviour\CmsFormsContext;
SilverStripe\Framework\Test\Behaviour\CmsUiContext, use SilverStripe\Framework\Test\Behaviour\CmsUiContext;
SilverStripe\Cms\Test\Behaviour; use SilverStripe\Cms\Test\Behaviour;
// PHPUnit // PHPUnit
require_once 'PHPUnit/Autoload.php'; require_once 'PHPUnit/Autoload.php';
@ -22,8 +24,8 @@ require_once 'PHPUnit/Framework/Assert/Functions.php';
* Context automatically loaded by Behat. * Context automatically loaded by Behat.
* Uses subcontexts to extend functionality. * Uses subcontexts to extend functionality.
*/ */
class FeatureContext extends SilverStripeContext { class FeatureContext extends SilverStripeContext
{
/** /**
* @var FixtureFactory * @var FixtureFactory
*/ */
@ -35,7 +37,8 @@ class FeatureContext extends SilverStripeContext {
* *
* @param array $parameters context parameters (set them up through behat.yml) * @param array $parameters context parameters (set them up through behat.yml)
*/ */
public function __construct(array $parameters) { public function __construct(array $parameters)
{
parent::__construct($parameters); parent::__construct($parameters);
$this->useContext('BasicContext', new BasicContext($parameters)); $this->useContext('BasicContext', new BasicContext($parameters));
@ -51,7 +54,9 @@ class FeatureContext extends SilverStripeContext {
$factory = $fixtureContext->getFixtureFactory(); $factory = $fixtureContext->getFixtureFactory();
$blueprint = \Injector::inst()->create('FixtureBlueprint', 'Member'); $blueprint = \Injector::inst()->create('FixtureBlueprint', 'Member');
$blueprint->addCallback('beforeCreate', function ($identifier, &$data, &$fixtures) { $blueprint->addCallback('beforeCreate', function ($identifier, &$data, &$fixtures) {
if(!isset($data['FirstName'])) $data['FirstName'] = $identifier; if (!isset($data['FirstName'])) {
$data['FirstName'] = $identifier;
}
}); });
$factory->define('Member', $blueprint); $factory->define('Member', $blueprint);
@ -65,7 +70,8 @@ class FeatureContext extends SilverStripeContext {
} }
} }
public function setMinkParameters(array $parameters) { public function setMinkParameters(array $parameters)
{
parent::setMinkParameters($parameters); parent::setMinkParameters($parameters);
if (isset($parameters['files_path'])) { if (isset($parameters['files_path'])) {
@ -76,7 +82,8 @@ class FeatureContext extends SilverStripeContext {
/** /**
* @return FixtureFactory * @return FixtureFactory
*/ */
public function getFixtureFactory() { public function getFixtureFactory()
{
if (!$this->fixtureFactory) { if (!$this->fixtureFactory) {
$this->fixtureFactory = \Injector::inst()->create('BehatFixtureFactory'); $this->fixtureFactory = \Injector::inst()->create('BehatFixtureFactory');
} }
@ -84,7 +91,8 @@ class FeatureContext extends SilverStripeContext {
return $this->fixtureFactory; return $this->fixtureFactory;
} }
public function setFixtureFactory(FixtureFactory $factory) { public function setFixtureFactory(FixtureFactory $factory)
{
$this->fixtureFactory = $factory; $this->fixtureFactory = $factory;
} }