public function onAfterWrite() { parent::onAfterWrite(); if ($this()->hasExtension(HasBlocks::class_name())) { /** @var \ManyManyList $existing */ $existing = $this()->{HasBlocks::relationship_name()}(); if ($this()->{self::SingleFieldName} || $this()->WasNew) { if ($defaultBlockClasses = $this->getDefaultBlockClasses()) { // get class names along with count of each expected $expected = array_count_values($defaultBlockClasses); $sort = $existing->count() + 1; foreach ($expected as $blockClass => $expectedCount) { if (!\ClassInfo::exists($blockClass)) { continue; } $existingCount = $existing->filter('ClassName', $blockClass)->count(); if ($existingCount < $expectedCount) { for ($i = $existingCount; $i < $expectedCount; $i++) { // generate a default title for the block from lang // e.g. ContentBlock.DefaultTitle $templateVars = ['pagetitle' => $this()->{Title::SingleFieldName}, 'singular' => singleton($blockClass)->i18n_singular_name(), 'index' => $i + 1]; // try the block class.DefaultTitle and then Block.DefaultTitle $title = _t("{$blockClass}.DefaultTitle", _t('Block.DefaultTitle', '{pagetitle} {singular} - {index}', $templateVars), $templateVars); /** @var Block $block */ $block = new $blockClass(); $block->update(['Title' => $title]); $block->write(); $existing->add($block, ['Sort' => $sort++]); } } } } } } }
/** * Mostly rewritten from parent, but allows circular dependencies - goes through the relation loop only after * the dictionary is fully populated. */ public function saveIntoDatabase(DataModel $model) { // Custom plumbing: this has to be executed only once per fixture. $testDataTag = basename($this->fixtureFile); $this->latestVersion = DB::query("SELECT MAX(\"Version\") FROM \"TestDataTag\" WHERE \"FixtureFile\"='{$testDataTag}'")->value(); // We have to disable validation while we import the fixtures, as the order in // which they are imported doesnt guarantee valid relations until after the // import is complete. $validationenabled = DataObject::get_validation_enabled(); DataObject::set_validation_enabled(false); $parser = new Spyc(); $fixtureContent = $parser->loadFile($this->fixtureFile); $this->fixtureDictionary = array(); foreach ($fixtureContent as $dataClass => $items) { if (ClassInfo::exists($dataClass)) { $this->writeDataObject($model, $dataClass, $items); } else { $this->writeSQL($dataClass, $items); } } // Dictionary is now fully built, inject the relations. foreach ($fixtureContent as $dataClass => $items) { if (ClassInfo::exists($dataClass)) { $this->writeRelations($dataClass, $items); } } DataObject::set_validation_enabled($validationenabled); }
public function getNestedController() { if ($this->urlParams['URLSegment']) { $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']); if (Translatable::is_enabled()) { $child = Translatable::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'"); } else { $child = DataObject::get_one("SiteTree", "URLSegment = '{$SQL_URLSegment}'"); } if (!$child) { $child = $this->get404Page(); } if ($child) { if (isset($_REQUEST['debug'])) { Debug::message("Using record #{$child->ID} of type {$child->class} with URL {$this->urlParams['URLSegment']}"); } $controllerClass = "{$child->class}_Controller"; if ($this->urlParams['Action'] && ClassInfo::exists($controllerClass . '_' . $this->urlParams['Action'])) { $controllerClass = $controllerClass . '_' . $this->urlParams['Action']; } if (ClassInfo::exists($controllerClass)) { $controller = new $controllerClass($child); } else { $controller = $child; } $controller->setURLParams($this->urlParams); return $controller; } else { die("The requested page couldn't be found."); } } else { user_error("ModelAsController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR); } }
/** * @param callable $callback * @param string $expectedException * @param null $expectedCode * @param null $expectedMessage * @author VladaHejda */ public static function assertException(callable $callback, $expectedException = 'Exception', $expectedCode = null, $expectedMessage = null) { $self = new SapphireTest(); if (!ClassInfo::exists($expectedException)) { $self->fail(sprintf('An exception of type "%s" does not exist.', $expectedException)); } try { $callback(); } catch (\Exception $e) { $class = ClassInfo::class_name($e); $message = $e->getMessage(); $code = $e->getCode(); $errorMessage = 'Failed asserting the class of exception'; if ($message && $code) { $errorMessage .= sprintf(' (message was %s, code was %d)', $message, $code); } elseif ($code) { $errorMessage .= sprintf(' (code was %d)', $code); } $errorMessage .= '.'; $self->assertInstanceOf($expectedException, $e, $errorMessage); if ($expectedCode !== null) { $self->assertEquals($expectedCode, $code, sprintf('Failed asserting code of thrown %s.', $class)); } if ($expectedMessage !== null) { $self->assertContains($expectedMessage, $message, sprintf('Failed asserting the message of thrown %s.', $class)); } return; } $errorMessage = 'Failed asserting that exception'; if (strtolower($expectedException) !== 'exception') { $errorMessage .= sprintf(' of type %s', $expectedException); } $errorMessage .= ' was thrown.'; $self->fail($errorMessage); }
/** * A simple Gridfield factory * @param string $model * @param string $relationname * @param DataObject $reference * @return GridField */ public static function create_gridfield_for($model, $relationname, $reference) { if ($relationname != null && ClassInfo::exists($model)) { $config = GridFieldConfig_RelationEditor::create(); $config->addComponent($gridFieldForm = new GridFieldDetailForm()); if ($items = $reference->{$relationname}()) { if (is_a($items, 'ManyManyList') && ClassInfo::exists('GridFieldManyRelationHandler')) { $config->addComponent(new GridFieldManyRelationHandler(), 'GridFieldPaginator'); } else { $sortable = singleton($model)->hasExtension('SortableDataExtension'); if ($sortable) { $config->addComponent(new GridFieldSortableRows('SortOrder')); } } $gridfield = GridField::create($relationname, $model, $items, $config); $datacolumns = $gridfield->getConfig()->getComponentByType('GridFieldDataColumns'); $cfields = singleton($model)->summaryFields(); if (singleton($model)->hasExtension('CMSPublishableDataExtension') && !isset($cfields['PublishStatus'])) { $cfields = array('PublishStatus' => 'PublishStatus') + $cfields; } $datacolumns->setDisplayFields($cfields); return $gridfield; } else { throw new InvalidArgumentException("Couldn't find relation."); } } else { throw new InvalidArgumentException("Couldn't create GridField because wrong parameters passed to the factory."); } }
/** * Retrieve the existing searchable fields, appending our custom search index to enable it. * @return array */ public function updateSolrSearchableFields(&$fields) { // Make sure the extension requirements have been met before enabling the custom search index. if (ClassInfo::exists('QueuedJob')) { $fields[$this->index] = true; } }
/** * Retrieve a modifier of a given class for the order. * Modifier will be retrieved from database if it already exists, * or created if it is always required. * * @param string $className * @param boolean $forcecreate - force the modifier to be created. */ public function getModifier($className, $forcecreate = false) { if (!ClassInfo::exists($className)) { user_error("Modifier class \"{$className}\" does not exist."); } //search for existing $modifier = $className::get()->filter("OrderID", $this->order->ID)->first(); if ($modifier) { //remove if no longer valid if (!$modifier->valid()) { //TODO: need to provide feedback message - why modifier was removed $modifier->delete(); $modifier->destroy(); return null; } return $modifier; } $modifier = new $className(); if ($modifier->required() || $forcecreate) { //create any modifiers that are required for every order $modifier->OrderID = $this->order->ID; $modifier->write(); $this->order->Modifiers()->add($modifier); return $modifier; } return null; }
public function getEditForm($id = null, $fields = null) { $form = parent::getEditForm($id, $fields); $field = $form->Fields()->dataFieldByName($this->modelClass); if ($field) { $config = $field->getConfig(); if (!ClassInfo::exists('GridFieldBetterButtonsItemRequest') && $this->IsEditingNews()) { $config->getComponentByType('GridFieldDetailForm')->setItemRequestClass('NewsGridFieldDetailForm_ItemRequest'); } $singleton = singleton($this->modelClass); if (is_a($singleton, 'NewsPost') && ClassInfo::exists('GridFieldOrderableRows')) { $config->addComponent(new GridFieldOrderableRows('Sort')); $exportButton = $config->getComponentByType('GridFieldExportButton'); if ($exportButton) { $export = array('Title' => 'Title', 'DateTime' => 'DateTime', 'Author' => 'Author', 'ExportContent' => 'Content'); $this->extend('updateExportColumn', $export); $exportButton->setExportColumns($export); } } $config->removeComponentsByType('GridFieldDeleteAction'); $config->removeComponentsByType('GridFieldPaginator'); $config->addComponent($pagination = new GridFieldPaginator(100)); } return $form; }
public function updateCMSFields(FieldList $fields) { $sortable = singleton('CleanTeaser')->hasExtension('SortableDataExtension'); $config = GridFieldConfig_RelationEditor::create(); $config->addComponent($gridFieldForm = new GridFieldDetailForm()); $dataFields = array(); if (singleton('CleanTeaser')->hasExtension('CMSPublishableDataExtension')) { $dataFields['PublishIndicator'] = 'Published'; } $dataFields = array_merge($dataFields, array('Thumbnail' => 'Thumbnail', 'Title' => 'Title', 'CleanDescription' => 'Description')); $config->getComponentByType('GridFieldDataColumns')->setDisplayFields($dataFields); $gridFieldForm->setTemplate('CMSGridFieldPopupForms'); if ($sortable) { $config->addComponent(new GridFieldSortableRows('SortOrder')); } if (ClassInfo::exists('GridFieldBulkUpload')) { $iu = new GridFieldBulkUpload('ImageID'); if (singleton('CleanTeaser')->hasExtension('ControlledFolderDataExtension')) { $iu->setUfConfig('folderName', singleton('CleanTeaser')->getUploadFolder()); } else { $iu->setUfConfig('folderName', CleanTeaser::$upload_folder); } $config->addComponent($iu); } if ($sortable) { $data = $this->owner->CleanTeasers("ClassName = 'CleanTeaser'")->sort('SortOrder'); } else { $data = $this->owner->CleanTeasers("ClassName = 'CleanTeaser'"); } // $config->removeComponentsByType('GridFieldAddNewButton'); // if (ClassInfo::exists('GridFieldBulkUpload')) { // $config->addComponent(new GridFieldAddNewMultiClass()); // } $fields->addFieldToTab("Root.Teasers", GridField::create('CleanTeasers', 'CleanTeaser', $data, $config)); }
protected function getRemoteObject($node) { $clazz = $node->nodeName; $object = null; // do we have this data object type? if (ClassInfo::exists($clazz)) { // we'll create one $object = new $clazz(); } else { $object = new Page(); } // track the name property and set it LAST again to handle special cases like file // that overwrite other properties when $name is set $name = null; foreach ($node->childNodes as $property) { if ($property instanceof DOMText) { continue; } $pname = $property->nodeName; if (isset($this->remap[$pname])) { $pname = $this->remap[$pname]; } if ($pname == 'Filename') { $name = $property->nodeValue; } $object->{$pname} = $property->nodeValue; } $object->SourceClassName = $clazz; if (!is_null($name)) { $object->Filename = $name; } return $object; }
/** * To process this job, we need to get the next page whose ID is the next greater than the last * processed. This way we don't need to remember a bunch of data about what we've processed */ public function process() { if (ClassInfo::exists('Subsite')) { Subsite::disable_subsite_filter(); } $class = $this->reindexType; $pages = $class::get(); $pages = $pages->filter(array('ID:GreaterThan' => $this->lastIndexedID)); $pages = $pages->limit(Config::inst()->get(__CLASS__, 'at_a_time')); $pages = $pages->sort('ID ASC'); if (ClassInfo::exists('Subsite')) { Subsite::$disable_subsite_filter = false; } if (!$pages || !$pages->count()) { $this->isComplete = true; return; } $mode = Versioned::get_reading_mode(); Versioned::reading_stage('Stage'); // index away $service = singleton('SolrSearchService'); $live = array(); $stage = array(); $all = array(); foreach ($pages as $page) { // Make sure the current page is not orphaned. if ($page->ParentID > 0) { $parent = $page->getParent(); if (is_null($parent) || $parent === false) { continue; } } // Appropriately index the current page, taking versioning into account. if ($page->hasExtension('Versioned')) { $stage[] = $page; $base = $page->baseTable(); $idField = '"' . $base . '_Live"."ID"'; $livePage = Versioned::get_one_by_stage($page->ClassName, 'Live', $idField . ' = ' . $page->ID); if ($livePage) { $live[] = $livePage; } } else { $all[] = $page; } $this->lastIndexedID = $page->ID; } if (count($all)) { $service->indexMultiple($all); } if (count($stage)) { $service->indexMultiple($stage, 'Stage'); } if (count($live)) { $service->indexMultiple($live, 'Live'); } Versioned::set_reading_mode($mode); $this->lastIndexedID = $page->ID; $this->currentStep += $pages->count(); }
public function getCMSFields() { $fields = parent::getCMSFields(); if (ClassInfo::exists('GridFieldOrderableRows')) { $fields->dataFieldByName('Tasks')->getConfig()->addComponent(new GridFieldOrderableRows('Sort')); } return $fields; }
public static function remove_weight($weight) { self::$weights = array_diff(self::$weights, array($weight)); $class = "NewsWeight{$weight}"; if (ClassInfo::exists($class)) { Object::remove_extension('NewsHolder', $class); } }
/** * The test to ensure the regular expression replacement is correct. */ public function testRegularExpressionReplacement() { // Instantiate a link mapping to use. $mapping = LinkMapping::create(array('LinkType' => 'Regular Expression', 'MappedLink' => '^www\\.wrong\\.com(/page)?/(index){1}\\.php$', 'RedirectLink' => 'https://www.correct.com$1')); $mapping->setMatchedURL('www.wrong.com/page/index.php'); // Determine whether the regular expression replacement is correct. $this->assertEquals($mapping->getLink(), ClassInfo::exists('Multisites') ? 'https://www.correct.com/page?misdirected=1' : 'https://www.correct.com/page'); }
function setValue($value, $record = null) { $parts = explode(":", $value); if (!is_array($parts) || count($parts) != 2 || !ClassInfo::exists($parts[0]) || !is_numeric($parts[1])) { return; } $this->value = DataObject::get_by_id($parts[0], $parts[1]); }
public function __construct() { if (!ClassInfo::exists('QueuedJobService')) { $this->config()->use_queues = false; } $this->setSenders($this->config()->get('default_senders')); $this->setChannels($this->config()->get('default_channels')); }
protected function importDataObject($item, $parentObject, $duplicateStrategy) { Versioned::reading_stage('Stage'); $ignore = array('ClassName' => true, 'Status' => true, 'ID' => true); $cls = 'Page'; if (strlen($item->ClassName) && ClassInfo::exists($item->ClassName)) { $cls = $item->ClassName; } if ($cls == 'SiteTree') { $cls = 'Page'; } $obj = new $cls(); $obj->Version = 1; if ($parentObject && $parentObject->hasExtension('Hierarchy') && $obj->hasExtension('Hierarchy')) { if ($cls == "SilverStripeContentItem" && $item->Title == "Files") { $fakeId = '0-File'; $fakeFiles = new SilverStripeContentItem($item->source, $fakeId); $fakeFiles->Title = 'Files'; $fakeFiles->ID = $item->ID . ExternalContent::ID_SEPARATOR . $fakeId; return $fakeFiles; } $filter = '"Title" = \'' . Convert::raw2sql($item->Title) . '\' AND "ParentID" = ' . (int) $parentObject->ID; $existing = DataObject::get_one($cls, $filter); if ($existing && $existing->exists()) { if ($duplicateStrategy == ExternalContentTransformer::DS_OVERWRITE) { $obj = $existing; $obj->ClassName = $cls; } else { if ($duplicateStrategy == ExternalContentTransformer::DS_SKIP) { return $existing; } } } } foreach ($item->getRemoteProperties() as $field => $value) { if (!isset($ignore[$field]) && $obj->hasField($field)) { $obj->{$field} = $value; } } $obj->RemoteNodeId = $item->getSS_ID(); $obj->RemoteSystemId = $item->getSource()->ID; $obj->ParentID = $parentObject->ID; if ($parentObject->SubsiteID) { $obj->SubsiteID = $parentObject->SubsiteID; } $obj->write(); // Adds proper support for 2.4 so everything doesn't get published since // the built in API will show unpublished pages. 3.x doesn't have this issue $itemPublished = false; if (isset($item->Status) && $item->Status == "Published") { $itemPublished = true; } // Changed here for $itemPublished OR $parentObject->isPublished to account for the 2.4 issue if ($parentObject->ClassName != "Folder" && $obj->hasExtension('Versioned') && ($itemPublished || $parentObject->isPublished())) { $obj->publish('Stage', 'Live'); } return $obj; }
/** * Retrieve the search page. * * @return extensible search page */ public function getSearchPage() { $pages = ExtensibleSearchPage::get(); // This is required to support multiple sites. if (ClassInfo::exists('Multisites')) { $pages = $pages->filter('SiteID', $this->owner->SiteID); } return $pages->first(); }
/** * Format a ClassName or Field name sent by client API * to be used by SilverStripe * * @param string $name ClassName of Field name * @return string Formatted name */ public function unformatName($name) { $class = ucfirst($name); if (ClassInfo::exists($class)) { return $class; } else { return $name; } }
public function testExists() { $this->assertTrue(ClassInfo::exists('Object')); $this->assertTrue(ClassInfo::exists('object')); $this->assertTrue(ClassInfo::exists('ClassInfoTest')); $this->assertTrue(ClassInfo::exists('CLASSINFOTEST')); $this->assertTrue(ClassInfo::exists('stdClass')); $this->assertTrue(ClassInfo::exists('stdCLASS')); }
public function run($request) { if (isset($request['name']) && ClassInfo::exists($request['name'])) { $clz = $request['name']; $job = new $clz(); } else { $job = new DummyQueuedJob(mt_rand(10, 100)); } singleton('QueuedJobService')->queueJob($job); }
/** * Creates a report template instance if one does not exist. */ protected function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->ReportTemplateID && $this->ReportType && ClassInfo::exists($this->ReportType)) { $template = Object::create($this->ReportType); $template->Title = $this->Title; $template->write(); $this->ReportTemplateID = $template->ID; } }
public function SiteConfig() { if (ClassInfo::exists("SiteConfig")) { if (method_exists($this->owner->dataRecord, 'getSiteConfig')) { return $this->owner->dataRecord->getSiteConfig(); } else { return SiteConfig::current_site_config(); } } }
public function __construct($filterField = 'Created', $fragment = 'header', $label = '', $navigationLabel = '') { if (!\ClassInfo::exists('RangeSliderField')) { throw new \LogicException('Please install the milkyway-multimedia/ss-mwm-formfields module to use this feature'); } $this->filterField = $filterField; $this->fragment = $fragment; $this->label = $label; $this->navigationLabel = $navigationLabel ?: _t('GridFieldUtils.SHOW', 'Show'); }
protected function getItem() { if (ClassInfo::exists('Subsite')) { Subsite::disable_subsite_filter(true); } $item = DataObject::get_by_id($this->itemType, $this->itemID); if (ClassInfo::exists('Subsite')) { Subsite::disable_subsite_filter(false); } return $item; }
/** * Format a ClassName or Field name sent by client API * to be used by SilverStripe * * @param string $name ClassName of Field name * @return string Formatted name */ public function unformatName($name) { $class = Inflector::singularize($name); $class = ucfirst($class); if (ClassInfo::exists($class)) { return $class; } else { $name = $this->deserializeColumnName($name); } return $name; }
function getHandler($noun) { $ancestry = array_reverse(ClassInfo::ancestry($noun->class)); foreach ($ancestry as $class) { $class = $class . '_Handler'; if (ClassInfo::exists($class)) { return new $class($noun); } } user_error("Couldn't find a handler for REST Noun " . $noun, E_USER_ERROR); }
/** * The test to ensure the request filter is functioning correctly. */ public function testRequestFilter() { // Instantiate link mappings to use. $mapping = LinkMapping::create(array('LinkType' => 'Simple', 'MappedLink' => 'wrong/page', 'RedirectLink' => 'pending')); $mapping->write(); LinkMapping::create(array('LinkType' => 'Simple', 'MappedLink' => 'pending', 'RedirectLink' => 'correct/page'))->write(); // The CMS module needs to be present to test page behaviour. if (ClassInfo::exists('SiteTree')) { // This is required to support multiple sites. $this->logInAs(Member::default_admin()); $parentID = ClassInfo::exists('Multisites') ? Multisites::inst()->getCurrentSiteId() : 0; // Instantiate pages to use. $first = SiteTree::create(array('URLSegment' => 'wrong', 'ParentID' => $parentID)); $first->writeToStage('Stage'); $first->writeToStage('Live'); $second = SiteTree::create(array('URLSegment' => 'page', 'ParentID' => $first->ID)); $second->writeToStage('Stage'); $second->writeToStage('Live'); } // Determine whether the enforce misdirection is functioning correctly. $response = $this->get('wrong/page'); $this->assertEquals($response->getStatusCode(), 303); $this->assertEquals($response->getHeader('Location'), '/correct/page'); // The CMS module needs to be present to test page behaviour. if (ClassInfo::exists('SiteTree')) { // Update the default enforce misdirection. Config::inst()->update('MisdirectionRequestFilter', 'enforce_misdirection', false); // Determine whether the page is now matched. $response = $this->get('wrong/page'); $this->assertEquals($response->getStatusCode(), 200); $this->assertEquals($response->getHeader('Location'), null); // Instantiate a fallback to use. $first->Fallback = 'Nearest'; $first->writeToStage('Stage'); $first->writeToStage('Live'); // The database needs to be cleaned up to prevent further testing conflict. $second->deleteFromStage('Live'); $second->deleteFromStage('Stage'); $mapping->delete(); // Determine whether the fallback is matched. $response = $this->get('wrong/page'); $this->assertEquals($response->getStatusCode(), 303); $this->assertEquals($response->getHeader('Location'), '/wrong/?misdirected=1'); } // Instantiate a director rule to use. Config::inst()->update('Director', 'rules', array('wrong/page' => 'Controller')); // Determine whether the director rule is matched. $response = $this->get('wrong/page'); $this->assertEquals($response->getStatusCode(), 200); $this->assertEquals($response->getHeader('Location'), null); // The database needs to be emptied to prevent further testing conflict. self::empty_temp_db(); }
function extractStates(&$table, &$ids, &$fields) { $class = $table; $suffix = null; if (ClassInfo::exists($class) && $this->appliesTo($class, false)) { $table = $class; $self = get_class($this); foreach ($ids as $i => $statefulid) { $ids[$i]['state'][$self] = $suffix ? $suffix : 'Stage'; } } }
/** * The "default" structure used for this report when auto generating etc */ public function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->ReportTemplateID && $this->ReportType && ClassInfo::exists($this->ReportType)) { $template = Object::create($this->ReportType); // create the template first. This is what all actual reports are based on when they're generated, either // automatically or by the 'generate' button $template->Title = $this->Title . ' Preview'; $template->write(); $this->ReportTemplateID = $template->ID; } }