reformat code and tests

This commit is contained in:
Werner M. Krauß 2017-05-24 15:26:28 +02:00
parent 2295501587
commit c5f507b3f9
30 changed files with 3683 additions and 3282 deletions

View File

@ -13,9 +13,10 @@ use SilverStripe\Subsites\Model\Subsite;
* *
* @package subsites * @package subsites
*/ */
class SubsiteAdmin extends ModelAdmin { class SubsiteAdmin extends ModelAdmin
{
private static $managed_models = array(Subsite::class); private static $managed_models = [Subsite::class];
private static $url_segment = 'subsites'; private static $url_segment = 'subsites';
@ -23,15 +24,16 @@ class SubsiteAdmin extends ModelAdmin {
private static $menu_icon = "subsites/images/subsites.png"; private static $menu_icon = "subsites/images/subsites.png";
public $showImportForm=false; public $showImportForm = false;
private static $tree_class = Subsite::class; private static $tree_class = Subsite::class;
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::class); $grid = $form->Fields()->dataFieldByName(Subsite::class);
if($grid) { if ($grid) {
$grid->getConfig()->removeComponentsByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm'); $grid->getConfig()->removeComponentsByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm');
$grid->getConfig()->addComponent(new GridFieldSubsiteDetailForm()); $grid->getConfig()->addComponent(new GridFieldSubsiteDetailForm());
} }

View File

@ -10,15 +10,21 @@ use SilverStripe\Subsites\Model\Subsite;
/** /**
* 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;
} }
@ -26,16 +32,20 @@ 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;
// Register a new callback // Register a new callback
$negotiator->setCallback('SubsiteList', function() use(&$self) { $negotiator->setCallback('SubsiteList', function () use (&$self) {
return $self->SubsiteList(); return $self->SubsiteList();
}); });
@ -45,7 +55,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('Includes/SubsiteList'); return $this->renderWith('Includes/SubsiteList');
} }

View File

@ -3,13 +3,15 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Core\Extension; use SilverStripe\Core\Extension;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class CMSPageAddControllerExtension extends Extension { class CMSPageAddControllerExtension extends Extension
{
function updatePageOptions(&$fields) { function updatePageOptions(&$fields)
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID())); $fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }

View File

@ -3,23 +3,27 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\View\SSViewer;
use SilverStripe\Core\Extension; use SilverStripe\Core\Extension;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\View\SSViewer;
/** /**
* @package subsites * @package subsites
*/ */
class ControllerSubsites extends Extension { class ControllerSubsites extends Extension
function controllerAugmentInit(){ {
if($subsite = Subsite::currentSubsite()){ function controllerAugmentInit()
if($theme = $subsite->Theme) {
if ($subsite = Subsite::currentSubsite()) {
if ($theme = $subsite->Theme) {
SSViewer::set_theme($theme); SSViewer::set_theme($theme);
} }
} }
}
function CurrentSubsite(){ function CurrentSubsite()
if($subsite = Subsite::currentSubsite()){ {
if ($subsite = Subsite::currentSubsite()) {
return $subsite; return $subsite;
} }
} }

View File

@ -3,12 +3,13 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
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
@ -21,21 +22,22 @@ class ErrorPageSubsite extends DataExtension {
* @param string $name Filename to write to * @param string $name Filename to write to
* @param int $statusCode Integer error code * @param int $statusCode Integer error code
*/ */
public function updateErrorFilename(&$name, $statusCode) { public function updateErrorFilename(&$name, $statusCode)
{
// Try to get current subsite from session // Try to get current subsite from session
$subsite = Subsite::currentSubsite(false); $subsite = Subsite::currentSubsite(false);
// 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) { if ($subsiteID != 0) {
$subsite = DataObject::get_by_id(Subsite::class, $subsiteID); $subsite = DataObject::get_by_id(Subsite::class, $subsiteID);
} }
} }
// Without subsite, don't rewrite // Without subsite, don't rewrite
if($subsite) { if ($subsite) {
// Add subdomain to end of filename, just before .html // Add subdomain to end of filename, just before .html
// This should preserve translatable locale in the filename as well // This should preserve translatable locale in the filename as well
$subdomain = $subsite->domain(); $subdomain = $subsite->domain();

View File

@ -3,15 +3,15 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\Forms\FieldList;
use SilverStripe\Assets\Folder; use SilverStripe\Assets\Folder;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\ORM\DataQuery;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Security\Permission; use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\Security\Permission;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
@ -20,51 +20,58 @@ use SilverStripe\Subsites\Model\Subsite;
* *
* @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; static $default_root_folders_global = false;
private static $has_one=array( private static $has_one = [
'Subsite' => Subsite::class, 'Subsite' => Subsite::class,
); ];
/** /**
* 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() { 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) { 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 = [];
$values[0] = _t('FileSubsites.AllSitesDropdownOpt','All sites'); $values[0] = _t('FileSubsites.AllSitesDropdownOpt', 'All sites');
foreach ($sites as $site) { foreach ($sites as $site) {
$values[$site->ID] = $site->Title; $values[$site->ID] = $site->Title;
} }
ksort($values); ksort($values);
if($sites){ if ($sites) {
//Dropdown needed to move folders between subsites //Dropdown needed to move folders between subsites
$dropdown = new DropdownField( $dropdown = new DropdownField(
'SubsiteID', 'SubsiteID',
_t('FileSubsites.SubsiteFieldLabel',Subsite::class), _t('FileSubsites.SubsiteFieldLabel', Subsite::class),
$values $values
); );
$dropdown->addExtraClass('subsites-move-dropdown'); $dropdown->addExtraClass('subsites-move-dropdown');
$fields->push($dropdown); $fields->push($dropdown);
$fields->push(new LiteralField( $fields->push(new LiteralField(
'Message', 'Message',
'<p class="message notice">'. '<p class="message notice">' .
_t('ASSETADMIN.SUBSITENOTICE', 'Folders and files created in the main site are accessible by all subsites.') _t('ASSETADMIN.SUBSITENOTICE',
.'</p>' 'Folders and files created in the main site are accessible by all subsites.')
. '</p>'
)); ));
} }
} }
@ -73,34 +80,40 @@ 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(SQLSelect $query, DataQuery $dataQuery = null) { public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
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();
// 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) {
$where = "\"$tableName\".\"SubsiteID\" IN (0, $subsiteID)"; $where = "\"$tableName\".\"SubsiteID\" IN (0, $subsiteID)";
$query->addWhere($where); $query->addWhere($where);
break; break;
} }
$sect=array_values($query->getSelect()); $sect = array_values($query->getSelect());
$isCounting = strpos($sect[0], 'COUNT') !== false; $isCounting = strpos($sect[0], 'COUNT') !== false;
// Ordering when deleting or counting doesn't apply // Ordering when deleting or counting doesn't apply
if(!$isCounting) { if (!$isCounting) {
$query->addOrderBy("\"SubsiteID\""); $query->addOrderBy("\"SubsiteID\"");
} }
} }
function onBeforeWrite() { 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;
@ -110,7 +123,8 @@ class FileSubsites extends DataExtension {
} }
} }
function onAfterUpload() { 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;
@ -120,14 +134,15 @@ class FileSubsites extends DataExtension {
$this->owner->write(); $this->owner->write();
} }
function canEdit($member = null) { 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) {
return true; return true;
} else { } else {
Session::set('SubsiteID', $this->owner->SubsiteID); Session::set('SubsiteID', $this->owner->SubsiteID);
$access = Permission::check(array('CMS_ACCESS_AssetAdmin', 'CMS_ACCESS_LeftAndMain')); $access = Permission::check(['CMS_ACCESS_AssetAdmin', 'CMS_ACCESS_LeftAndMain']);
Session::set('SubsiteID', $subsiteID); Session::set('SubsiteID', $subsiteID);
return $access; return $access;
@ -137,8 +152,9 @@ 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() { function cacheKeyComponent()
return 'subsite-'.Subsite::currentSubsiteID(); {
return 'subsite-' . Subsite::currentSubsiteID();
} }
} }

View File

@ -3,19 +3,19 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\ORM\DB;
use SilverStripe\Forms\FieldList;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\CheckboxSetField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\ORM\DataQuery;
use SilverStripe\Control\Cookie; use SilverStripe\Control\Cookie;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\CheckboxSetField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\Security\Group;
use SilverStripe\Security\PermissionProvider; use SilverStripe\Security\PermissionProvider;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Security\Group;
/** /**
@ -23,30 +23,32 @@ use SilverStripe\Security\Group;
* *
* @package subsites * @package subsites
*/ */
class GroupSubsites extends DataExtension implements PermissionProvider { class GroupSubsites extends DataExtension implements PermissionProvider
{
private static $db = array( private static $db = [
'AccessAllSubsites' => 'Boolean' 'AccessAllSubsites' => 'Boolean'
); ];
private static $many_many = array( private static $many_many = [
'Subsites' => Subsite::class 'Subsites' => Subsite::class
); ];
private static $defaults = array( private static $defaults = [
'AccessAllSubsites' => true 'AccessAllSubsites' => true
); ];
/** /**
* Migrations for GroupSubsites data. * Migrations for GroupSubsites data.
*/ */
function requireDefaultRecords() { 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
$schema = $this->owner->getSchema(); $schema = $this->owner->getSchema();
$groupFields = DB::field_list($schema->tableName(Group::class)); $groupFields = DB::field_list($schema->tableName(Group::class));
// Detection of SubsiteID field is the trigger for old-style-subsiteID migration // Detection of SubsiteID field is the trigger for old-style-subsiteID migration
if(isset($groupFields['SubsiteID'])) { if (isset($groupFields['SubsiteID'])) {
// Migrate subsite-specific data // Migrate subsite-specific data
DB::query('INSERT INTO "Group_Subsites" ("GroupID", "SubsiteID") DB::query('INSERT INTO "Group_Subsites" ("GroupID", "SubsiteID")
SELECT "ID", "SubsiteID" FROM "Group" WHERE "SubsiteID" > 0'); SELECT "ID", "SubsiteID" FROM "Group" WHERE "SubsiteID" > 0');
@ -59,21 +61,25 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
// No subsite access on anything means that we've just installed the subsites module. // No subsite access on anything means that we've just installed the subsites module.
// Make all previous groups global-access groups // Make all previous groups global-access groups
} else if(!DB::query('SELECT "Group"."ID" FROM "Group" } else {
if (!DB::query('SELECT "Group"."ID" FROM "Group"
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) { 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'));
$subsites = Subsite::accessible_sites(array('ADMIN', 'SECURITY_SUBSITE_GROUP'), true); $subsites = Subsite::accessible_sites(['ADMIN', 'SECURITY_SUBSITE_GROUP'], true);
$subsiteMap = $subsites->map(); $subsiteMap = $subsites->map();
// Prevent XSS injection // Prevent XSS injection
@ -81,13 +87,13 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
// Interface is different if you have the rights to modify subsite group values on // Interface is different if you have the rights to modify subsite group values on
// all subsites // all subsites
if(isset($subsiteMap[0])) { if (isset($subsiteMap[0])) {
$fields->addFieldToTab("Root.Subsites", new OptionsetField("AccessAllSubsites", $fields->addFieldToTab("Root.Subsites", new OptionsetField("AccessAllSubsites",
_t('GroupSubsites.ACCESSRADIOTITLE', 'Give this group access to'), _t('GroupSubsites.ACCESSRADIOTITLE', 'Give this group access to'),
array( [
1 => _t('GroupSubsites.ACCESSALL', "All subsites"), 1 => _t('GroupSubsites.ACCESSALL', "All subsites"),
0 => _t('GroupSubsites.ACCESSONLY', "Only these subsites"), 0 => _t('GroupSubsites.ACCESSONLY', "Only these subsites"),
) ]
)); ));
unset($subsiteMap[0]); unset($subsiteMap[0]);
@ -114,8 +120,9 @@ 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() { 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>';
} else { } else {
@ -127,27 +134,36 @@ 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(SQLSelect $query, DataQuery $dataQuery = null) { public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
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()) {
/*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();
// Don't filter by Group_Subsites if we've already done that // Don't filter by Group_Subsites if we've already done that
$hasGroupSubsites = false; $hasGroupSubsites = false;
foreach($query->getFrom() as $item) { foreach ($query->getFrom() as $item) {
if((is_array($item) && strpos($item['table'], 'Group_Subsites')!==false) || (!is_array($item) && strpos($item, 'Group_Subsites')!==false)) { if ((is_array($item) && strpos($item['table'],
'Group_Subsites') !== false) || (!is_array($item) && strpos($item,
'Group_Subsites') !== false)
) {
$hasGroupSubsites = true; $hasGroupSubsites = true;
break; break;
} }
} }
if(!$hasGroupSubsites) { if (!$hasGroupSubsites) {
if($subsiteID) { if ($subsiteID) {
$query->addLeftJoin("Group_Subsites", "\"Group_Subsites\".\"GroupID\" $query->addLeftJoin("Group_Subsites", "\"Group_Subsites\".\"GroupID\"
= \"Group\".\"ID\" AND \"Group_Subsites\".\"SubsiteID\" = $subsiteID"); = \"Group\".\"ID\" AND \"Group_Subsites\".\"SubsiteID\" = $subsiteID");
$query->addWhere("(\"Group_Subsites\".\"SubsiteID\" IS NOT NULL OR $query->addWhere("(\"Group_Subsites\".\"SubsiteID\" IS NOT NULL OR
@ -158,31 +174,34 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
} }
// WORKAROUND for databases that complain about an ORDER BY when the column wasn't selected (e.g. SQL Server) // WORKAROUND for databases that complain about an ORDER BY when the column wasn't selected (e.g. SQL Server)
$select=$query->getSelect(); $select = $query->getSelect();
if(isset($select[0]) && !$select[0] == 'COUNT(*)') { if (isset($select[0]) && !$select[0] == 'COUNT(*)') {
$query->orderby = "\"AccessAllSubsites\" DESC" . ($query->orderby ? ', ' : '') . $query->orderby; $query->orderby = "\"AccessAllSubsites\" DESC" . ($query->orderby ? ', ' : '') . $query->orderby;
} }
} }
} }
function onBeforeWrite() { 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()) {
$this->owner->AccessAllSubsites = 1; $this->owner->AccessAllSubsites = 1;
} }
} }
function onAfterWrite() { 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()) {
$subsites = $this->owner->Subsites(); $subsites = $this->owner->Subsites();
$subsites->add($currentSubsiteID); $subsites->add($currentSubsiteID);
} }
} }
function alternateCanEdit() { 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');
@ -192,15 +211,17 @@ class GroupSubsites extends DataExtension implements PermissionProvider {
return (bool)array_intersect($accessibleSites, $linkedSites); return (bool)array_intersect($accessibleSites, $linkedSites);
} }
function providePermissions() { function providePermissions()
return array( {
'SECURITY_SUBSITE_GROUP' => array( return [
'SECURITY_SUBSITE_GROUP' => [
'name' => _t('GroupSubsites.MANAGE_SUBSITES', 'Manage subsites for groups'), 'name' => _t('GroupSubsites.MANAGE_SUBSITES', 'Manage subsites for groups'),
'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'), 'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
'help' => _t('GroupSubsites.MANAGE_SUBSITES_HELP', 'Ability to limit the permissions for a group to one or more subsites.'), 'help' => _t('GroupSubsites.MANAGE_SUBSITES_HELP',
'Ability to limit the permissions for a group to one or more subsites.'),
'sort' => 200 'sort' => 200
) ]
); ];
} }
} }

View File

@ -3,21 +3,21 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\View\Requirements; use SilverStripe\Admin\CMSMenu;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Session;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Core\Extension;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\HiddenField;
use SilverStripe\Security\Member;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\Core\Config\Config; use SilverStripe\Security\Member;
use SilverStripe\View\ArrayData;
use SilverStripe\Security\Permission; use SilverStripe\Security\Permission;
use SilverStripe\Control\Session;
use SilverStripe\Admin\CMSMenu;
use SilverStripe\Security\Security; use SilverStripe\Security\Security;
use SilverStripe\Control\Controller;
use SilverStripe\Core\Extension;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements;
/** /**
@ -25,9 +25,10 @@ use SilverStripe\Subsites\Model\Subsite;
* *
* @package subsites * @package subsites
*/ */
class LeftAndMainSubsites extends Extension { class LeftAndMainSubsites extends Extension
{
private static $allowed_actions = array('CopyToSubsite'); private static $allowed_actions = ['CopyToSubsite'];
/** /**
* Normally SubsiteID=0 on a DataObject means it is only accessible from the special "main site". * Normally SubsiteID=0 on a DataObject means it is only accessible from the special "main site".
@ -36,7 +37,8 @@ class LeftAndMainSubsites extends Extension {
*/ */
private static $treats_subsite_0_as_global = false; private static $treats_subsite_0_as_global = false;
function init() { 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');
@ -45,12 +47,14 @@ class LeftAndMainSubsites extends Extension {
/** /**
* Set the title of the CMS tree * Set the title of the CMS tree
*/ */
function getCMSTreeTitle() { 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) { function updatePageOptions(&$fields)
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID())); $fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }
@ -59,31 +63,41 @@ 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) { 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('SilverStripe\\Security\\Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('SilverStripe\\Security\\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 = [];
$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();
} }
// Find subsites satisfying all permissions for the Member. // Find subsites satisfying all permissions for the Member.
$codesPerSite = array(); $codesPerSite = [];
$sitesArray = array(); $sitesArray = [];
foreach ($codes as $code) { foreach ($codes as $code) {
$sites = Subsite::accessible_sites($code, $includeMainSite, $mainSiteTitle, $member); $sites = Subsite::accessible_sites($code, $includeMainSite, $mainSiteTitle, $member);
foreach ($sites as $site) { foreach ($sites as $site) {
@ -98,7 +112,7 @@ class LeftAndMainSubsites extends Extension {
// Find sites that satisfy all codes conjuncitvely. // Find sites that satisfy all codes conjuncitvely.
$accessibleSites = new ArrayList(); $accessibleSites = new ArrayList();
foreach ($codesPerSite as $siteID => $siteCodes) { foreach ($codesPerSite as $siteID => $siteCodes) {
if (count($siteCodes)==count($codes)) { if (count($siteCodes) == count($codes)) {
$accessibleSites->push($sitesArray[$siteID]); $accessibleSites->push($sitesArray[$siteID]);
} }
} }
@ -110,7 +124,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();
} }
@ -120,11 +135,12 @@ 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();
if($list == null || $list->Count() == 1 && $list->First()->DefaultSite == true){ if ($list == null || $list->Count() == 1 && $list->First()->DefaultSite == true) {
return false; return false;
} }
@ -132,31 +148,32 @@ class LeftAndMainSubsites extends Extension {
$output = new ArrayList(); $output = new ArrayList();
foreach($list as $subsite) { foreach ($list as $subsite) {
$CurrentState = $subsite->ID == $currentSubsiteID ? 'selected' : ''; $CurrentState = $subsite->ID == $currentSubsiteID ? 'selected' : '';
$output->push(new ArrayData(array( $output->push(new ArrayData([
'CurrentState' => $CurrentState, 'CurrentState' => $CurrentState,
'ID' => $subsite->ID, 'ID' => $subsite->ID,
'Title' => Convert::raw2xml($subsite->Title) 'Title' => Convert::raw2xml($subsite->Title)
))); ]));
} }
return $output; return $output;
} }
public function alternateMenuDisplayCheck($controllerName) { public function alternateMenuDisplayCheck($controllerName)
if(!class_exists($controllerName)){ {
if (!class_exists($controllerName)) {
return false; return false;
} }
// Check subsite support. // Check subsite support.
if(Subsite::currentSubsiteID() == 0){ if (Subsite::currentSubsiteID() == 0) {
// Main site always supports everything. // Main site always supports everything.
return true; return true;
} else { } else {
$controller = singleton($controllerName); $controller = singleton($controllerName);
if($controller->hasMethod('subsiteCMSShowInMenu') && $controller->subsiteCMSShowInMenu()){ if ($controller->hasMethod('subsiteCMSShowInMenu') && $controller->subsiteCMSShowInMenu()) {
return true; return true;
} }
} }
@ -167,30 +184,39 @@ 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() { 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 &&
( (
Permission::checkMember($member, 'ADMIN') || // 'Full administrative rights' in SecurityAdmin Permission::checkMember($member, 'ADMIN') || // 'Full administrative rights' in SecurityAdmin
Permission::checkMember($member, 'CMS_ACCESS_LeftAndMain') // 'Access to all CMS sections' in SecurityAdmin Permission::checkMember($member,
)) { 'CMS_ACCESS_LeftAndMain') // 'Access to all CMS sections' in SecurityAdmin
)
) {
return true; return true;
} }
@ -208,7 +234,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();
} }
@ -222,16 +249,17 @@ 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;
// FIRST, check if we need to change subsites due to the URL. // FIRST, check if we need to change subsites due to the URL.
// Catch forced subsite changes that need to cause CMS reloads. // Catch forced subsite changes that need to cause CMS reloads.
if(isset($_GET['SubsiteID'])) { if (isset($_GET['SubsiteID'])) {
// Clear current page when subsite changes (or is set for the first time) // Clear current page when subsite changes (or is set for the first time)
if(!Session::get('SubsiteID') || $_GET['SubsiteID'] != Session::get('SubsiteID')) { if (!Session::get('SubsiteID') || $_GET['SubsiteID'] != Session::get('SubsiteID')) {
Session::clear("{$this->owner->class}.currentPage"); Session::clear("{$this->owner->class}.currentPage");
} }
@ -250,7 +278,7 @@ class LeftAndMainSubsites extends Extension {
// Automatically redirect the session to appropriate subsite when requesting a record. // Automatically redirect the session to appropriate subsite when requesting a record.
// 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
@ -274,8 +302,8 @@ class LeftAndMainSubsites extends Extension {
// 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())) {
@ -286,8 +314,8 @@ class LeftAndMainSubsites extends Extension {
} }
// If no section is available, look for other accessible subsites. // If no section is available, look for other accessible subsites.
foreach($menu as $candidate) { foreach ($menu as $candidate) {
if($candidate->controller) { if ($candidate->controller) {
$accessibleSites = singleton($candidate->controller)->sectionSites(true, 'Main site', $member); $accessibleSites = singleton($candidate->controller)->sectionSites(true, 'Main site', $member);
if ($accessibleSites->count()) { if ($accessibleSites->count()) {
Subsite::changeSubsite($accessibleSites->First()->ID); Subsite::changeSubsite($accessibleSites->First()->ID);
@ -305,17 +333,21 @@ class LeftAndMainSubsites extends Extension {
return; return;
} }
function augmentNewSiteTreeItem(&$item) { function augmentNewSiteTreeItem(&$item)
{
$item->SubsiteID = isset($_POST['SubsiteID']) ? $_POST['SubsiteID'] : Subsite::currentSubsiteID(); $item->SubsiteID = isset($_POST['SubsiteID']) ? $_POST['SubsiteID'] : Subsite::currentSubsiteID();
} }
function onAfterSave($record) { function onAfterSave($record)
if($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) { {
$this->owner->response->addHeader('X-Status', rawurlencode(_t('LeftAndMainSubsites.Saved', 'Saved, please update related pages.'))); if ($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) {
$this->owner->response->addHeader('X-Status',
rawurlencode(_t('LeftAndMainSubsites.Saved', 'Saved, please update related pages.')));
} }
} }
function copytosubsite($data, $form) { function copytosubsite($data, $form)
{
$page = DataObject::get_by_id('SilverStripe\\CMS\\Model\\SiteTree', $data['ID']); $page = DataObject::get_by_id('SilverStripe\\CMS\\Model\\SiteTree', $data['ID']);
$subsite = DataObject::get_by_id(Subsite::class, $data['CopyToSubsiteID']); $subsite = DataObject::get_by_id(Subsite::class, $data['CopyToSubsiteID']);
$newPage = $page->duplicateToSubsite($subsite->ID, true); $newPage = $page->duplicateToSubsite($subsite->ID, true);

View File

@ -3,60 +3,75 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\ORM\DataQuery;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\HiddenField;
use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataExtension;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\SiteConfig\SiteConfig; use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Model\Subsite;
/** /**
* 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 = [
'Subsite' => Subsite::class, // The subsite that this page belongs to 'Subsite' => Subsite::class, // The subsite that this page belongs to
); ];
/** /**
* 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(SQLSelect $query, DataQuery $dataQuery = null) { public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
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;
else */$subsiteID = (int)Subsite::currentSubsiteID(); else */
$subsiteID = (int)Subsite::currentSubsiteID();
$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::class) return; if ($tableName != SiteConfig::class) {
return;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
} }
function onBeforeWrite() { 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() { function cacheKeyComponent()
return 'subsite-'.Subsite::currentSubsiteID(); {
return 'subsite-' . Subsite::currentSubsiteID();
} }
function updateCMSFields(FieldList $fields) { function updateCMSFields(FieldList $fields)
$fields->push(new HiddenField('SubsiteID','SubsiteID', Subsite::currentSubsiteID())); {
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
} }
} }

View File

@ -3,91 +3,110 @@
namespace SilverStripe\Subsites\Extensions; namespace SilverStripe\Subsites\Extensions;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\ORM\DataQuery;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\InlineFormAction;
use SilverStripe\Core\Config\Config;
use SilverStripe\Control\Director;
use SilverStripe\Control\Controller;
use SilverStripe\ORM\DataObject;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Security\Member;
use SilverStripe\Control\HTTP;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\DataExtension;
use SilverStripe\Subsites\Model\Subsite;
use Page; use Page;
use SilverStripe\CMS\Model\SiteTree; use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTP;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\InlineFormAction;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\Security\Member;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Model\Subsite;
/** /**
* 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 = [
'Subsite' => Subsite::class, // The subsite that this page belongs to 'Subsite' => Subsite::class, // The subsite that this page belongs to
); ];
private static $many_many = array( private static $many_many = [
'CrossSubsiteLinkTracking' => 'SilverStripe\\CMS\\Model\\SiteTree' // Stored separately, as the logic for URL rewriting is different 'CrossSubsiteLinkTracking' => 'SilverStripe\\CMS\\Model\\SiteTree'
); // Stored separately, as the logic for URL rewriting is different
];
private static $many_many_extraFields = array( private static $many_many_extraFields = [
"CrossSubsiteLinkTracking" => array("FieldName" => "Varchar") "CrossSubsiteLinkTracking" => ["FieldName" => "Varchar"]
); ];
function isMainSite() { 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(SQLSelect $query, DataQuery $dataQuery = null) { public function augmentSQL(SQLSelect $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();
} }
// 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::class) === false) break; if (strpos($tableName, SiteTree::class) === false) {
break;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
break; break;
} }
} }
function onBeforeWrite() { 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) { function updateCMSFields(FieldList $fields)
{
$subsites = Subsite::accessible_sites("CMS_ACCESS_CMSMain"); $subsites = Subsite::accessible_sites("CMS_ACCESS_CMSMain");
$subsitesMap = array(); $subsitesMap = [];
if($subsites && $subsites->Count()) { if ($subsites && $subsites->Count()) {
$subsitesMap = $subsites->map('ID', 'Title')->toArray(); $subsitesMap = $subsites->map('ID', 'Title')->toArray();
unset($subsitesMap[$this->owner->SubsiteID]); unset($subsitesMap[$this->owner->SubsiteID]);
} }
// Master page edit field (only allowed from default subsite to avoid inconsistent relationships) // Master page edit field (only allowed from default subsite to avoid inconsistent relationships)
$isDefaultSubsite = $this->owner->SubsiteID == 0 || $this->owner->Subsite()->DefaultSite; $isDefaultSubsite = $this->owner->SubsiteID == 0 || $this->owner->Subsite()->DefaultSite;
if($isDefaultSubsite && $subsitesMap) { if ($isDefaultSubsite && $subsitesMap) {
$fields->addFieldToTab( $fields->addFieldToTab(
'Root.Main', 'Root.Main',
new DropdownField( new DropdownField(
@ -109,9 +128,9 @@ class SiteTreeSubsites extends DataExtension {
// replace readonly link prefix // replace readonly link prefix
$subsite = $this->owner->Subsite(); $subsite = $this->owner->Subsite();
$nested_urls_enabled = Config::inst()->get('SilverStripe\\CMS\\Model\\SiteTree', 'nested_urls'); $nested_urls_enabled = Config::inst()->get('SilverStripe\\CMS\\Model\\SiteTree', 'nested_urls');
if($subsite && $subsite->ID) { if ($subsite && $subsite->ID) {
$baseUrl = Director::protocol() . $subsite->domain() . '/'; $baseUrl = Director::protocol() . $subsite->domain() . '/';
$baseLink = Controller::join_links ( $baseLink = Controller::join_links(
$baseUrl, $baseUrl,
($nested_urls_enabled && $this->owner->ParentID ? $this->owner->Parent()->RelativeLink(true) : null) ($nested_urls_enabled && $this->owner->ParentID ? $this->owner->Parent()->RelativeLink(true) : null)
); );
@ -121,14 +140,17 @@ class SiteTreeSubsites extends DataExtension {
} }
} }
function alternateSiteConfig() { function alternateSiteConfig()
if(!$this->owner->SubsiteID) return false; {
if (!$this->owner->SubsiteID) {
return false;
}
$sc = DataObject::get_one('SilverStripe\\SiteConfig\\SiteConfig', '"SubsiteID" = ' . $this->owner->SubsiteID); $sc = DataObject::get_one('SilverStripe\\SiteConfig\\SiteConfig', '"SubsiteID" = ' . $this->owner->SubsiteID);
if(!$sc) { if (!$sc) {
$sc = new SiteConfig(); $sc = new SiteConfig();
$sc->SubsiteID = $this->owner->SubsiteID; $sc->SubsiteID = $this->owner->SubsiteID;
$sc->Title = _t('Subsite.SiteConfigTitle','Your Site Name'); $sc->Title = _t('Subsite.SiteConfigTitle', 'Your Site Name');
$sc->Tagline = _t('Subsite.SiteConfigSubtitle','Your tagline here'); $sc->Tagline = _t('Subsite.SiteConfigSubtitle', 'Your tagline here');
$sc->write(); $sc->write();
} }
return $sc; return $sc;
@ -141,12 +163,15 @@ class SiteTreeSubsites extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
function canEdit($member = null) { 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');
if (!is_null($this->owner->SubsiteID)) { if (!is_null($this->owner->SubsiteID)) {
$subsiteID = $this->owner->SubsiteID; $subsiteID = $this->owner->SubsiteID;
@ -160,14 +185,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) { 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);
} }
@ -175,8 +205,11 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* @return boolean * @return boolean
*/ */
function canAddChildren($member = null) { 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);
} }
@ -184,8 +217,11 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* @return boolean * @return boolean
*/ */
function canPublish($member = null) { 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);
} }
@ -195,7 +231,8 @@ class SiteTreeSubsites extends DataExtension {
* this means we can subclass this easier and do more complex * this means we can subclass this easier and do more complex
* relation duplication. * relation duplication.
*/ */
public function duplicateToSubsitePrep($subsiteID) { public function duplicateToSubsitePrep($subsiteID)
{
if (is_object($subsiteID)) { if (is_object($subsiteID)) {
$subsiteID = $subsiteID->ID; $subsiteID = $subsiteID->ID;
} }
@ -231,7 +268,8 @@ 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)
{
$clone = $this->owner->duplicateToSubsitePrep($subsiteID); $clone = $this->owner->duplicateToSubsitePrep($subsiteID);
$clone->invokeWithExtensions('onBeforeDuplicateToSubsite', $this->owner); $clone->invokeWithExtensions('onBeforeDuplicateToSubsite', $this->owner);
$clone->write(); $clone->write();
@ -251,16 +289,17 @@ class SiteTreeSubsites extends DataExtension {
* whereas others may need to be duplicated * whereas others may need to be duplicated
* *
*/ */
public function duplicateSubsiteRelations($originalPage) { public function duplicateSubsiteRelations($originalPage)
{
$thisClass = $originalPage->ClassName; $thisClass = $originalPage->ClassName;
$relations = Config::inst()->get($thisClass, 'duplicate_to_subsite_relations'); $relations = Config::inst()->get($thisClass, 'duplicate_to_subsite_relations');
if($relations && !empty($relations)) { if ($relations && !empty($relations)) {
foreach($relations as $relation) { foreach ($relations as $relation) {
$items = $originalPage->$relation(); $items = $originalPage->$relation();
foreach($items as $item) { foreach ($items as $item) {
$duplicateItem = $item->duplicate(false); $duplicateItem = $item->duplicate(false);
$duplicateItem->{$thisClass.'ID'} = $this->owner->ID; $duplicateItem->{$thisClass . 'ID'} = $this->owner->ID;
$duplicateItem->write(); $duplicateItem->write();
} }
} }
@ -270,19 +309,21 @@ class SiteTreeSubsites extends DataExtension {
/** /**
* Called by ContentController::init(); * Called by ContentController::init();
*/ */
static function contentcontrollerInit($controller) { static function contentcontrollerInit($controller)
{
$subsite = Subsite::currentSubsite(); $subsite = Subsite::currentSubsite();
if($subsite && $subsite->Theme){ if ($subsite && $subsite->Theme) {
Config::modify()->set('SilverStripe\\View\\SSViewer', 'theme', Subsite::currentSubsite()->Theme); Config::modify()->set('SilverStripe\\View\\SSViewer', 'theme', Subsite::currentSubsite()->Theme);
} }
} }
function alternateAbsoluteLink() { 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());
if($this->owner->SubsiteID) { if ($this->owner->SubsiteID) {
$url = preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url); $url = preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url);
} }
return $url; return $url;
@ -292,9 +333,10 @@ 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) { 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);
} }
return $url; return $url;
@ -303,35 +345,42 @@ 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) { 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";
} }
return $tags; return $tags;
} }
function augmentSyncLinkTracking() { function augmentSyncLinkTracking()
{
// Set LinkTracking appropriately // Set LinkTracking appropriately
$links = HTTP::getLinksIn($this->owner->Content); $links = HTTP::getLinksIn($this->owner->Content);
$linkedPages = array(); $linkedPages = [];
if($links) foreach($links as $link) { if ($links) {
if(substr($link, 0, strlen('http://')) == 'http://') { foreach ($links as $link) {
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)) {
$domain = substr($withoutHttp, 0, strpos($withoutHttp, '/')); $domain = substr($withoutHttp, 0, strpos($withoutHttp, '/'));
$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);
$candidatePage = DataObject::get_one("SilverStripe\\CMS\\Model\\SiteTree", "\"URLSegment\" = '" . Convert::raw2sql(urldecode( $rest)) . "' AND \"SubsiteID\" = " . $subsiteID, false); $candidatePage = DataObject::get_one("SilverStripe\\CMS\\Model\\SiteTree",
"\"URLSegment\" = '" . Convert::raw2sql(urldecode($rest)) . "' AND \"SubsiteID\" = " . $subsiteID,
false);
Subsite::disable_subsite_filter($origDisableSubsiteFilter); Subsite::disable_subsite_filter($origDisableSubsiteFilter);
if($candidatePage) { if ($candidatePage) {
$linkedPages[] = $candidatePage->ID; $linkedPages[] = $candidatePage->ID;
} else { } else {
$this->owner->HasBrokenLink = true; $this->owner->HasBrokenLink = true;
@ -339,6 +388,7 @@ class SiteTreeSubsites extends DataExtension {
} }
} }
} }
}
$this->owner->CrossSubsiteLinkTracking()->setByIDList($linkedPages); $this->owner->CrossSubsiteLinkTracking()->setByIDList($linkedPages);
} }
@ -346,21 +396,25 @@ 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() { function cacheKeyComponent()
return 'subsite-'.Subsite::currentSubsiteID(); {
return 'subsite-' . Subsite::currentSubsiteID();
} }
/** /**
* @param Member * @param Member
* @return boolean|null * @return boolean|null
*/ */
function canCreate($member = null) { 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

@ -6,7 +6,6 @@ namespace SilverStripe\Subsites\Extensions;
use SilverStripe\Core\Extension; use SilverStripe\Core\Extension;
/* /*
* Simple extension to show admins in the menu of subsites. * Simple extension to show admins in the menu of subsites.
* If an admin area should be available to a subsite, you can attach * If an admin area should be available to a subsite, you can attach
@ -17,9 +16,11 @@ use SilverStripe\Core\Extension;
* 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

@ -3,22 +3,23 @@
namespace SilverStripe\Subsites\Forms; namespace SilverStripe\Subsites\Forms;
use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest; use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class GridFieldSubsiteDetailForm extends GridFieldDetailForm { class GridFieldSubsiteDetailForm extends GridFieldDetailForm
protected $itemRequestClass=GridFieldSubsiteDetailForm_ItemRequest::class; {
protected $itemRequestClass = GridFieldSubsiteDetailForm_ItemRequest::class;
} }
class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest { class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
private static $allowed_actions = array( private static $allowed_actions = [
'ItemEditForm', 'ItemEditForm',
); ];
/** /**
* Builds an item edit form. The arguments to getCMSFields() are the popupController and * Builds an item edit form. The arguments to getCMSFields() are the popupController and
@ -31,17 +32,19 @@ class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemReq
* @return Form * @return Form
* @see GridFieldDetailForm_ItemRequest::ItemEditForm() * @see GridFieldDetailForm_ItemRequest::ItemEditForm()
*/ */
function ItemEditForm() { function ItemEditForm()
$form=parent::ItemEditForm(); {
$form = parent::ItemEditForm();
if($this->record->ID == 0) { if ($this->record->ID == 0) {
$templates = Subsite::get()->sort('Title'); $templates = Subsite::get()->sort('Title');
$templateArray = array(); $templateArray = [];
if($templates) { if ($templates) {
$templateArray = $templates->map('ID', 'Title'); $templateArray = $templates->map('ID', 'Title');
} }
$templateDropdown = new DropdownField('TemplateID', _t('Subsite.COPYSTRUCTURE', 'Copy structure from:'), $templateArray); $templateDropdown = new DropdownField('TemplateID', _t('Subsite.COPYSTRUCTURE', 'Copy structure from:'),
$templateArray);
$templateDropdown->setEmptyString('(' . _t('Subsite.NOTEMPLATE', 'No template') . ')'); $templateDropdown->setEmptyString('(' . _t('Subsite.NOTEMPLATE', 'No template') . ')');
$form->Fields()->addFieldToTab('Root.Configuration', $templateDropdown); $form->Fields()->addFieldToTab('Root.Configuration', $templateDropdown);
} }
@ -49,11 +52,12 @@ class GridFieldSubsiteDetailForm_ItemRequest extends GridFieldDetailForm_ItemReq
return $form; return $form;
} }
function doSave($data, $form) { 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']));
if($template) { if ($template) {
$this->record = $template->duplicate(); $this->record = $template->duplicate();
} }
} }

View File

@ -3,11 +3,10 @@
namespace SilverStripe\Subsites\Forms; namespace SilverStripe\Subsites\Forms;
use SilverStripe\View\Requirements;
use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Forms\TreeDropdownField; use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\View\Requirements;
/** /**
@ -16,17 +15,19 @@ use SilverStripe\Forms\TreeDropdownField;
* *
* @package subsites * @package subsites
*/ */
class SubsitesTreeDropdownField extends TreeDropdownField { class SubsitesTreeDropdownField extends TreeDropdownField
{
private static $allowed_actions = array( private static $allowed_actions = [
'tree' 'tree'
); ];
protected $subsiteID = 0; protected $subsiteID = 0;
protected $extraClasses = array(SubsitesTreeDropdownField::class); protected $extraClasses = [SubsitesTreeDropdownField::class];
function Field($properties = array()) { function Field($properties = [])
{
$html = parent::Field($properties); $html = parent::Field($properties);
Requirements::javascript('subsites/javascript/SubsitesTreeDropdownField.js'); Requirements::javascript('subsites/javascript/SubsitesTreeDropdownField.js');
@ -34,15 +35,18 @@ class SubsitesTreeDropdownField extends TreeDropdownField {
return $html; return $html;
} }
function setSubsiteID($id) { function setSubsiteID($id)
{
$this->subsiteID = $id; $this->subsiteID = $id;
} }
function getSubsiteID() { function getSubsiteID()
{
return $this->subsiteID; return $this->subsiteID;
} }
function tree(HTTPRequest $request) { function tree(HTTPRequest $request)
{
$oldSubsiteID = Session::get('SubsiteID'); $oldSubsiteID = Session::get('SubsiteID');
Session::set('SubsiteID', $this->subsiteID); Session::set('SubsiteID', $this->subsiteID);

View File

@ -3,37 +3,34 @@
namespace SilverStripe\Subsites\Model; namespace SilverStripe\Subsites\Model;
use SilverStripe\i18n\Data\Intl\IntlLocales;
use SilverStripe\ORM\DataObject;
use SilverStripe\Control\Session;
use SilverStripe\i18n\i18n;
use SilverStripe\Security\Permission;
use SilverStripe\Security\Member;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\ArrayList;
use SilverStripe\Admin\CMSMenu; use SilverStripe\Admin\CMSMenu;
use SilverStripe\ORM\DataList;
use SilverStripe\Control\Director;
use SilverStripe\ORM\DB;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\CMS\Model\SiteTree; use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Forms\HeaderField; use SilverStripe\Control\Director;
use SilverStripe\Forms\TextField; use SilverStripe\Control\Session;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\CheckboxSetField; use SilverStripe\Forms\CheckboxSetField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
use SilverStripe\Forms\HeaderField;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\Tab; use SilverStripe\Forms\Tab;
use SilverStripe\Forms\TabSet; use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\TextField;
use SilverStripe\Forms\FieldList; use SilverStripe\i18n\Data\Intl\IntlLocales;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\ArrayLib; use SilverStripe\ORM\ArrayLib;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Versioned\Versioned; use SilverStripe\Versioned\Versioned;
use UnexpectedValueException; use UnexpectedValueException;
use SilverStripe\Security\Group;
use SilverStripe\Security\PermissionRole;
use SilverStripe\Security\PermissionRoleCode;
/** /**
@ -42,7 +39,8 @@ use SilverStripe\Security\PermissionRoleCode;
* *
* @package subsites * @package subsites
*/ */
class Subsite extends DataObject { class Subsite extends DataObject
{
private static $table_name = 'Subsite'; private static $table_name = 'Subsite';
@ -78,21 +76,21 @@ class Subsite extends DataObject {
* *
* @array * @array
*/ */
private static $_cache_accessible_sites = array(); private static $_cache_accessible_sites = [];
/** /**
* Memory cache of subsite id for domains * Memory cache of subsite id for domains
* *
* @var array * @var array
*/ */
private static $_cache_subsite_for_domain = array(); private static $_cache_subsite_for_domain = [];
/** /**
* @var array $allowed_themes Numeric array of all themes which are allowed to be selected for all subsites. * @var array $allowed_themes Numeric array of all themes which are allowed to be selected for all subsites.
* Corresponds to subfolder names within the /themes folder. By default, all themes contained in this folder * Corresponds to subfolder names within the /themes folder. By default, all themes contained in this folder
* are listed. * are listed.
*/ */
private static $allowed_themes = array(); private static $allowed_themes = [];
/** /**
* @var Boolean If set to TRUE, don't assume 'www.example.com' and 'example.com' are the same. * @var Boolean If set to TRUE, don't assume 'www.example.com' and 'example.com' are the same.
@ -109,18 +107,19 @@ class Subsite extends DataObject {
/** /**
* @return array * @return array
*/ */
private static $summary_fields = array( private static $summary_fields = [
'Title', 'Title',
'PrimaryDomain', 'PrimaryDomain',
'IsPublic' 'IsPublic'
); ];
/** /**
* Set allowed themes * Set allowed themes
* *
* @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;
} }
@ -130,7 +129,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::class, self::currentSubsiteID()); return DataObject::get_by_id(Subsite::class, self::currentSubsiteID());
} }
@ -148,16 +148,19 @@ 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'];
} else if (Subsite::$use_session_subsiteid) { } else {
if (Subsite::$use_session_subsiteid) {
$id = Session::get('SubsiteID'); $id = Session::get('SubsiteID');
} }
}
if($id === NULL) { if ($id === NULL) {
$id = self::getSubsiteIDForDomain(); $id = self::getSubsiteIDForDomain();
} }
@ -170,20 +173,26 @@ 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);
// Set locale // Set locale
if (is_object($subsite) && $subsite->Language != '') { if (is_object($subsite) && $subsite->Language != '') {
$locale = i18n::get_locale_from_lang($subsite->Language); $locale = i18n::get_locale_from_lang($subsite->Language);
if($locale) { if ($locale) {
i18n::set_locale($locale); i18n::set_locale($locale);
} }
} }
@ -200,31 +209,37 @@ 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'];
} }
$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('_', [$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(
SubsiteDomain::class, SubsiteDomain::class,
"'$SQL_host' LIKE replace(\"SubsiteDomain\".\"Domain\",'*','%')", "'$SQL_host' LIKE replace(\"SubsiteDomain\".\"Domain\",'*','%')",
"\"IsPrimary\" DESC" "\"IsPrimary\" DESC"
)->innerJoin('Subsite', "\"Subsite\".\"ID\" = \"SubsiteDomain\".\"SubsiteID\" AND \"Subsite\".\"IsPublic\"=1"); )->innerJoin('Subsite',
"\"Subsite\".\"ID\" = \"SubsiteDomain\".\"SubsiteID\" AND \"Subsite\".\"IsPublic\"=1");
} }
if($matchingDomains && $matchingDomains->Count()) { if ($matchingDomains && $matchingDomains->Count()) {
$subsiteIDs = array_unique($matchingDomains->column('SubsiteID')); $subsiteIDs = array_unique($matchingDomains->column('SubsiteID'));
$subsiteDomains = array_unique($matchingDomains->column('Domain')); $subsiteDomains = array_unique($matchingDomains->column('Domain'));
if(sizeof($subsiteIDs) > 1) { if (sizeof($subsiteIDs) > 1) {
throw new UnexpectedValueException(sprintf( throw new UnexpectedValueException(sprintf(
"Multiple subsites match on '%s': %s", "Multiple subsites match on '%s': %s",
$host, $host,
@ -233,13 +248,15 @@ class Subsite extends DataObject {
} }
$subsiteID = $subsiteIDs[0]; $subsiteID = $subsiteIDs[0];
} else if($default = DataObject::get_one(Subsite::class, "\"DefaultSite\" = 1")) { } else {
if ($default = DataObject::get_one(Subsite::class, "\"DefaultSite\" = 1")) {
// Check for a 'default' subsite // Check for a 'default' subsite
$subsiteID = $default->ID; $subsiteID = $default->ID;
} else { } else {
// Default subsite id = 0, the main site // Default subsite id = 0, the main site
$subsiteID = 0; $subsiteID = 0;
} }
}
if ($cacheKey) { if ($cacheKey) {
self::$_cache_subsite_for_domain[$cacheKey] = $subsiteID; self::$_cache_subsite_for_domain[$cacheKey] = $subsiteID;
@ -257,7 +274,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;
@ -266,16 +284,18 @@ 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_subsite_for_domain = array(); self::$_cache_accessible_sites = [];
self::$_cache_subsite_for_domain = [];
} }
/** /**
@ -283,10 +303,11 @@ 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) {
$subsites = $subsites->toArray(); $subsites = $subsites->toArray();
$mainSite = new Subsite(); $mainSite = new Subsite();
@ -305,17 +326,24 @@ 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('SilverStripe\\Security\\Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('SilverStripe\\Security\\Member', $member);
}
$subsites = new ArrayList(); $subsites = new ArrayList();
// Collect subsites for all sections. // Collect subsites for all sections.
$menu = CMSMenu::get_viewable_menu_items(); $menu = CMSMenu::get_viewable_menu_items();
foreach($menu as $candidate) { foreach ($menu as $candidate) {
if ($candidate->controller) { if ($candidate->controller) {
$accessibleSites = singleton($candidate->controller)->sectionSites( $accessibleSites = singleton($candidate->controller)->sectionSites(
$includeMainSite, $includeMainSite,
@ -343,59 +371,88 @@ 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('SilverStripe\\Security\\Member', $member); }
if (!$member) {
return new ArrayList();
}
if (!is_object($member)) {
$member = DataObject::get_by_id('SilverStripe\\Security\\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;
if(isset(self::$_cache_accessible_sites[$cacheKey])) { if (isset(self::$_cache_accessible_sites[$cacheKey])) {
return self::$_cache_accessible_sites[$cacheKey]; return self::$_cache_accessible_sites[$cacheKey];
} }
$subsites = DataList::create(Subsite::class) $subsites = DataList::create(Subsite::class)
->where("\"Subsite\".\"Title\" != ''") ->where("\"Subsite\".\"Title\" != ''")
->leftJoin('Group_Subsites', "\"Group_Subsites\".\"SubsiteID\" = \"Subsite\".\"ID\"") ->leftJoin('Group_Subsites', "\"Group_Subsites\".\"SubsiteID\" = \"Subsite\".\"ID\"")
->innerJoin('Group', "\"Group\".\"ID\" = \"Group_Subsites\".\"GroupID\" OR \"Group\".\"AccessAllSubsites\" = 1") ->innerJoin('Group',
->innerJoin('Group_Members', "\"Group_Members\".\"GroupID\"=\"Group\".\"ID\" AND \"Group_Members\".\"MemberID\" = $member->ID") "\"Group\".\"ID\" = \"Group_Subsites\".\"GroupID\" OR \"Group\".\"AccessAllSubsites\" = 1")
->innerJoin('Permission', "\"Group\".\"ID\"=\"Permission\".\"GroupID\" AND \"Permission\".\"Code\" IN ($SQL_codes, 'CMS_ACCESS_LeftAndMain', 'ADMIN')"); ->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')");
if(!$subsites) $subsites = new ArrayList(); if (!$subsites) {
$subsites = new ArrayList();
}
$rolesSubsites = DataList::create(Subsite::class) $rolesSubsites = DataList::create(Subsite::class)
->where("\"Subsite\".\"Title\" != ''") ->where("\"Subsite\".\"Title\" != ''")
->leftJoin('Group_Subsites', "\"Group_Subsites\".\"SubsiteID\" = \"Subsite\".\"ID\"") ->leftJoin('Group_Subsites', "\"Group_Subsites\".\"SubsiteID\" = \"Subsite\".\"ID\"")
->innerJoin('Group', "\"Group\".\"ID\" = \"Group_Subsites\".\"GroupID\" OR \"Group\".\"AccessAllSubsites\" = 1") ->innerJoin('Group',
->innerJoin('Group_Members', "\"Group_Members\".\"GroupID\"=\"Group\".\"ID\" AND \"Group_Members\".\"MemberID\" = $member->ID") "\"Group\".\"ID\" = \"Group_Subsites\".\"GroupID\" OR \"Group\".\"AccessAllSubsites\" = 1")
->innerJoin('Group_Members',
"\"Group_Members\".\"GroupID\"=\"Group\".\"ID\" AND \"Group_Members\".\"MemberID\" = $member->ID")
->innerJoin('Group_Roles', "\"Group_Roles\".\"GroupID\"=\"Group\".\"ID\"") ->innerJoin('Group_Roles', "\"Group_Roles\".\"GroupID\"=\"Group\".\"ID\"")
->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) {
if(!$subsites->find('ID', $subsite->ID)) { foreach ($rolesSubsites as $subsite) {
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)) {
if(self::hasMainSitePermission($member, $permCode)) { $permCode = [$permCode];
$subsites=$subsites->toArray(); }
if (self::hasMainSitePermission($member, $permCode)) {
$subsites = $subsites->toArray();
$mainSite = new Subsite(); $mainSite = new Subsite();
$mainSite->Title = $mainSiteTitle; $mainSite->Title = $mainSiteTitle;
array_unshift($subsites, $mainSite); array_unshift($subsites, $mainSite);
$subsites=ArrayList::create($subsites); $subsites = ArrayList::create($subsites);
} }
} }
@ -412,22 +469,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) {
$hostmap = array(); $file = Director::baseFolder() . '/subsites/host-map.php';
}
$hostmap = [];
$subsites = DataObject::get(Subsite::class); $subsites = DataObject::get(Subsite::class);
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";
@ -452,15 +522,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 = ['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);
@ -497,7 +575,7 @@ class Subsite extends DataObject {
* *
* @var array * @var array
*/ */
private static $db = array( private static $db = [
'Title' => 'Varchar(255)', 'Title' => 'Varchar(255)',
'RedirectURL' => 'Varchar(255)', 'RedirectURL' => 'Varchar(255)',
'DefaultSite' => 'Boolean', 'DefaultSite' => 'Boolean',
@ -510,41 +588,41 @@ class Subsite extends DataObject {
// Comma-separated list of disallowed page types // Comma-separated list of disallowed page types
'PageTypeBlacklist' => 'Text', 'PageTypeBlacklist' => 'Text',
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $has_many = array( private static $has_many = [
'Domains' => SubsiteDomain::class, 'Domains' => SubsiteDomain::class,
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $belongs_many_many = array( private static $belongs_many_many = [
"Groups" => "SilverStripe\\Security\\Group", "Groups" => "SilverStripe\\Security\\Group",
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $defaults = array( private static $defaults = [
'IsPublic' => 1 'IsPublic' => 1
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $searchable_fields = array( private static $searchable_fields = [
'Title', 'Title',
'Domains.Domain', 'Domains.Domain',
'IsPublic', 'IsPublic',
); ];
/** /**
* *
@ -556,7 +634,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;
} }
@ -565,18 +644,20 @@ 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",
_t('Subsite.DomainsListTitle',"Domains"), _t('Subsite.DomainsListTitle', "Domains"),
$this->Domains(), $this->Domains(),
GridFieldConfig_RecordEditor::create(10) GridFieldConfig_RecordEditor::create(10)
); );
}else { } else {
$domainTable = new LiteralField( $domainTable = new LiteralField(
'Domains', 'Domains',
'<p>'._t('Subsite.DOMAINSAVEFIRST', 'You can only add domains after saving for the first time').'</p>' '<p>' . _t('Subsite.DOMAINSAVEFIRST',
'You can only add domains after saving for the first time') . '</p>'
); );
} }
@ -586,9 +667,9 @@ class Subsite extends DataObject {
(new IntlLocales)->getLocales() (new IntlLocales)->getLocales()
); );
$pageTypeMap = array(); $pageTypeMap = [];
$pageTypes = SiteTree::page_type_classes(); $pageTypes = SiteTree::page_type_classes();
foreach($pageTypes as $pageType) { foreach ($pageTypes as $pageType) {
$pageTypeMap[$pageType] = singleton($pageType)->i18n_singular_name(); $pageTypeMap[$pageType] = singleton($pageType)->i18n_singular_name();
} }
asort($pageTypeMap); asort($pageTypeMap);
@ -611,7 +692,7 @@ class Subsite extends DataObject {
new CheckboxField('DefaultSite', $this->fieldLabel('DefaultSite'), $this->DefaultSite), new CheckboxField('DefaultSite', $this->fieldLabel('DefaultSite'), $this->DefaultSite),
new CheckboxField('IsPublic', $this->fieldLabel('IsPublic'), $this->IsPublic), new CheckboxField('IsPublic', $this->fieldLabel('IsPublic'), $this->IsPublic),
new DropdownField('Theme',$this->fieldLabel('Theme'), $this->allowedThemes(), $this->Theme), new DropdownField('Theme', $this->fieldLabel('Theme'), $this->allowedThemes(), $this->Theme),
new LiteralField( new LiteralField(
@ -643,7 +724,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');
@ -663,15 +745,18 @@ 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 = [];
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] == '.') {
$theme = strtok($theme,'_'); continue;
}
$theme = strtok($theme, '_');
$themes[$theme] = $theme; $themes[$theme] = $theme;
} }
ksort($themes); ksort($themes);
@ -683,8 +768,9 @@ 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 {
return i18n::get_locale(); return i18n::get_locale();
@ -695,9 +781,10 @@ 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"'));
} }
return $result; return $result;
@ -708,7 +795,8 @@ class Subsite extends DataObject {
* *
* @return void * @return void
*/ */
public function onAfterWrite() { public function onAfterWrite()
{
Subsite::writeHostMap(); Subsite::writeHostMap();
parent::onAfterWrite(); parent::onAfterWrite();
} }
@ -719,19 +807,20 @@ 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) { {
$domains = DataObject::get(SubsiteDomain::class, "\"SubsiteID\" = $this->ID", "\"IsPrimary\" DESC","", 1); if ($this->ID) {
if($domains && $domains->Count()>0) { $domains = DataObject::get(SubsiteDomain::class, "\"SubsiteID\" = $this->ID", "\"IsPrimary\" DESC", "", 1);
if ($domains && $domains->Count() > 0) {
$domain = $domains->First()->Domain; $domain = $domains->First()->Domain;
// If there are wildcards in the primary domain (not recommended), make some // If there are wildcards in the primary domain (not recommended), make some
// educated guesses about what to replace them with: // educated guesses about what to replace them with:
$domain = preg_replace('/\.\*$/',".$_SERVER[HTTP_HOST]", $domain); $domain = preg_replace('/\.\*$/', ".$_SERVER[HTTP_HOST]", $domain);
// Default to "subsite." prefix for first wildcard // Default to "subsite." prefix for first wildcard
// TODO Whats the significance of "subsite" in this context?! // TODO Whats the significance of "subsite" in this context?!
$domain = preg_replace('/^\*\./',"subsite.", $domain); $domain = preg_replace('/^\*\./', "subsite.", $domain);
// *Only* removes "intermediate" subdomains, so 'subdomain.www.domain.com' becomes 'subdomain.domain.com' // *Only* removes "intermediate" subdomains, so 'subdomain.www.domain.com' becomes 'subdomain.domain.com'
$domain = str_replace('.www.','.', $domain); $domain = str_replace('.www.', '.', $domain);
return $domain; return $domain;
} }
@ -746,7 +835,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();
} }
@ -754,14 +844,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;
} }
@ -770,12 +862,13 @@ 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',
'Created a copy of {title}', 'Created a copy of {title}',
array('title' => Convert::raw2js($this->Title)) ['title' => Convert::raw2js($this->Title)]
); );
return <<<JS return <<<JS
@ -787,7 +880,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);
} }
@ -796,9 +890,11 @@ JS;
* @param array $permissionCodes * @param array $permissionCodes
* @return DataList * @return DataList
*/ */
public function getMembersByPermission($permissionCodes = array('ADMIN')){ public function getMembersByPermission($permissionCodes = ['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);
@ -817,7 +913,8 @@ JS;
/** /**
* 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');
@ -829,13 +926,13 @@ JS;
* issues with having to check whether or not the new parents have been added to the site tree * issues with having to check whether or not the new parents have been added to the site tree
* when a page, etc, is duplicated * when a page, etc, is duplicated
*/ */
$stack = array(array(0,0)); $stack = [[0, 0]];
while(count($stack) > 0) { while (count($stack) > 0) {
list($sourceParentID, $destParentID) = array_pop($stack); list($sourceParentID, $destParentID) = array_pop($stack);
$children = Versioned::get_by_stage('Page', 'Live', "\"ParentID\" = $sourceParentID", ''); $children = Versioned::get_by_stage('Page', 'Live', "\"ParentID\" = $sourceParentID", '');
if($children) { if ($children) {
foreach($children as $child) { foreach ($children as $child) {
self::changeSubsite($duplicate->ID); //Change to destination subsite self::changeSubsite($duplicate->ID); //Change to destination subsite
$childClone = $child->duplicateToSubsite($duplicate, false); $childClone = $child->duplicateToSubsite($duplicate, false);
@ -845,7 +942,7 @@ JS;
self::changeSubsite($this->ID); //Change Back to this subsite self::changeSubsite($this->ID); //Change Back to this subsite
array_push($stack, array($child->ID, $childClone->ID)); array_push($stack, [$child->ID, $childClone->ID]);
} }
} }
} }

View File

@ -3,19 +3,19 @@
namespace SilverStripe\Subsites\Model; namespace SilverStripe\Subsites\Model;
use SilverStripe\Forms\TextField; use SilverStripe\Core\Convert;
use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\Core\Convert; use SilverStripe\Forms\TextField;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
/** /**
* @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
{
private static $table_name = 'SubsiteDomain'; private static $table_name = 'SubsiteDomain';
@ -29,34 +29,35 @@ class SubsiteDomain extends DataObject {
* *
* @var array * @var array
*/ */
private static $db = array( private static $db = [
"Domain" => "Varchar(255)", "Domain" => "Varchar(255)",
"IsPrimary" => "Boolean", "IsPrimary" => "Boolean",
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $has_one = array( private static $has_one = [
"Subsite" => Subsite::class, "Subsite" => Subsite::class,
); ];
/** /**
* *
* @var array * @var array
*/ */
private static $summary_fields=array( private static $summary_fields = [
'Domain', 'Domain',
'IsPrimary', 'IsPrimary',
); ];
/** /**
* Whenever a Subsite Domain is written, rewrite the hostmap * Whenever a Subsite Domain is written, rewrite the hostmap
* *
* @return void * @return void
*/ */
public function onAfterWrite() { public function onAfterWrite()
{
Subsite::writeHostMap(); Subsite::writeHostMap();
} }
@ -64,7 +65,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'))
@ -79,7 +81,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');
@ -91,7 +94,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

@ -3,51 +3,53 @@
namespace SilverStripe\Subsites\Pages; namespace SilverStripe\Subsites\Pages;
use SilverStripe\ORM\DataObject; use SilverStripe\CMS\Model\VirtualPage;
use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Control\Controller; use SilverStripe\Control\Controller;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\CMS\Model\VirtualPage; use SilverStripe\Forms\DropdownField;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\Subsites\Forms\SubsitesTreeDropdownField; use SilverStripe\Subsites\Forms\SubsitesTreeDropdownField;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\View\ArrayData;
class SubsitesVirtualPage extends VirtualPage { class SubsitesVirtualPage extends VirtualPage
{
private static $table_name = 'SubsitesVirtualPage'; private static $table_name = 'SubsitesVirtualPage';
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 = [
'CustomMetaTitle' => 'Varchar(255)', 'CustomMetaTitle' => 'Varchar(255)',
'CustomMetaKeywords' => 'Varchar(255)', 'CustomMetaKeywords' => 'Varchar(255)',
'CustomMetaDescription' => 'Text', 'CustomMetaDescription' => 'Text',
'CustomExtraMeta' => 'HTMLText' 'CustomExtraMeta' => 'HTMLText'
); ];
public function getCMSFields() { public function getCMSFields()
{
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$subsites = DataObject::get(Subsite::class); $subsites = DataObject::get(Subsite::class);
if(!$subsites) { if (!$subsites) {
$subsites = new ArrayList(); $subsites = new ArrayList();
}else { } else {
$subsites=ArrayList::create($subsites->toArray()); $subsites = ArrayList::create($subsites->toArray());
} }
$subsites->push(new ArrayData(array('Title' => 'Main site', 'ID' => 0))); $subsites->push(new ArrayData(['Title' => 'Main site', 'ID' => 0]));
$fields->addFieldToTab( $fields->addFieldToTab(
'Root.Main', 'Root.Main',
DropdownField::create( DropdownField::create(
"CopyContentFromID_SubsiteID", "CopyContentFromID_SubsiteID",
_t('SubsitesVirtualPage.SubsiteField',Subsite::class), _t('SubsitesVirtualPage.SubsiteField', Subsite::class),
$subsites->map('ID', 'Title') $subsites->map('ID', 'Title')
)->addExtraClass('subsitestreedropdownfield-chooser no-change-track'), )->addExtraClass('subsitestreedropdownfield-chooser no-change-track'),
'CopyContentFromID' 'CopyContentFromID'
@ -62,14 +64,14 @@ class SubsitesVirtualPage extends VirtualPage {
"MenuTitle" "MenuTitle"
); );
if(Controller::has_curr() && Controller::curr()->getRequest()) { if (Controller::has_curr() && Controller::curr()->getRequest()) {
$subsiteID = Controller::curr()->getRequest()->requestVar('CopyContentFromID_SubsiteID'); $subsiteID = Controller::curr()->getRequest()->requestVar('CopyContentFromID_SubsiteID');
$pageSelectionField->setSubsiteID($subsiteID); $pageSelectionField->setSubsiteID($subsiteID);
} }
$fields->replaceField('CopyContentFromID', $pageSelectionField); $fields->replaceField('CopyContentFromID', $pageSelectionField);
// Create links back to the original object in the CMS // Create links back to the original object in the CMS
if($this->CopyContentFromID) { if ($this->CopyContentFromID) {
$editLink = "admin/pages/edit/show/$this->CopyContentFromID/?SubsiteID=" . $this->CopyContentFrom()->SubsiteID; $editLink = "admin/pages/edit/show/$this->CopyContentFromID/?SubsiteID=" . $this->CopyContentFrom()->SubsiteID;
$linkToContent = " $linkToContent = "
<a class=\"cmsEditlink\" href=\"$editLink\">" . <a class=\"cmsEditlink\" href=\"$editLink\">" .
@ -121,70 +123,89 @@ 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');
$labels['CustomMetaDescription'] = _t('Subsite.CustomMetaDescription','Description'); $labels['CustomMetaDescription'] = _t('Subsite.CustomMetaDescription', 'Description');
$labels['CustomExtraMeta'] = _t('Subsite.CustomExtraMeta','Custom Meta Tags'); $labels['CustomExtraMeta'] = _t('Subsite.CustomExtraMeta', 'Custom Meta Tags');
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('SilverStripe\\CMS\\Model\\SiteTree', $this->CopyContentFromID) ? false : true; if ($this->CopyContentFromID) {
$this->HasBrokenLink = DataObject::get_by_id('SilverStripe\\CMS\\Model\\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
// needs to be duplicated from parent to find out the exact reason the validation failed. // needs to be duplicated from parent to find out the exact reason the validation failed.
if(!$isValid) { if (!$isValid) {
$IDFilter = ($this->ID) ? "AND \"SiteTree\".\"ID\" <> $this->ID" : null; $IDFilter = ($this->ID) ? "AND \"SiteTree\".\"ID\" <> $this->ID" : null;
$parentFilter = null; $parentFilter = null;
if(Config::inst()->get('SilverStripe\\CMS\\Model\\SiteTree', 'nested_urls')) { if (Config::inst()->get('SilverStripe\\CMS\\Model\\SiteTree', 'nested_urls')) {
if($this->ParentID) { if ($this->ParentID) {
$parentFilter = " AND \"SiteTree\".\"ParentID\" = $this->ParentID"; $parentFilter = " AND \"SiteTree\".\"ParentID\" = $this->ParentID";
} else { } else {
$parentFilter = ' AND "SiteTree"."ParentID" = 0'; $parentFilter = ' AND "SiteTree"."ParentID" = 0';

View File

@ -3,22 +3,23 @@
namespace SilverStripe\Subsites\Reports; namespace SilverStripe\Subsites\Reports;
use SilverStripe\Forms\TreeMultiselectField;
use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TreeMultiselectField;
use SilverStripe\Reports\ReportWrapper; use SilverStripe\Reports\ReportWrapper;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
/** /**
* 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 ReportWrapper { class SubsiteReportWrapper extends ReportWrapper
{
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Filtering // Filtering
function parameterFields() { 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');
@ -30,12 +31,12 @@ class SubsiteReportWrapper extends ReportWrapper {
$subsiteField->setValue(array_keys($options)); $subsiteField->setValue(array_keys($options));
// We don't need to make the field editable if only one subsite is available // We don't need to make the field editable if only one subsite is available
if(sizeof($options) <= 1) { if (sizeof($options) <= 1) {
$subsiteField = $subsiteField->performReadonlyTransformation(); $subsiteField = $subsiteField->performReadonlyTransformation();
} }
$fields = parent::parameterFields(); $fields = parent::parameterFields();
if($fields) { if ($fields) {
$fields->insertBefore($subsiteField, $fields->First()->Name()); $fields->insertBefore($subsiteField, $fields->First()->Name());
} else { } else {
$fields = new FieldList($subsiteField); $fields = new FieldList($subsiteField);
@ -46,7 +47,8 @@ class SubsiteReportWrapper extends ReportWrapper {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Columns // Columns
function columns() { function columns()
{
$columns = parent::columns(); $columns = parent::columns();
$columns['Subsite.Title'] = Subsite::class; $columns['Subsite.Title'] = Subsite::class;
return $columns; return $columns;
@ -55,9 +57,10 @@ class SubsiteReportWrapper extends ReportWrapper {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Querying // Querying
function beforeQuery($params) { 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'];
// Default: restrict to all accessible sites // Default: restrict to all accessible sites
@ -67,7 +70,9 @@ class SubsiteReportWrapper extends ReportWrapper {
Subsite::$force_subsite = join(',', array_keys($options)); Subsite::$force_subsite = join(',', array_keys($options));
} }
} }
function afterQuery() {
function afterQuery()
{
// Manually manage the subsite filtering // Manually manage the subsite filtering
Subsite::$force_subsite = null; Subsite::$force_subsite = null;
} }

View File

@ -3,12 +3,12 @@
namespace SilverStripe\Subsites\Tasks; namespace SilverStripe\Subsites\Tasks;
use SilverStripe\ORM\DataObject;
use SilverStripe\Dev\BuildTask;
use InvalidArgumentException; use InvalidArgumentException;
use SilverStripe\Dev\BuildTask;
use SilverStripe\ORM\DataObject;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Versioned\Versioned;
use SilverStripe\Subsites\Pages\SubsitesVirtualPage; use SilverStripe\Subsites\Pages\SubsitesVirtualPage;
use SilverStripe\Versioned\Versioned;
/** /**
@ -18,22 +18,32 @@ use SilverStripe\Subsites\Pages\SubsitesVirtualPage;
* *
* 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) { 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::class, $subsiteFromId); $subsiteFrom = DataObject::get_by_id(Subsite::class, $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::class, $subsiteToId); $subsiteTo = DataObject::get_by_id(Subsite::class, $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');
@ -43,15 +53,16 @@ class SubsiteCopyPagesTask extends BuildTask {
// This will make sure that the new parents on the new subsite are correct, and there are no funny // This will make sure that the new parents on the new subsite are correct, and there are no funny
// issues with having to check whether or not the new parents have been added to the site tree // issues with having to check whether or not the new parents have been added to the site tree
// when a page, etc, is duplicated // when a page, etc, is duplicated
$stack = array(array(0,0)); $stack = [[0, 0]];
while(count($stack) > 0) { while (count($stack) > 0) {
list($sourceParentID, $destParentID) = array_pop($stack); list($sourceParentID, $destParentID) = array_pop($stack);
$children = Versioned::get_by_stage('SilverStripe\\CMS\\Model\\SiteTree', 'Live', "\"ParentID\" = $sourceParentID", ''); $children = Versioned::get_by_stage('SilverStripe\\CMS\\Model\\SiteTree', 'Live',
"\"ParentID\" = $sourceParentID", '');
if($children) { if ($children) {
foreach($children as $child) { foreach ($children as $child) {
if($useVirtualPages) { if ($useVirtualPages) {
$childClone = new SubsitesVirtualPage(); $childClone = new SubsitesVirtualPage();
$childClone->writeToStage('Stage'); $childClone->writeToStage('Stage');
$childClone->CopyContentFromID = $child->ID; $childClone->CopyContentFromID = $child->ID;
@ -63,7 +74,7 @@ class SubsiteCopyPagesTask extends BuildTask {
$childClone->ParentID = $destParentID; $childClone->ParentID = $destParentID;
$childClone->writeToStage('Stage'); $childClone->writeToStage('Stage');
$childClone->publish('Stage', 'Live'); $childClone->publish('Stage', 'Live');
array_push($stack, array($child->ID, $childClone->ID)); array_push($stack, [$child->ID, $childClone->ID]);
$this->log(sprintf('Copied "%s" (#%d, %s)', $child->Title, $child->ID, $child->Link())); $this->log(sprintf('Copied "%s" (#%d, %s)', $child->Title, $child->ID, $child->Link()));
} }
@ -73,7 +84,8 @@ class SubsiteCopyPagesTask extends BuildTask {
} }
} }
function log($msg) { function log($msg)
{
echo $msg . "\n"; echo $msg . "\n";
} }
} }

View File

@ -3,9 +3,11 @@
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class BaseSubsiteTest extends SapphireTest { class BaseSubsiteTest extends SapphireTest
{
function setUp() { function setUp()
{
parent::setUp(); parent::setUp();
Subsite::$use_session_subsiteid = true; Subsite::$use_session_subsiteid = true;
@ -14,7 +16,8 @@ class BaseSubsiteTest extends SapphireTest {
/** /**
* Avoid subsites filtering on fixture fetching. * Avoid subsites filtering on fixture fetching.
*/ */
function objFromFixture($class, $id) { 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);
@ -25,7 +28,8 @@ class BaseSubsiteTest extends SapphireTest {
/** /**
* Tests the initial state of disable_subsite_filter * Tests the initial state of disable_subsite_filter
*/ */
function testDisableSubsiteFilter() { function testDisableSubsiteFilter()
{
$this->assertFalse(Subsite::$disable_subsite_filter); $this->assertFalse(Subsite::$disable_subsite_filter);
} }

View File

@ -1,16 +1,18 @@
<?php <?php
use SilverStripe\Assets\File; use SilverStripe\Assets\File;
use SilverStripe\Forms\FieldList;
use SilverStripe\Assets\Folder; use SilverStripe\Assets\Folder;
use SilverStripe\Forms\FieldList;
use SilverStripe\Subsites\Extensions\FileSubsites; use SilverStripe\Subsites\Extensions\FileSubsites;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class FileSubsitesTest extends BaseSubsiteTest { class FileSubsitesTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function testTrivialFeatures() { function testTrivialFeatures()
{
$this->assertTrue(is_array(singleton(FileSubsites::class)->extraStatics())); $this->assertTrue(is_array(singleton(FileSubsites::class)->extraStatics()));
$file = new File(); $file = new File();
$file->Name = 'FileTitle'; $file->Name = 'FileTitle';
@ -23,7 +25,8 @@ class FileSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($file->cacheKeyComponent(), 'subsite-1'); $this->assertEquals($file->cacheKeyComponent(), 'subsite-1');
} }
function testWritingSubsiteID() { function testWritingSubsiteID()
{
$this->objFromFixture('SilverStripe\\Security\\Member', 'admin')->logIn(); $this->objFromFixture('SilverStripe\\Security\\Member', 'admin')->logIn();
$subsite = $this->objFromFixture(Subsite::class, 'domaintest1'); $subsite = $this->objFromFixture(Subsite::class, 'domaintest1');
@ -61,7 +64,8 @@ class FileSubsitesTest extends BaseSubsiteTest {
$this->assertEquals($folder->SubsiteID, $file->SubsiteID); $this->assertEquals($folder->SubsiteID, $file->SubsiteID);
} }
function testSubsitesFolderDropdown() { function testSubsitesFolderDropdown()
{
$this->objFromFixture('SilverStripe\\Security\\Member', 'admin')->logIn(); $this->objFromFixture('SilverStripe\\Security\\Member', 'admin')->logIn();
$file = new Folder(); $file = new Folder();
@ -69,7 +73,7 @@ class FileSubsitesTest extends BaseSubsiteTest {
$source = array_values($file->getCMSFields()->dataFieldByName('SubsiteID')->getSource()); $source = array_values($file->getCMSFields()->dataFieldByName('SubsiteID')->getSource());
asort($source); asort($source);
$this->assertEquals(array( $this->assertEquals([
'Main site', 'Main site',
'Template', 'Template',
'Subsite1 Template', 'Subsite1 Template',
@ -77,7 +81,7 @@ class FileSubsitesTest extends BaseSubsiteTest {
'Test 1', 'Test 1',
'Test 2', 'Test 2',
'Test 3' 'Test 3'
), $source); ], $source);
} }
} }

View File

@ -6,18 +6,21 @@ use SilverStripe\Subsites\Extensions\GroupSubsites;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class GroupSubsitesTest extends BaseSubsiteTest { class GroupSubsitesTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
protected $requireDefaultRecordsFrom = array(GroupSubsites::class); protected $requireDefaultRecordsFrom = [GroupSubsites::class];
function testTrivialFeatures() { function testTrivialFeatures()
{
$this->assertTrue(is_array(singleton(GroupSubsites::class)->extraStatics())); $this->assertTrue(is_array(singleton(GroupSubsites::class)->extraStatics()));
$this->assertTrue(is_array(singleton(GroupSubsites::class)->providePermissions())); $this->assertTrue(is_array(singleton(GroupSubsites::class)->providePermissions()));
$this->assertTrue(singleton('SilverStripe\\Security\\Group')->getCMSFields() instanceof FieldList); $this->assertTrue(singleton('SilverStripe\\Security\\Group')->getCMSFields() instanceof FieldList);
} }
function testAlternateTreeTitle() { 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,20 +1,22 @@
<?php <?php
use SilverStripe\Admin\LeftAndMain; use SilverStripe\Admin\LeftAndMain;
use SilverStripe\AssetAdmin\Controller\AssetAdmin;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\AssetAdmin\Controller\AssetAdmin;
class LeftAndMainSubsitesTest extends FunctionalTest { class LeftAndMainSubsitesTest extends FunctionalTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
/** /**
* Avoid subsites filtering on fixture fetching. * Avoid subsites filtering on fixture fetching.
*/ */
function objFromFixture($class, $id) { 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);
@ -22,32 +24,34 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
return $obj; return $obj;
} }
function testSectionSites() { function testSectionSites()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member');
$cmsmain = singleton('SilverStripe\\CMS\\Controllers\\CMSMain'); $cmsmain = singleton('SilverStripe\\CMS\\Controllers\\CMSMain');
$subsites = $cmsmain->sectionSites(true, "Main site", $member); $subsites = $cmsmain->sectionSites(true, "Main site", $member);
$this->assertDOSEquals(array( $this->assertDOSEquals([
array('Title' =>'Subsite1 Template') ['Title' => 'Subsite1 Template']
), $subsites, 'Lists member-accessible sites for the accessible controller.'); ], $subsites, 'Lists member-accessible sites for the accessible controller.');
$assetadmin = singleton(AssetAdmin::class); $assetadmin = singleton(AssetAdmin::class);
$subsites = $assetadmin->sectionSites(true, "Main site", $member); $subsites = $assetadmin->sectionSites(true, "Main site", $member);
$this->assertDOSEquals(array(), $subsites, 'Does not list any sites for forbidden controller.'); $this->assertDOSEquals([], $subsites, 'Does not list any sites for forbidden controller.');
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor');
$cmsmain = singleton('SilverStripe\\CMS\\Controllers\\CMSMain'); $cmsmain = singleton('SilverStripe\\CMS\\Controllers\\CMSMain');
$subsites = $cmsmain->sectionSites(true, "Main site", $member); $subsites = $cmsmain->sectionSites(true, "Main site", $member);
$this->assertDOSContains(array( $this->assertDOSContains([
array('Title' =>'Main site') ['Title' => 'Main site']
), $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() { function testAccessChecksDontChangeCurrentSubsite()
$admin = $this->objFromFixture("SilverStripe\\Security\\Member","admin"); {
$admin = $this->objFromFixture("SilverStripe\\Security\\Member", "admin");
$this->loginAs($admin); $this->loginAs($admin);
$ids = array(); $ids = [];
$subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1'); $subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$subsite2 = $this->objFromFixture(Subsite::class, 'domaintest2'); $subsite2 = $this->objFromFixture(Subsite::class, 'domaintest2');
@ -61,7 +65,7 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
// Enable session-based subsite tracking. // Enable session-based subsite tracking.
Subsite::$use_session_subsiteid = true; Subsite::$use_session_subsiteid = true;
foreach($ids as $id) { foreach ($ids as $id) {
Subsite::changeSubsite($id); Subsite::changeSubsite($id);
$this->assertEquals($id, Subsite::currentSubsiteID()); $this->assertEquals($id, Subsite::currentSubsiteID());
@ -73,17 +77,20 @@ class LeftAndMainSubsitesTest extends FunctionalTest {
} }
function testShouldChangeSubsite() { function testShouldChangeSubsite()
{
$l = new LeftAndMain(); $l = new LeftAndMain();
Config::inst()->nest(); Config::inst()->nest();
Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global', false); Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global',
false);
$this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 5)); $this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 5));
$this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 0)); $this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 0));
$this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 5)); $this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 5));
$this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 1)); $this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 1));
Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global', true); Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global',
true);
$this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 5)); $this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 5));
$this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 0)); $this->assertFalse($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 0, 0));
$this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 5)); $this->assertTrue($l->shouldChangeSubsite('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 1, 5));

View File

@ -1,14 +1,16 @@
<?php <?php
use SilverStripe\SiteConfig\SiteConfig; use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Extensions\SiteConfigSubsites; use SilverStripe\Subsites\Extensions\SiteConfigSubsites;
use SilverStripe\Subsites\Model\Subsite;
class SiteConfigSubsitesTest extends BaseSubsiteTest { class SiteConfigSubsitesTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function testEachSubsiteHasAUniqueSiteConfig() { function testEachSubsiteHasAUniqueSiteConfig()
{
$subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1'); $subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$subsite2 = $this->objFromFixture(Subsite::class, 'domaintest2'); $subsite2 = $this->objFromFixture(Subsite::class, 'domaintest2');

View File

@ -1,33 +1,35 @@
<?php <?php
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Forms\FieldList;
use SilverStripe\Control\Session;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\CMS\Model\ErrorPage;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Session;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
use SilverStripe\CMS\Model\ErrorPage; use SilverStripe\Forms\FieldList;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Extensions\SiteTreeSubsites;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Pages\SubsitesVirtualPage; use SilverStripe\Subsites\Pages\SubsitesVirtualPage;
use SilverStripe\Subsites\Extensions\SiteTreeSubsites;
class SiteTreeSubsitesTest extends BaseSubsiteTest { class SiteTreeSubsitesTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
protected $extraDataObjects = array( protected $extraDataObjects = [
'SiteTreeSubsitesTest_ClassA', 'SiteTreeSubsitesTest_ClassA',
'SiteTreeSubsitesTest_ClassB', 'SiteTreeSubsitesTest_ClassB',
'SiteTreeSubsitesTest_ErrorPage' 'SiteTreeSubsitesTest_ErrorPage'
); ];
protected $illegalExtensions = array( protected $illegalExtensions = [
'SilverStripe\CMS\Model\SiteTree' => array('Translatable') 'SilverStripe\CMS\Model\SiteTree' => ['Translatable']
); ];
function testPagesInDifferentSubsitesCanShareURLSegment() { function testPagesInDifferentSubsitesCanShareURLSegment()
{
$subsiteMain = $this->objFromFixture(Subsite::class, 'main'); $subsiteMain = $this->objFromFixture(Subsite::class, 'main');
$subsite1 = $this->objFromFixture(Subsite::class, 'subsite1'); $subsite1 = $this->objFromFixture(Subsite::class, 'subsite1');
@ -57,7 +59,8 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
); );
} }
function testBasicSanity() { function testBasicSanity()
{
$this->assertTrue(singleton('SilverStripe\\CMS\\Model\\SiteTree')->getSiteConfig() instanceof SiteConfig); $this->assertTrue(singleton('SilverStripe\\CMS\\Model\\SiteTree')->getSiteConfig() instanceof SiteConfig);
// The following assert is breaking in Translatable. // The following assert is breaking in Translatable.
$this->assertTrue(singleton('SilverStripe\\CMS\\Model\\SiteTree')->getCMSFields() instanceof FieldList); $this->assertTrue(singleton('SilverStripe\\CMS\\Model\\SiteTree')->getCMSFields() instanceof FieldList);
@ -65,17 +68,19 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
$this->assertTrue(is_array(singleton(SiteTreeSubsites::class)->extraStatics())); $this->assertTrue(is_array(singleton(SiteTreeSubsites::class)->extraStatics()));
} }
function testErrorPageLocations() { function testErrorPageLocations()
{
$subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1'); $subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1');
Subsite::changeSubsite($subsite1->ID); Subsite::changeSubsite($subsite1->ID);
$path = SiteTreeSubsitesTest_ErrorPage::get_error_filename_spy(500); $path = SiteTreeSubsitesTest_ErrorPage::get_error_filename_spy(500);
$expected_path = 'error-500-'.$subsite1->domain().'.html'; $expected_path = 'error-500-' . $subsite1->domain() . '.html';
$this->assertEquals($expected_path, $path); $this->assertEquals($expected_path, $path);
} }
function testCanEditSiteTree() { function testCanEditSiteTree()
{
$admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'); $admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
$subsite1member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'); $subsite1member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member');
$subsite2member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite2member'); $subsite2member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite2member');
@ -118,10 +123,11 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
/** /**
* Similar to {@link SubsitesVirtualPageTest->testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()}. * Similar to {@link SubsitesVirtualPageTest->testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()}.
*/ */
function testTwoPagesWithSameURLOnDifferentSubsites() { 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::class,'domaintest1'); $s1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$s2 = $this->objFromFixture(Subsite::class,'domaintest2'); $s2 = $this->objFromFixture(Subsite::class, 'domaintest2');
$p1 = new SiteTree(); $p1 = new SiteTree();
$p1->Title = $p1->URLSegment = "test-page"; $p1->Title = $p1->URLSegment = "test-page";
@ -145,12 +151,13 @@ 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() { function testPageTypesBlacklistInClassDropdown()
{
$editor = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor'); $editor = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor');
Session::set("loggedInAs", $editor->ID); Session::set("loggedInAs", $editor->ID);
$s1 = $this->objFromFixture(Subsite::class,'domaintest1'); $s1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$s2 = $this->objFromFixture(Subsite::class,'domaintest2'); $s2 = $this->objFromFixture(Subsite::class, 'domaintest2');
$page = singleton('SilverStripe\\CMS\\Model\\SiteTree'); $page = singleton('SilverStripe\\CMS\\Model\\SiteTree');
$s1->PageTypeBlacklist = 'SiteTreeSubsitesTest_ClassA,ErrorPage'; $s1->PageTypeBlacklist = 'SiteTreeSubsitesTest_ClassA,ErrorPage';
@ -182,14 +189,15 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
); );
} }
function testPageTypesBlacklistInCMSMain() { function testPageTypesBlacklistInCMSMain()
{
$editor = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor'); $editor = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor');
Session::set("loggedInAs", $editor->ID); Session::set("loggedInAs", $editor->ID);
$cmsmain = new CMSMain(); $cmsmain = new CMSMain();
$s1 = $this->objFromFixture(Subsite::class,'domaintest1'); $s1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$s2 = $this->objFromFixture(Subsite::class,'domaintest2'); $s2 = $this->objFromFixture(Subsite::class, 'domaintest2');
$s1->PageTypeBlacklist = 'SiteTreeSubsitesTest_ClassA,ErrorPage'; $s1->PageTypeBlacklist = 'SiteTreeSubsitesTest_ClassA,ErrorPage';
$s1->write(); $s1->write();
@ -211,11 +219,16 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest {
} }
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
{
}
class SiteTreeSubsitesTest_ErrorPage extends ErrorPage implements TestOnly { class SiteTreeSubsitesTest_ErrorPage extends ErrorPage implements TestOnly
{
/** /**
* Helper method to call protected members * Helper method to call protected members
@ -223,7 +236,8 @@ class SiteTreeSubsitesTest_ErrorPage extends ErrorPage implements TestOnly {
* @param int $statusCode * @param int $statusCode
* @return string * @return string
*/ */
public static function get_error_filename_spy($statusCode) { public static function get_error_filename_spy($statusCode)
{
return self::get_error_filename($statusCode); return self::get_error_filename($statusCode);
} }
} }

View File

@ -3,11 +3,12 @@
use SilverStripe\Control\Session; use SilverStripe\Control\Session;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Controller\SubsiteXHRController; use SilverStripe\Subsites\Controller\SubsiteXHRController;
use SilverStripe\Subsites\Model\Subsite;
class SubsiteAdminFunctionalTest extends FunctionalTest { class SubsiteAdminFunctionalTest extends FunctionalTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
static $use_draft_site = true; static $use_draft_site = true;
@ -16,7 +17,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
/** /**
* 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) { 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();
@ -29,7 +31,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
/** /**
* Anonymous user cannot access anything. * Anonymous user cannot access anything.
*/ */
function testAnonymousIsForbiddenAdminAccess() { 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');
@ -45,7 +48,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() { function testAdminCanAccessAllSubsites()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -63,7 +67,8 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
'SubsiteXHRController is reachable'); 'SubsiteXHRController is reachable');
} }
function testAdminIsRedirectedToObjectsSubsite() { function testAdminIsRedirectedToObjectsSubsite()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -72,20 +77,25 @@ class SubsiteAdminFunctionalTest extends FunctionalTest {
Config::inst()->nest(); Config::inst()->nest();
Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global', false); Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global',
false);
Subsite::changeSubsite(0); Subsite::changeSubsite(0);
$this->getAndFollowAll("admin/pages/edit/show/$subsite1Home->ID"); $this->getAndFollowAll("admin/pages/edit/show/$subsite1Home->ID");
$this->assertEquals(Subsite::currentSubsiteID(), $subsite1Home->SubsiteID, 'Loading an object switches the subsite'); $this->assertEquals(Subsite::currentSubsiteID(), $subsite1Home->SubsiteID,
'Loading an object switches the subsite');
$this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section'); $this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section');
Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global', true); Config::modify()->set('SilverStripe\\CMS\\Controllers\\CMSPageEditController', 'treats_subsite_0_as_global',
true);
Subsite::changeSubsite(0); Subsite::changeSubsite(0);
$this->getAndFollowAll("admin/pages/edit/show/$subsite1Home->ID"); $this->getAndFollowAll("admin/pages/edit/show/$subsite1Home->ID");
$this->assertEquals(Subsite::currentSubsiteID(), $subsite1Home->SubsiteID, 'Loading a non-main-site object still switches the subsite if configured with treats_subsite_0_as_global'); $this->assertEquals(Subsite::currentSubsiteID(), $subsite1Home->SubsiteID,
'Loading a non-main-site object still switches the subsite if configured with treats_subsite_0_as_global');
$this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section'); $this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section');
$this->getAndFollowAll("admin/pages/edit/show/$mainSubsitePage->ID"); $this->getAndFollowAll("admin/pages/edit/show/$mainSubsitePage->ID");
$this->assertNotEquals(Subsite::currentSubsiteID(), $mainSubsitePage->SubsiteID, 'Loading a main-site object does not change the subsite if configured with treats_subsite_0_as_global'); $this->assertNotEquals(Subsite::currentSubsiteID(), $mainSubsitePage->SubsiteID,
'Loading a main-site object does not change the subsite if configured with treats_subsite_0_as_global');
$this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section'); $this->assertRegExp("#^admin/pages.*#", $this->mainSession->lastUrl(), 'Lands on the correct section');
Config::inst()->unnest(); Config::inst()->unnest();
@ -95,7 +105,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() { function testEditorCanAccessAllSubsites()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'editor');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
@ -116,7 +127,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() { function testSubsiteAdmin()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);

View File

@ -1,33 +1,38 @@
<?php <?php
use SilverStripe\Control\Session;
use SilverStripe\Control\Director;
use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Control\Director;
use SilverStripe\Control\Session;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
class SubsiteAdminTest extends BaseSubsiteTest { class SubsiteAdminTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
function adminLoggedInSession() { function adminLoggedInSession()
return new Session(array( {
return new Session([
'loggedInAs' => $this->idFromFixture('SilverStripe\\Security\\Member', 'admin') 'loggedInAs' => $this->idFromFixture('SilverStripe\\Security\\Member', 'admin')
)); ]);
} }
/** /**
* Test generation of the view * Test generation of the view
*/ */
function testBasicView() { function testBasicView()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite1ID = $this->objFromFixture(Subsite::class,'domaintest1')->ID; $subsite1ID = $this->objFromFixture(Subsite::class, 'domaintest1')->ID;
// Open the admin area logged in as admin // Open the admin area logged in as admin
$response1 = Director::test('admin/subsites/', null, $this->adminLoggedInSession()); $response1 = Director::test('admin/subsites/', null, $this->adminLoggedInSession());
// Confirm that this URL gets you the entire page, with the edit form loaded // Confirm that this URL gets you the entire page, with the edit form loaded
$response2 = Director::test("admin/subsites/Subsite/EditForm/field/Subsite/item/$subsite1ID/edit", null, $this->adminLoggedInSession()); $response2 = Director::test("admin/subsites/Subsite/EditForm/field/Subsite/item/$subsite1ID/edit", null,
$this->assertTrue(strpos($response2->getBody(), 'id="Form_ItemEditForm_ID"') !== false, "Testing Form_ItemEditForm_ID exists"); $this->adminLoggedInSession());
$this->assertTrue(strpos($response2->getBody(), 'id="Form_ItemEditForm_ID"') !== false,
"Testing Form_ItemEditForm_ID exists");
$this->assertTrue(strpos($response2->getBody(), '<head') !== false, "Testing <head> exists"); $this->assertTrue(strpos($response2->getBody(), '<head') !== false, "Testing <head> exists");
} }
@ -36,19 +41,22 @@ 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() { function testMainsiteAdminCanAccessAllSubsites()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
Session::set("loggedInAs", $member->ID); Session::set("loggedInAs", $member->ID);
$cmsMain = new CMSMain(); $cmsMain = new CMSMain();
foreach($cmsMain->Subsites() as $subsite) { foreach ($cmsMain->Subsites() as $subsite) {
$ids[$subsite->ID] = true; $ids[$subsite->ID] = true;
} }
$this->assertArrayHasKey(0, $ids, "Main site accessible"); $this->assertArrayHasKey(0, $ids, "Main site accessible");
$this->assertArrayHasKey($this->idFromFixture(Subsite::class,'main'), $ids, "Site with no groups inaccesible"); $this->assertArrayHasKey($this->idFromFixture(Subsite::class, 'main'), $ids, "Site with no groups inaccesible");
$this->assertArrayHasKey($this->idFromFixture(Subsite::class,'subsite1'), $ids, "Subsite1 Template inaccessible"); $this->assertArrayHasKey($this->idFromFixture(Subsite::class, 'subsite1'), $ids,
$this->assertArrayHasKey($this->idFromFixture(Subsite::class,'subsite2'), $ids, "Subsite2 Template inaccessible"); "Subsite1 Template inaccessible");
$this->assertArrayHasKey($this->idFromFixture(Subsite::class, 'subsite2'), $ids,
"Subsite2 Template inaccessible");
} }

View File

@ -1,23 +1,26 @@
<?php <?php
use SilverStripe\ORM\DataObject;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\ORM\DataObject;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Model\SubsiteDomain; use SilverStripe\Subsites\Model\SubsiteDomain;
class SubsiteTest extends BaseSubsiteTest { class SubsiteTest extends BaseSubsiteTest
{
static $fixture_file = 'subsites/tests/SubsiteTest.yml'; static $fixture_file = 'subsites/tests/SubsiteTest.yml';
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() { function tearDown()
{
parent::tearDown(); parent::tearDown();
Subsite::$strict_subdomain_matching = $this->origStrictSubdomainMatching; Subsite::$strict_subdomain_matching = $this->origStrictSubdomainMatching;
@ -26,7 +29,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() { function testSubsiteCreation()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
// Create the instance // Create the instance
@ -34,13 +38,13 @@ class SubsiteTest extends BaseSubsiteTest {
// Test that changeSubsite is working // Test that changeSubsite is working
Subsite::changeSubsite($template->ID); Subsite::changeSubsite($template->ID);
$tmplStaff = $this->objFromFixture('Page','staff'); $tmplStaff = $this->objFromFixture('Page', 'staff');
$tmplHome = DataObject::get_one('Page', "\"URLSegment\" = 'home'"); $tmplHome = DataObject::get_one('Page', "\"URLSegment\" = 'home'");
// Publish all the pages in the template, testing that DataObject::get only returns pages from the chosen subsite // Publish all the pages in the template, testing that DataObject::get only returns pages from the chosen subsite
$pages = DataObject::get("SilverStripe\\CMS\\Model\\SiteTree"); $pages = DataObject::get("SilverStripe\\CMS\\Model\\SiteTree");
$totalPages = $pages->Count(); $totalPages = $pages->Count();
foreach($pages as $page) { foreach ($pages as $page) {
$this->assertEquals($template->ID, $page->SubsiteID); $this->assertEquals($template->ID, $page->SubsiteID);
$page->publish('Stage', 'Live'); $page->publish('Stage', 'Live');
} }
@ -66,26 +70,31 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Confirm that domain lookup is working * Confirm that domain lookup is working
*/ */
function testDomainLookup() { function testDomainLookup()
{
// Clear existing fixtures // Clear existing fixtures
foreach(DataObject::get(Subsite::class) as $subsite) $subsite->delete(); foreach (DataObject::get(Subsite::class) as $subsite) {
foreach(DataObject::get(SubsiteDomain::class) as $domain) $domain->delete(); $subsite->delete();
}
foreach (DataObject::get(SubsiteDomain::class) 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([
'one.example.org' => true, 'one.example.org' => true,
'one.*' => false, 'one.*' => false,
)); ]);
$subsite2 = $this->createSubsiteWithDomains(array( $subsite2 = $this->createSubsiteWithDomains([
'two.mysite.com' => true, 'two.mysite.com' => true,
'*.mysite.com' => false, '*.mysite.com' => false,
'subdomain.onmultiplesubsites.com' => false, 'subdomain.onmultiplesubsites.com' => false,
)); ]);
$subsite3 = $this->createSubsiteWithDomains(array( $subsite3 = $this->createSubsiteWithDomains([
'three.*' => true, // wildcards in primary domain are not recommended 'three.*' => true, // wildcards in primary domain are not recommended
'subdomain.unique.com' => false, 'subdomain.unique.com' => false,
'*.onmultiplesubsites.com' => false, '*.onmultiplesubsites.com' => false,
)); ]);
$this->assertEquals( $this->assertEquals(
$subsite3->ID, $subsite3->ID,
@ -102,7 +111,7 @@ class SubsiteTest extends BaseSubsiteTest {
$failed = false; $failed = false;
try { try {
Subsite::getSubsiteIDForDomain('subdomain.onmultiplesubsites.com'); Subsite::getSubsiteIDForDomain('subdomain.onmultiplesubsites.com');
} catch(UnexpectedValueException $e) { } catch (UnexpectedValueException $e) {
$failed = true; $failed = true;
} }
$this->assertTrue( $this->assertTrue(
@ -136,21 +145,26 @@ class SubsiteTest extends BaseSubsiteTest {
} }
function testStrictSubdomainMatching() { function testStrictSubdomainMatching()
{
// Clear existing fixtures // Clear existing fixtures
foreach(DataObject::get(Subsite::class) as $subsite) $subsite->delete(); foreach (DataObject::get(Subsite::class) as $subsite) {
foreach(DataObject::get(SubsiteDomain::class) as $domain) $domain->delete(); $subsite->delete();
}
foreach (DataObject::get(SubsiteDomain::class) 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([
'example.org' => true, 'example.org' => true,
'example.com' => false, 'example.com' => false,
'*.wildcard.com' => false, '*.wildcard.com' => false,
)); ]);
$subsite2 = $this->createSubsiteWithDomains(array( $subsite2 = $this->createSubsiteWithDomains([
'www.example.org' => true, 'www.example.org' => true,
'www.wildcard.com' => false, 'www.wildcard.com' => false,
)); ]);
Subsite::$strict_subdomain_matching = false; Subsite::$strict_subdomain_matching = false;
@ -195,7 +209,7 @@ class SubsiteTest extends BaseSubsiteTest {
$failed = false; $failed = false;
try { try {
Subsite::getSubsiteIDForDomain('www.wildcard.com'); Subsite::getSubsiteIDForDomain('www.wildcard.com');
} catch(UnexpectedValueException $e) { } catch (UnexpectedValueException $e) {
$failed = true; $failed = true;
} }
$this->assertTrue( $this->assertTrue(
@ -205,17 +219,18 @@ class SubsiteTest extends BaseSubsiteTest {
} }
protected function createSubsiteWithDomains($domains) { protected function createSubsiteWithDomains($domains)
$subsite = new Subsite(array( {
$subsite = new Subsite([
'Title' => 'My Subsite' 'Title' => 'My Subsite'
)); ]);
$subsite->write(); $subsite->write();
foreach($domains as $domainStr => $isPrimary) { foreach ($domains as $domainStr => $isPrimary) {
$domain = new SubsiteDomain(array( $domain = new SubsiteDomain([
'Domain' => $domainStr, 'Domain' => $domainStr,
'IsPrimary' => $isPrimary, 'IsPrimary' => $isPrimary,
'SubsiteID' => $subsite->ID 'SubsiteID' => $subsite->ID
)); ]);
$domain->write(); $domain->write();
} }
@ -225,55 +240,60 @@ class SubsiteTest extends BaseSubsiteTest {
/** /**
* Test the Subsite->domain() method * Test the Subsite->domain() method
*/ */
function testDefaultDomain() { function testDefaultDomain()
{
$this->assertEquals('one.example.org', $this->assertEquals('one.example.org',
$this->objFromFixture(Subsite::class,'domaintest1')->domain()); $this->objFromFixture(Subsite::class, 'domaintest1')->domain());
$this->assertEquals('two.mysite.com', $this->assertEquals('two.mysite.com',
$this->objFromFixture(Subsite::class,'domaintest2')->domain()); $this->objFromFixture(Subsite::class, 'domaintest2')->domain());
$originalHTTPHost = $_SERVER['HTTP_HOST']; $originalHTTPHost = $_SERVER['HTTP_HOST'];
$_SERVER['HTTP_HOST'] = "www.example.org"; $_SERVER['HTTP_HOST'] = "www.example.org";
$this->assertEquals('three.example.org', $this->assertEquals('three.example.org',
$this->objFromFixture(Subsite::class,'domaintest3')->domain()); $this->objFromFixture(Subsite::class, 'domaintest3')->domain());
$_SERVER['HTTP_HOST'] = "mysite.example.org"; $_SERVER['HTTP_HOST'] = "mysite.example.org";
$this->assertEquals('three.mysite.example.org', $this->assertEquals('three.mysite.example.org',
$this->objFromFixture(Subsite::class,'domaintest3')->domain()); $this->objFromFixture(Subsite::class, 'domaintest3')->domain());
$this->assertEquals($_SERVER['HTTP_HOST'], singleton(Subsite::class)->PrimaryDomain); $this->assertEquals($_SERVER['HTTP_HOST'], singleton(Subsite::class)->PrimaryDomain);
$this->assertEquals('http://'.$_SERVER['HTTP_HOST'].Director::baseURL(), singleton(Subsite::class)->absoluteBaseURL()); $this->assertEquals('http://' . $_SERVER['HTTP_HOST'] . Director::baseURL(),
singleton(Subsite::class)->absoluteBaseURL());
$_SERVER['HTTP_HOST'] = $originalHTTPHost; $_SERVER['HTTP_HOST'] = $originalHTTPHost;
} }
function testAllSites() { function testAllSites()
{
$subsites = Subsite::all_sites(); $subsites = Subsite::all_sites();
$this->assertDOSEquals(array( $this->assertDOSEquals([
array('Title' =>'Main site'), ['Title' => 'Main site'],
array('Title' =>'Template'), ['Title' => 'Template'],
array('Title' =>'Subsite1 Template'), ['Title' => 'Subsite1 Template'],
array('Title' =>'Subsite2 Template'), ['Title' => 'Subsite2 Template'],
array('Title' =>'Test 1'), ['Title' => 'Test 1'],
array('Title' =>'Test 2'), ['Title' => 'Test 2'],
array('Title' =>'Test 3') ['Title' => 'Test 3']
), $subsites, 'Lists all subsites'); ], $subsites, 'Lists all subsites');
} }
function testAllAccessibleSites() { function testAllAccessibleSites()
{
$member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'); $member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member');
$subsites = Subsite::all_accessible_sites(true, 'Main site', $member); $subsites = Subsite::all_accessible_sites(true, 'Main site', $member);
$this->assertDOSEquals(array( $this->assertDOSEquals([
array('Title' =>'Subsite1 Template') ['Title' => 'Subsite1 Template']
), $subsites, 'Lists member-accessible sites.'); ], $subsites, 'Lists member-accessible sites.');
} }
/** /**
* Test Subsite::accessible_sites() * Test Subsite::accessible_sites()
*/ */
function testAccessibleSites() { function testAccessibleSites()
{
$member1Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null, $member1Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null,
$this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member')); $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'));
$member1SiteTitles = $member1Sites->column("Title"); $member1SiteTitles = $member1Sites->column("Title");
@ -284,14 +304,14 @@ class SubsiteTest extends BaseSubsiteTest {
$this->objFromFixture('SilverStripe\\Security\\Member', 'admin')); $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'));
$adminSiteTitles = $adminSites->column("Title"); $adminSiteTitles = $adminSites->column("Title");
sort($adminSiteTitles); sort($adminSiteTitles);
$this->assertEquals(array( $this->assertEquals([
'Subsite1 Template', 'Subsite1 Template',
'Subsite2 Template', 'Subsite2 Template',
'Template', 'Template',
'Test 1', 'Test 1',
'Test 2', 'Test 2',
'Test 3', 'Test 3',
), $adminSiteTitles); ], $adminSiteTitles);
$member2Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null, $member2Sites = Subsite::accessible_sites("CMS_ACCESS_CMSMain", false, null,
$this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member2')); $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member2'));
@ -300,7 +320,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() { function testhasMainSitePermission()
{
$admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin'); $admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'admin');
$subsite1member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member'); $subsite1member = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1member');
$subsite1admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1admin'); $subsite1admin = $this->objFromFixture('SilverStripe\\Security\\Member', 'subsite1admin');
@ -311,38 +332,39 @@ class SubsiteTest extends BaseSubsiteTest {
'Default permissions granted for super-admin' 'Default permissions granted for super-admin'
); );
$this->assertTrue( $this->assertTrue(
Subsite::hasMainSitePermission($admin, array("ADMIN")), Subsite::hasMainSitePermission($admin, ["ADMIN"]),
'ADMIN permissions granted for super-admin' 'ADMIN permissions granted for super-admin'
); );
$this->assertFalse( $this->assertFalse(
Subsite::hasMainSitePermission($subsite1admin, array("ADMIN")), Subsite::hasMainSitePermission($subsite1admin, ["ADMIN"]),
'ADMIN permissions (on main site) denied for subsite1 admin' 'ADMIN permissions (on main site) denied for subsite1 admin'
); );
$this->assertFalse( $this->assertFalse(
Subsite::hasMainSitePermission($subsite1admin, array("CMS_ACCESS_CMSMain")), Subsite::hasMainSitePermission($subsite1admin, ["CMS_ACCESS_CMSMain"]),
'CMS_ACCESS_CMSMain (on main site) denied for subsite1 admin' 'CMS_ACCESS_CMSMain (on main site) denied for subsite1 admin'
); );
$this->assertFalse( $this->assertFalse(
Subsite::hasMainSitePermission($allsubsitesauthor, array("ADMIN")), Subsite::hasMainSitePermission($allsubsitesauthor, ["ADMIN"]),
'ADMIN permissions (on main site) denied for CMS author with edit rights on all subsites' 'ADMIN permissions (on main site) denied for CMS author with edit rights on all subsites'
); );
$this->assertTrue( $this->assertTrue(
Subsite::hasMainSitePermission($allsubsitesauthor, array("CMS_ACCESS_CMSMain")), Subsite::hasMainSitePermission($allsubsitesauthor, ["CMS_ACCESS_CMSMain"]),
'CMS_ACCESS_CMSMain (on main site) granted for CMS author with edit rights on all subsites' 'CMS_ACCESS_CMSMain (on main site) granted for CMS author with edit rights on all subsites'
); );
$this->assertFalse( $this->assertFalse(
Subsite::hasMainSitePermission($subsite1member, array("ADMIN")), Subsite::hasMainSitePermission($subsite1member, ["ADMIN"]),
'ADMIN (on main site) denied for subsite1 subsite1 cms author' 'ADMIN (on main site) denied for subsite1 subsite1 cms author'
); );
$this->assertFalse( $this->assertFalse(
Subsite::hasMainSitePermission($subsite1member, array("CMS_ACCESS_CMSMain")), Subsite::hasMainSitePermission($subsite1member, ["CMS_ACCESS_CMSMain"]),
'CMS_ACCESS_CMSMain (on main site) denied for subsite1 cms author' 'CMS_ACCESS_CMSMain (on main site) denied for subsite1 cms author'
); );
} }
function testDuplicateSubsite() { function testDuplicateSubsite()
{
// get subsite1 & create page // get subsite1 & create page
$subsite1 = $this->objFromFixture(Subsite::class,'domaintest1'); $subsite1 = $this->objFromFixture(Subsite::class, 'domaintest1');
$subsite1->activate(); $subsite1->activate();
$page1 = new Page(); $page1 = new Page();
$page1->Title = 'MyAwesomePage'; $page1->Title = 'MyAwesomePage';

View File

@ -1,22 +1,23 @@
<?php <?php
use SilverStripe\Assets\Filesystem; use SilverStripe\Assets\Filesystem;
use SilverStripe\ORM\DB;
use SilverStripe\Core\Config\Config;
use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore; use SilverStripe\Assets\Tests\Storage\AssetStoreTest\TestAssetStore;
use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DB;
use SilverStripe\Subsites\Model\Subsite; use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Pages\SubsitesVirtualPage; use SilverStripe\Subsites\Pages\SubsitesVirtualPage;
use SilverStripe\Versioned\Versioned; use SilverStripe\Versioned\Versioned;
class SubsitesVirtualPageTest extends BaseSubsiteTest { class SubsitesVirtualPageTest extends BaseSubsiteTest
static $fixture_file = array( {
static $fixture_file = [
'subsites/tests/SubsiteTest.yml', 'subsites/tests/SubsiteTest.yml',
'subsites/tests/SubsitesVirtualPageTest.yml', 'subsites/tests/SubsitesVirtualPageTest.yml',
); ];
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
// Set backend root to /DataDifferencerTest // Set backend root to /DataDifferencerTest
@ -31,17 +32,19 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
copy($fromPath, $destPath); copy($fromPath, $destPath);
// Hack in site link tracking after the fact // Hack in site link tracking after the fact
$page->Content = '<p><img src="'. $file->getURL(). '" data-fileid="' . $file->ID . '" /></p>'; $page->Content = '<p><img src="' . $file->getURL() . '" data-fileid="' . $file->ID . '" /></p>';
$page->write(); $page->write();
} }
public function tearDown() { public function tearDown()
{
TestAssetStore::reset(); TestAssetStore::reset();
parent::tearDown(); parent::tearDown();
} }
// Attempt to bring main:linky to subsite2:linky // Attempt to bring main:linky to subsite2:linky
function testVirtualPageFromAnotherSubsite() { function testVirtualPageFromAnotherSubsite()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite = $this->objFromFixture(Subsite::class, 'subsite2'); $subsite = $this->objFromFixture(Subsite::class, 'subsite2');
@ -62,7 +65,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
$this->assertEquals($svp->Title, $linky->Title); $this->assertEquals($svp->Title, $linky->Title);
} }
function testFileLinkRewritingOnVirtualPages() { function testFileLinkRewritingOnVirtualPages()
{
// File setup // File setup
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
@ -88,7 +92,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
DB::query("SELECT \"Content\" FROM \"SiteTree_Live\" WHERE \"ID\" = $svp->ID")->value()); DB::query("SELECT \"Content\" FROM \"SiteTree_Live\" WHERE \"ID\" = $svp->ID")->value());
} }
function testSubsiteVirtualPagesArentInappropriatelyPublished() { function testSubsiteVirtualPagesArentInappropriatelyPublished()
{
// Fixture // Fixture
$p = new Page(); $p = new Page();
$p->Content = "test content"; $p->Content = "test content";
@ -188,7 +193,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
$this->assertEquals($svpdb->Title, $p->Title); $this->assertEquals($svpdb->Title, $p->Title);
} }
function testUnpublishingParentPageUnpublishesSubsiteVirtualPages() { function testUnpublishingParentPageUnpublishesSubsiteVirtualPages()
{
Config::modify()->set('StaticPublisher', 'disable_realtime', true); Config::modify()->set('StaticPublisher', 'disable_realtime', true);
// Go to main site, get parent page // Go to main site, get parent page
@ -218,12 +224,14 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
$page->doUnpublish(); $page->doUnpublish();
Subsite::changeSubsite($vp1->SubsiteID); Subsite::changeSubsite($vp1->SubsiteID);
$onLive = Versioned::get_one_by_stage(SubsitesVirtualPage::class, 'Live', "\"SiteTree_Live\".\"ID\" = ".$vp1->ID); $onLive = Versioned::get_one_by_stage(SubsitesVirtualPage::class, 'Live',
"\"SiteTree_Live\".\"ID\" = " . $vp1->ID);
$this->assertNull($onLive, 'SVP has been removed from live'); $this->assertNull($onLive, 'SVP has been removed from live');
$subsite = $this->objFromFixture(Subsite::class, 'subsite2'); $subsite = $this->objFromFixture(Subsite::class, 'subsite2');
Subsite::changeSubsite($vp2->SubsiteID); Subsite::changeSubsite($vp2->SubsiteID);
$onLive = Versioned::get_one_by_stage(SubsitesVirtualPage::class, 'Live', "\"SiteTree_Live\".\"ID\" = ".$vp2->ID); $onLive = Versioned::get_one_by_stage(SubsitesVirtualPage::class, 'Live',
"\"SiteTree_Live\".\"ID\" = " . $vp2->ID);
$this->assertNull($onLive, 'SVP has been removed from live'); $this->assertNull($onLive, 'SVP has been removed from live');
} }
@ -231,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() { function testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()
{
Subsite::$write_hostmap = false; Subsite::$write_hostmap = false;
$subsite1 = $this->objFromFixture(Subsite::class, 'subsite1'); $subsite1 = $this->objFromFixture(Subsite::class, 'subsite1');
$subsite2 = $this->objFromFixture(Subsite::class, 'subsite2'); $subsite2 = $this->objFromFixture(Subsite::class, 'subsite2');
@ -268,11 +277,12 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest {
); );
} }
function fixVersionNumberCache($page) { function fixVersionNumberCache($page)
{
$pages = func_get_args(); $pages = func_get_args();
foreach($pages as $p) { foreach ($pages as $p) {
Versioned::prepopulate_versionnumber_cache('SilverStripe\\CMS\\Model\\SiteTree', 'Stage', array($p->ID)); Versioned::prepopulate_versionnumber_cache('SilverStripe\\CMS\\Model\\SiteTree', 'Stage', [$p->ID]);
Versioned::prepopulate_versionnumber_cache('SilverStripe\\CMS\\Model\\SiteTree', 'Live', array($p->ID)); Versioned::prepopulate_versionnumber_cache('SilverStripe\\CMS\\Model\\SiteTree', 'Live', [$p->ID]);
} }
} }

View File

@ -2,17 +2,18 @@
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\BasicContext;
SilverStripe\BehatExtension\Context\BasicContext, use SilverStripe\BehatExtension\Context\FixtureContext;
SilverStripe\BehatExtension\Context\LoginContext, use SilverStripe\BehatExtension\Context\LoginContext;
SilverStripe\BehatExtension\Context\FixtureContext, use SilverStripe\BehatExtension\Context\SilverStripeContext;
SilverStripe\Framework\Test\Behaviour\CmsFormsContext,
SilverStripe\Framework\Test\Behaviour\CmsUiContext,
SilverStripe\Cms\Test\Behaviour;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\ClassInfo; use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Framework\Test\Behaviour\CmsFormsContext;
use SilverStripe\Framework\Test\Behaviour\CmsUiContext;
// PHPUnit // PHPUnit
@ -25,7 +26,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
@ -38,7 +40,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));
@ -53,25 +56,28 @@ class FeatureContext extends SilverStripeContext {
// Use blueprints to set user name from identifier // Use blueprints to set user name from identifier
$factory = $fixtureContext->getFixtureFactory(); $factory = $fixtureContext->getFixtureFactory();
$blueprint = Injector::inst()->create('SilverStripe\\Dev\\FixtureBlueprint', 'SilverStripe\\Security\\Member'); $blueprint = Injector::inst()->create('SilverStripe\\Dev\\FixtureBlueprint', 'SilverStripe\\Security\\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('SilverStripe\\Security\\Member', $blueprint); $factory->define('SilverStripe\\Security\\Member', $blueprint);
// Auto-publish pages // Auto-publish pages
foreach(ClassInfo::subclassesFor('SilverStripe\\CMS\\Model\\SiteTree') as $id => $class) { foreach (ClassInfo::subclassesFor('SilverStripe\\CMS\\Model\\SiteTree') as $id => $class) {
$blueprint = Injector::inst()->create('SilverStripe\\Dev\\FixtureBlueprint', $class); $blueprint = Injector::inst()->create('SilverStripe\\Dev\\FixtureBlueprint', $class);
$blueprint->addCallback('afterCreate', function($obj, $identifier, &$data, &$fixtures) { $blueprint->addCallback('afterCreate', function ($obj, $identifier, &$data, &$fixtures) {
$obj->publish('Stage', 'Live'); $obj->publish('Stage', 'Live');
}); });
$factory->define($class, $blueprint); $factory->define($class, $blueprint);
} }
} }
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'])) {
$this->getSubcontext('FixtureContext')->setFilesPath($parameters['files_path']); $this->getSubcontext('FixtureContext')->setFilesPath($parameters['files_path']);
} }
} }
@ -79,15 +85,17 @@ 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('SilverStripe\\Dev\\BehatFixtureFactory'); $this->fixtureFactory = Injector::inst()->create('SilverStripe\\Dev\\BehatFixtureFactory');
} }
return $this->fixtureFactory; return $this->fixtureFactory;
} }
public function setFixtureFactory(FixtureFactory $factory) { public function setFixtureFactory(FixtureFactory $factory)
{
$this->fixtureFactory = $factory; $this->fixtureFactory = $factory;
} }