public function doAllChildrenIncludingDeleted($context = null)
 {
     if (!$this->owner) {
         user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
     }
     $baseClass = ClassInfo::baseDataClass($this->owner->class);
     if ($baseClass) {
         $stageChildren = $this->owner->stageChildren(true);
         $stageChildren = $this->RemoveNewsPostsFromSiteTree($stageChildren);
         // Add live site content that doesn't exist on the stage site, if required.
         if ($this->owner->hasExtension('Versioned')) {
             // Next, go through the live children.  Only some of these will be listed
             $liveChildren = $this->owner->liveChildren(true, true);
             if ($liveChildren) {
                 $liveChildren = $this->RemoveNewsPostsFromSiteTree($liveChildren);
                 $merged = new ArrayList();
                 $merged->merge($stageChildren);
                 $merged->merge($liveChildren);
                 $stageChildren = $merged;
             }
         }
         $this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
     } else {
         user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'", E_USER_ERROR);
     }
     return $stageChildren;
 }
 public function getAllBlocks()
 {
     $blocks = new ArrayList();
     $blocks->merge($this->getMyBlocks());
     $blocks->merge($this->getDockedBlocks());
     return $blocks;
 }
 /**
  * Returns all the {@link InlineHelpTopic}s attached to this page.
  *
  * @return InlineHelpTopic[]
  */
 public function getHelpItems()
 {
     $items = new ArrayList();
     $items->merge(InlineHelpTopic::get()->where('"AttachType" = \'All\''));
     $items->merge(InlineHelpTopic::get()->where(sprintf('"AttachType" = \'Type\' AND "AttachPageType" = \'%s\'', $this->owner->class)));
     $items->merge($this->owner->HelpTopics());
     $stack = $this->owner->parentStack();
     array_shift($stack);
     if ($stack) {
         $items->merge(InlineHelpTopic::get()->where(sprintf('"AttachType" = \'Children\' AND "ParentFilterID" IN(%s)', implode(', ', array_map(create_function('$self', 'return $self->ID;'), $stack)))));
     }
     $items->removeDuplicates();
     return $items;
 }
Пример #4
0
 function TalksByMemberID($memberID)
 {
     $SpeakerList = new ArrayList();
     // Pull any talks that belong to this Summit and are owned by member
     $talksMemberOwns = $this->Talks("`OwnerID` = " . $memberID . " AND `SummitID` = " . $this->ID);
     $SpeakerList->merge($talksMemberOwns);
     // Now pull any talks that belong to this Summit and the member is listed as a speaker
     $speaker = Speaker::get()->filter('memberID', $memberID)->first();
     if ($speaker) {
         $talksMemberIsASpeaker = $speaker->TalksBySummitID($this->ID);
         // Now merge and de-dupe the lists
         $SpeakerList->merge($talksMemberIsASpeaker);
         $SpeakerList->removeDuplicates('ID');
     }
     return $SpeakerList;
 }
 /**
  * If this is attached to an object with the hierarchy extension, it returns
  * a set of a schema objects attached to any ancestors (which should be
  * present on this object).
  *
  * @return ArrayList
  */
 public function getInheritedSchemas()
 {
     $result = new ArrayList();
     if (!$this->owner->hasExtension('Hierarchy')) {
         return new ArrayList();
     }
     $ids = array();
     $parents = $this->owner->getAncestors();
     foreach ($parents as $parent) {
         $ids[] = $parent->ID;
     }
     if (count($ids)) {
         $filter = sprintf('"MetadataSchema"."ID" = "MetadataSchemaLink"."SchemaID"' . ' AND "MetadataSchemaLink"."ParentClass" = \'%s\'' . ' AND "MetadataSchemaLink"."ParentID" IN (%s)', ClassInfo::baseDataClass($this->owner->class), implode(', ', $ids));
         $result = MetadataSchema::get()->innerJoin('MetadataSchemaLink', $filter);
         if ($result) {
             $result = new ArrayList($result->toArray());
         } else {
             $result = new ArrayList();
         }
     }
     if ($this->owner instanceof SiteTree) {
         // Check SiteConfig too
         $config = SiteConfig::current_site_config();
         if ($config->hasExtension('MetadataExtension')) {
             $schemas = $config->getAttachedSchemas();
             if ($schemas && $schemas->count()) {
                 $result->merge($schemas);
             }
         }
     }
     return $result;
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->getSearchFields($className);
         // build the filter
         $filter = array();
         // Use parametrized query if SilverStripe >= 3.2
         if (SHOP_SEARCH_IS_SS32) {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = array("MATCH ({$indexFields}) AGAINST (?)" => $keywords);
             }
             $list = $list->whereAny($filter);
         } else {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = sprintf("MATCH ({$indexFields}) AGAINST ('%s')", Convert::raw2sql($keywords));
             }
             // join all the filters with an "OR" statement
             $list = $list->where(implode(' OR ', $filter));
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->scaffoldSearchFields($className);
         // convert that list into something we can pass to Datalist::filter
         $keywordFilter = array();
         if (!empty($keywords)) {
             foreach ($keywordFields as $searchField) {
                 $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:PartialMatch";
                 $keywordFilter[$name] = $keywords;
             }
         }
         if (count($keywordFilter) > 0) {
             $list = $list->filterAny($keywordFilter);
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 /**
  * This may need to be optimised. We'll just have to see how it performs.
  *
  * @param SS_HTTPRequest $req
  * @return array
  */
 public function downloads(SS_HTTPRequest $req)
 {
     $downloads = new ArrayList();
     $member = Member::currentUser();
     if (!$member || !$member->exists()) {
         $this->httpError(401);
     }
     // create a dropdown for sorting
     $sortOptions = Config::inst()->get('DownloadableAccountPageController', 'sort_options');
     if ($sortOptions) {
         $sort = $req->requestVar('sort');
         if (empty($sort)) {
             reset($sortOptions);
             $sort = key($sortOptions);
         }
         $sortControl = new DropdownField('download-sort', 'Sort By:', $sortOptions, $sort);
     } else {
         $sort = 'PurchaseDate';
         $sortControl = '';
     }
     // create a list of downloads
     $orders = $member->getPastOrders();
     if (!empty($orders)) {
         foreach ($orders as $order) {
             if ($order->DownloadsAvailable()) {
                 $downloads->merge($order->getDownloads());
             }
         }
     }
     Requirements::javascript(SHOP_DOWNLOADABLE_FOLDER . '/javascript/AccountPage_downloads.js');
     return array('Title' => 'Digital Purchases', 'Content' => '', 'SortControl' => $sortControl, 'HasDownloads' => $downloads->count() > 0, 'Downloads' => $downloads->sort($sort));
 }
Пример #9
0
 public function testMerge()
 {
     $list = new ArrayList(array(array('Num' => 1), array('Num' => 2)));
     $list->merge(array(array('Num' => 3), array('Num' => 4)));
     $this->assertEquals(4, count($list));
     $this->assertEquals($list->toArray(), array(array('Num' => 1), array('Num' => 2), array('Num' => 3), array('Num' => 4)));
 }
 public function provideGridListItems()
 {
     $results = new \ArrayList();
     /** @var Service $service */
     $service = \Injector::inst()->get('SearchService');
     // check something was passed in 'q' parameter up front to skip processing if we can
     if ($service->constraint(Constraints::FullTextVar)) {
         $searchClasses = $this->config()->get('search_classes') ?: [];
         foreach ($searchClasses as $className) {
             $filter = $service->Filters()->filter($className, Constraints::FullTextVar, \Modular\Search\ModelExtension::SearchIndex);
             if ($filter) {
                 $intermediates = \DataObject::get($className)->filter($filter);
                 /** @var ModelExtension|\DataObject $intermediate */
                 foreach ($intermediates as $intermediate) {
                     if ($intermediate->hasMethod('SearchTargets')) {
                         // merge in what the intermediate object thinks are it's actual targets,
                         // e.g. for a ContentBlock this is the Pages which are related to that block
                         $results->merge($intermediate->SearchTargets());
                     } else {
                         // if no search targets nominated then just add the intermediate as it is the target
                         $results->push($intermediate);
                     }
                 }
             }
         }
     }
     return $results;
 }
 /**
  * @return ArrayList
  */
 private static function ExpiredDataObjects()
 {
     $data_objects = new ArrayList();
     foreach (AutoArchivableExtension::getExtendedClasses() as $class_name) {
         $data_objects->merge(DataObject::get($class_name)->filter(array('AutoArchiveOn' => true, 'AutoArchiveDate:LessThanOrEqual' => date('Y-m-d'))));
     }
     return $data_objects;
 }
Пример #12
0
 public function getEventList($start, $end, $filter = null, $limit = null)
 {
     $eventList = new ArrayList();
     foreach ($this->getAllCalendars() as $calendar) {
         if ($events = $calendar->getStandardEvents($start, $end, $filter)) {
             $eventList->merge($events);
         }
     }
     $eventList = $eventList->sort(array("StartDate" => "ASC", "StartTime" => "ASC"));
     $eventList = $eventList->limit($limit);
     return $eventList;
 }
 /**
  * Takes a list of groups and members and return a list of unique member.
  *
  * @param SS_List $groups
  * @param SS_List $members
  *
  * @return ArrayList
  */
 public static function merge_owners(SS_List $groups, SS_List $members)
 {
     $contentReviewOwners = new ArrayList();
     if ($groups->count()) {
         $groupIDs = array();
         foreach ($groups as $group) {
             $familyIDs = $group->collateFamilyIDs();
             if (is_array($familyIDs)) {
                 $groupIDs = array_merge($groupIDs, array_values($familyIDs));
             }
         }
         array_unique($groupIDs);
         if (count($groupIDs)) {
             $groupMembers = DataObject::get("Member")->where("\"Group\".\"ID\" IN (" . implode(",", $groupIDs) . ")")->leftJoin("Group_Members", "\"Member\".\"ID\" = \"Group_Members\".\"MemberID\"")->leftJoin("Group", "\"Group_Members\".\"GroupID\" = \"Group\".\"ID\"");
             $contentReviewOwners->merge($groupMembers);
         }
     }
     $contentReviewOwners->merge($members);
     $contentReviewOwners->removeDuplicates();
     return $contentReviewOwners;
 }
 public function onAfterInit()
 {
     if (!Director::isDev()) {
         // Only on live site
         $errorcode = $this->owner->failover->ErrorCode ? $this->owner->failover->ErrorCode : 404;
         $extract = preg_match('/^([a-z0-9\\.\\_\\-\\/]+)/i', $_SERVER['REQUEST_URI'], $rawString);
         if ($errorcode == 404 && $extract) {
             $uri = preg_replace('/\\.(aspx?|html?|php[34]?)$/i', '', $rawString[0]);
             $parts = preg_split('/\\//', $uri, -1, PREG_SPLIT_NO_EMPTY);
             $page_key = array_pop($parts);
             $sounds_like = soundex($page_key);
             // extend ignored classes with child classes
             $ignoreClassNames = array();
             if ($configClasses = Config::inst()->get('Intelligent404', 'intelligent_404_ignored_classes')) {
                 foreach ($configClasses as $class) {
                     $ignoreClassNames = array_merge($ignoreClassNames, array_values(ClassInfo::subclassesFor($class)));
                 }
             }
             // get all pages
             $SiteTree = SiteTree::get()->exclude('ClassName', $ignoreClassNames);
             // Translatable support
             if (class_exists('Translatable')) {
                 $SiteTree = $SiteTree->filter('Locale', Translatable::get_current_locale());
             }
             // Multisites support
             if (class_exists('Multisites')) {
                 $SiteTree = $SiteTree->filter('SiteID', Multisites::inst()->getCurrentSiteId());
             }
             $ExactMatches = new ArrayList();
             $PossibleMatches = new ArrayList();
             foreach ($SiteTree as $page) {
                 if ($page->URLSegment == $page_key) {
                     $ExactMatches->push($page);
                 } elseif ($sounds_like == soundex($page->URLSegment)) {
                     $PossibleMatches->push($page);
                 }
             }
             $ExactCount = $ExactMatches->Count();
             $PossibleCount = $PossibleMatches->Count();
             $redirectOnSingleMatch = Config::inst()->get('Intelligent404', 'redirect_on_single_match');
             if ($ExactCount == 1 && $redirectOnSingleMatch) {
                 return $this->RedirectToPage($ExactMatches->First()->Link());
             } elseif ($ExactCount == 0 && $PossibleCount == 1 && $redirectOnSingleMatch) {
                 return $this->RedirectToPage($PossibleMatches->First()->Link());
             } elseif ($ExactCount > 1 || $PossibleCount > 1 || !$redirectOnSingleMatch) {
                 $ExactMatches->merge($PossibleMatches);
                 $content = $this->owner->customise(array('Pages' => $ExactMatches))->renderWith(array('Intelligent404Options'));
                 $this->owner->Content .= $content;
             }
         }
     }
 }
 /**
  * Return all the page models related to this tag (there may be multiple Page Classe attached so iterate through them all)
  *
  * @param string|array $matchClassNames and array of classnames, a class name or a pattern as used by fnmatch, eg. '*Page'
  * @return \ArrayList
  */
 public function relatedByClassName($matchClassNames)
 {
     $matchClassNames = is_array($matchClassNames) ? $matchClassNames : [$matchClassNames];
     $pages = new \ArrayList();
     foreach ($this()->config()->get('belongs_many_many') as $relationship => $className) {
         foreach ($matchClassNames as $pattern) {
             if (fnmatch($pattern, $className)) {
                 $pages->merge($this()->{$relationship}());
             }
         }
     }
     return $pages;
 }
 /**
  * @param \DataList|\ArrayList $items
  * @param                      $filters
  * @param array                $parameters
  */
 public function sequenceGridListItems(&$items, $filters, &$parameters = [])
 {
     $limit = isset($parameters['PageLength']) ? $parameters['PageLength'] : null;
     // filter items for each filter to current page length
     if ($limit) {
         $start = GridList::service()->Filters()->start() ?: 0;
         $out = new \ArrayList();
         $currentFilter = GridList::service()->constraint(Constraints::FilterVar);
         if ($currentFilter && $currentFilter != 'all') {
             if ($filter = GridListFilter::get()->filter(['ModelTag' => $currentFilter])->first()) {
                 $out->merge($items->limit($limit, $start));
             }
         } else {
             foreach ($filters as $filter) {
                 $filtered = new \ArrayList();
                 foreach ($items as $item) {
                     if ($item instanceof Block) {
                         // only push blocks first page
                         if ($start == 0) {
                             $filtered->push($item);
                         }
                     } else {
                         if ($currentFilter == 'all') {
                             $filtered->push($item);
                         } else {
                             if ($item->GridListFilters()->find('ID', $filter->ID)) {
                                 $filtered->push($item);
                             }
                         }
                     }
                 }
                 // merge limited filtered items back in
                 $out->merge($filtered->limit($limit, $start));
             }
         }
         $items = $out;
     }
 }
 protected function processAll($filepath, $preview = false)
 {
     $this->extend('updateColumnMap', $this->columnMap);
     // we have to check for the existence of this in case the stockcontrol module hasn't been loaded
     // and the CSV still contains a Stock column
     self::$hasStockImpl = Object::has_extension('Product', 'ProductStockDecorator');
     $results = parent::processAll($filepath, $preview);
     //After results have been processed, publish all created & updated products
     $objects = new ArrayList();
     $objects->merge($results->Created());
     $objects->merge($results->Updated());
     foreach ($objects as $object) {
         if (!$object->ParentID) {
             //set parent page
             if (is_numeric(self::$parentpageid) && DataObject::get_by_id('ProductCategory', self::$parentpageid)) {
                 //cached option
                 $object->ParentID = self::$parentpageid;
             } elseif ($parentpage = DataObject::get_one('ProductCategory', "\"Title\" = 'Products'", '"Created" DESC')) {
                 //page called 'Products'
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } elseif ($parentpage = DataObject::get_one('ProductCategory', "\"ParentID\" = 0", '"Created" DESC')) {
                 //root page
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } elseif ($parentpage = DataObject::get_one('ProductCategory', "", '"Created" DESC')) {
                 //any product page
                 $object->ParentID = self::$parentpageid = $parentpage->ID;
             } else {
                 $object->ParentID = self::$parentpageid = 0;
             }
         }
         $object->extend('updateImport');
         //could be used for setting other attributes, such as stock level
         $object->writeToStage('Stage');
         $object->publish('Stage', 'Live');
     }
     return $results;
 }
 /**
  * Use the 'related' method to return related pages.
  *
  * @return mixed
  */
 public function provideGridListItems()
 {
     if ($this()->{self::SingleFieldName}) {
         if ($page = \Director::get_current_page()) {
             $items = new \ArrayList();
             // iterate through children of 'HasRelatedPages', eg 'BusinessPages', 'DivisionPages' etc
             foreach (HasRelatedPages::implementors() as $className => $title) {
                 if ($page->hasExtension($className)) {
                     // get all the related e.g. country pages to this page via the 'RelatedCountries' back relationship
                     $items->merge($page->{$className::relationship_name()}());
                 }
             }
             return $items;
         }
     }
 }
 public function provideGridListItems()
 {
     $results = new \ArrayList();
     /** @var Service $service */
     $service = \Injector::inst()->get('SearchService');
     if ($tags = array_filter(explode(',', $service->constraint(Constraints::TagsVar)))) {
         $allTags = Tag::get();
         $searchClasses = $this->config()->get('search_classes');
         foreach ($tags as $tag) {
             /** @var ModelTag $tag */
             if ($tag = $allTags->find(ModelTag::field_name(), $tag)) {
                 // merge all related classes that end in 'Page' for this tag
                 $results->merge($tag->relatedByClassName($searchClasses));
             }
         }
     }
     return $results;
 }
 /**
  * Recursively search children of current page to find a particular classtype
  *
  * @param $parentPage DataObject The Object of which you want to find the children
  * @param $classType String The text string to match `ClassName` field
  * @return DataObjectSet of items if Class $classType
  */
 function getChildrenOfType($parentPage, $classType = null)
 {
     $children = $parentPage->AllChildren();
     if (!isset($childrenOfType)) {
         $childrenOfType = new ArrayList();
     }
     if ($children) {
         foreach ($children as $item) {
             $childrenOfType->merge($this->getChildrenOfType($item, $classType));
         }
     }
     if (isset($classType) && $CurrentPage->ClassName == $classType || !isset($classType)) {
         if ($parentPage->HasGeoInfo) {
             $childrenOfType->push($parentPage);
         }
     }
     return $childrenOfType ? $childrenOfType : new ArrayList();
 }
Пример #21
0
 function FutureEvents($num, $filter = '')
 {
     if ($this->event_manager == null) {
         $this->buildEventManager();
     }
     $filterLowerCase = strtolower($filter);
     $events_array = new ArrayList();
     if ($filterLowerCase != 'other') {
         $filter_array = array('EventEndDate:GreaterThanOrEqual' => date('Y-m-d'));
         if (strtolower($filter) != 'all' && $filter != '') {
             $filter_array['EventCategory'] = $filter;
         }
         $pulled_events = EventPage::get()->filter($filter_array)->sort('EventStartDate', 'ASC')->limit($num)->toArray();
     } else {
         $pulled_events = EventPage::get()->where("EventCategory is null and EventEndDate >= CURDATE()")->sort('EventStartDate', 'ASC')->limit($num)->toArray();
     }
     $events_array->merge($pulled_events);
     return $events_array->sort('EventStartDate', 'ASC')->limit($num, 0)->toArray();
 }
 /**
  * Returns all pages that will be moved under this page when they will be archived in the future. Does not return
  * pages that are already located under this page.
  *
  * @param bool $include_disabled If true, also those pages will be returned that have AutoArchiveOn set to false.
  * @return ArrayList
  */
 public function Archivables($include_disabled = false)
 {
     $result = new ArrayList();
     $owner = $this->owner;
     foreach (AutoArchivableExtension::getExtendedClasses() as $class_name) {
         $archivables = SiteTree::get($class_name)->exclude('ParentID', $owner->ID);
         if (!$include_disabled) {
             $archivables = $archivables->exclude('AutoArchiveOn', false);
         }
         $result->merge($archivables->filterByCallback(function ($archivable) use($owner) {
             if ($archivable->getDestination()) {
                 return $owner->ID == $archivable->getDestination()->ID;
             } else {
                 return false;
             }
         }));
     }
     return $result;
 }
Пример #23
0
 /**
  * Caution: Only call on instances, not through a singleton.
  *
  * @return FieldSet
  */
 public function getCMSFields()
 {
     Requirements::javascript(SAPPHIRE_DIR . '/javascript/PermissionCheckboxSetField.js');
     $fields = new FieldList(new TabSet("Root", new Tab('Members', _t('SecurityAdmin.MEMBERS', 'Members'), new TextField("Title", $this->fieldLabel('Title')), $memberList = new MemberTableField(Controller::has_curr() ? Controller::curr() : new Controller(), "Members", $this, null, false)), $permissionsTab = new Tab('Permissions', _t('SecurityAdmin.PERMISSIONS', 'Permissions'), new PermissionCheckboxSetField('Permissions', false, 'Permission', 'GroupID', $this)), new Tab('IPAddresses', _t('Security.IPADDRESSES', 'IP Addresses'), new LiteralField("", _t('SecurityAdmin.IPADDRESSESHELP', "<p>You can restrict this group to a particular \n\t\t\t\t\t\tIP address range (one range per line). <br />Ranges can be in any of the following forms: <br />\n\t\t\t\t\t\t203.96.152.12<br />\n\t\t\t\t\t\t203.96.152/24<br />\n\t\t\t\t\t\t203.96/16<br />\n\t\t\t\t\t\t203/8<br /><br />If you enter one or more IP address ranges in this box, then members will only get\n\t\t\t\t\t\tthe rights of being in this group if they log on from one of the valid IP addresses.  It won't prevent\n\t\t\t\t\t\tpeople from logging in.  This is because the same user might have to log in to access parts of the\n\t\t\t\t\t\tsystem without IP address restrictions.")), new TextareaField("IPRestrictions", "IP Ranges", 10))));
     // Only add a dropdown for HTML editor configurations if more than one is available.
     // Otherwise Member->getHtmlEditorConfigForCMS() will default to the 'cms' configuration.
     $editorConfigMap = HtmlEditorConfig::get_available_configs_map();
     if (count($editorConfigMap) > 1) {
         $fields->addFieldToTab('Root.Permissions', new DropdownField('HtmlEditorConfig', 'HTML Editor Configuration', $editorConfigMap), 'Permissions');
     }
     if (!Permission::check('EDIT_PERMISSIONS')) {
         $fields->removeFieldFromTab('Root', 'Permissions');
         $fields->removeFieldFromTab('Root', 'IP Addresses');
     }
     // Only show the "Roles" tab if permissions are granted to edit them,
     // and at least one role exists
     if (Permission::check('APPLY_ROLES') && DataObject::get('PermissionRole')) {
         $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.ROLES', 'Roles'));
         $fields->addFieldToTab('Root.Roles', new LiteralField("", "<p>" . _t('SecurityAdmin.ROLESDESCRIPTION', "This section allows you to add roles to this group. Roles are logical groupings of permissions, which can be editied in the Roles tab") . "</p>"));
         // Add roles (and disable all checkboxes for inherited roles)
         $allRoles = Permission::check('ADMIN') ? DataObject::get('PermissionRole') : DataObject::get('PermissionRole', 'OnlyAdminCanApply = 0');
         $groupRoles = $this->Roles();
         $inheritedRoles = new ArrayList();
         $ancestors = $this->getAncestors();
         foreach ($ancestors as $ancestor) {
             $ancestorRoles = $ancestor->Roles();
             if ($ancestorRoles) {
                 $inheritedRoles->merge($ancestorRoles);
             }
         }
         $fields->findOrMakeTab('Root.Roles', 'Root.' . _t('SecurityAdmin.ROLES', 'Roles'));
         $fields->addFieldToTab('Root.Roles', $rolesField = new CheckboxSetField('Roles', 'Roles', $allRoles));
         $rolesField->setDefaultItems($inheritedRoles->column('ID'));
         $rolesField->setDisabledItems($inheritedRoles->column('ID'));
     }
     $memberList->setPermissions(array('edit', 'delete', 'export', 'add', 'inlineadd'));
     $memberList->setPopupCaption(_t('SecurityAdmin.VIEWUSER', 'View User'));
     $fields->push($idField = new HiddenField("ID"));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 public function getAllCalendars()
 {
     $calendars = new ArrayList();
     $calendars->push($this);
     $calendars->merge($this->NestedCalendars());
     return $calendars;
 }
 /**
  * Mark duplicate attributes
  *
  * @param SS_List $list
  * @return SS_List
  */
 private function markDuplicates($list)
 {
     $duplicates = $this->findDuplicates($list, 'MetaTitle')->map('ID', 'ID')->toArray();
     $duplicateList = new ArrayList();
     foreach ($list as $item) {
         if (in_array($item->ID, $duplicates)) {
             $item->IsDuplicate = true;
             $duplicateList->push($item);
         }
     }
     $duplicates = $this->findDuplicates($list, 'MetaDescription')->map('ID', 'ID')->toArray();
     foreach ($list as $item) {
         if (in_array($item->ID, $duplicates)) {
             $item->IsDuplicate = true;
             if (!$list->byID($item->ID)) {
                 $duplicateList->push($item);
             }
         }
     }
     $duplicateList->merge($list);
     $duplicateList->removeDuplicates();
     return $duplicateList;
 }
Пример #26
0
 /**
  * Get a member SQLMap of members in specific groups
  * 
  * If no $groups is passed, all members will be returned
  * 
  * @param mixed $groups - takes a SS_List, an array or a single Group.ID
  * @return SQLMap Returns an SQLMap that returns all Member data.
  * @see map()
  */
 public static function map_in_groups($groups = null)
 {
     $groupIDList = array();
     if ($groups instanceof SS_List) {
         foreach ($groups as $group) {
             $groupIDList[] = $group->ID;
         }
     } elseif (is_array($groups)) {
         $groupIDList = $groups;
     } elseif ($groups) {
         $groupIDList[] = $groups;
     }
     // No groups, return all Members
     if (!$groupIDList) {
         return Member::get()->sort(array('Surname' => 'ASC', 'FirstName' => 'ASC'))->map();
     }
     $membersList = new ArrayList();
     // This is a bit ineffective, but follow the ORM style
     foreach (Group::get()->byIDs($groupIDList) as $group) {
         $membersList->merge($group->Members());
     }
     $membersList->removeDuplicates('ID');
     return $membersList->map();
 }
 /**
  * Returns the filters which should show in-page gathered via provideGridListFilters. These are composed of those specifically set on the GridList first
  * and then those for the current page which may have an alternate strategy to provide them, such as most popular filters from child pages.
  *
  * @return \ArrayList
  */
 protected function filters($mode)
 {
     static $filters;
     if (!$filters) {
         $providers = $this->providers();
         $filters = new \ArrayList();
         foreach ($providers as $provider) {
             // first get filters which have been added specifically to the GridList, e.g. via a HasGridListFilters extendiong on the extended class
             // this will return an array of SS_Lists
             $lists = $provider->extend('provideGridListFilters');
             foreach ($lists as $list) {
                 $filters->merge($list);
             }
             $filters->removeDuplicates();
             $items = $this->items($mode);
             $provider->extend('constrainGridListFilters', $items, $filters);
         }
     }
     return $filters;
 }
 function hibImagesFromChildren()
 {
     $hibImages = new ArrayList();
     if ($this->owner->hasMethod("Children")) {
         if ($this->owner->Children()) {
             foreach ($this->owner->Children() as $child) {
                 $tempImages = $child->showHibImages(0, false);
                 if (isset($tempImages) && $tempImages->Count() > 0) {
                     $hibImages->merge($tempImages);
                 }
                 $tempImages = $child->hibImagesFromChildren();
                 if (isset($tempImages) && $tempImages->Count() > 0) {
                     $hibImages->merge($tempImages);
                 }
             }
         }
     }
     return $hibImages;
 }
Пример #29
0
 /**
  * Caution: Only call on instances, not through a singleton.
  * The "root group" fields will be created through {@link SecurityAdmin->EditForm()}.
  *
  * @return FieldList
  */
 public function getCMSFields()
 {
     Requirements::javascript(FRAMEWORK_DIR . '/javascript/PermissionCheckboxSetField.js');
     $fields = new FieldList(new TabSet("Root", new Tab('Members', _t('SecurityAdmin.MEMBERS', 'Members'), new TextField("Title", $this->fieldLabel('Title')), $parentidfield = DropdownField::create('ParentID', $this->fieldLabel('Parent'), Group::get()->exclude('ID', $this->ID)->map('ID', 'Breadcrumbs'))->setEmptyString(' '), new TextareaField('Description', $this->fieldLabel('Description'))), $permissionsTab = new Tab('Permissions', _t('SecurityAdmin.PERMISSIONS', 'Permissions'), $permissionsField = new PermissionCheckboxSetField('Permissions', false, 'Permission', 'GroupID', $this))));
     $parentidfield->setDescription(_t('Group.GroupReminder', 'If you choose a parent group, this group will take all it\'s roles'));
     // Filter permissions
     // TODO SecurityAdmin coupling, not easy to get to the form fields through GridFieldDetailForm
     $permissionsField->setHiddenPermissions((array) Config::inst()->get('SecurityAdmin', 'hidden_permissions'));
     if ($this->ID) {
         $group = $this;
         $config = GridFieldConfig_RelationEditor::create();
         $config->addComponent(new GridFieldButtonRow('after'));
         $config->addComponents(new GridFieldExportButton('buttons-after-left'));
         $config->addComponents(new GridFieldPrintButton('buttons-after-left'));
         $config->getComponentByType('GridFieldAddExistingAutocompleter')->setResultsFormat('$Title ($Email)')->setSearchFields(array('FirstName', 'Surname', 'Email'));
         $config->getComponentByType('GridFieldDetailForm')->setValidator(new Member_Validator())->setItemEditFormCallback(function ($form, $component) use($group) {
             $record = $form->getRecord();
             $groupsField = $form->Fields()->dataFieldByName('DirectGroups');
             if ($groupsField) {
                 // If new records are created in a group context,
                 // set this group by default.
                 if ($record && !$record->ID) {
                     $groupsField->setValue($group->ID);
                 } elseif ($record && $record->ID) {
                     // TODO Mark disabled once chosen.js supports it
                     // $groupsField->setDisabledItems(array($group->ID));
                     $form->Fields()->replaceField('DirectGroups', $groupsField->performReadonlyTransformation());
                 }
             }
         });
         $memberList = GridField::create('Members', false, $this->DirectMembers(), $config)->addExtraClass('members_grid');
         // @todo Implement permission checking on GridField
         //$memberList->setPermissions(array('edit', 'delete', 'export', 'add', 'inlineadd'));
         $fields->addFieldToTab('Root.Members', $memberList);
     }
     // Only add a dropdown for HTML editor configurations if more than one is available.
     // Otherwise Member->getHtmlEditorConfigForCMS() will default to the 'cms' configuration.
     $editorConfigMap = HtmlEditorConfig::get_available_configs_map();
     if (count($editorConfigMap) > 1) {
         $fields->addFieldToTab('Root.Permissions', new DropdownField('HtmlEditorConfig', 'HTML Editor Configuration', $editorConfigMap), 'Permissions');
     }
     if (!Permission::check('EDIT_PERMISSIONS')) {
         $fields->removeFieldFromTab('Root', 'Permissions');
     }
     // Only show the "Roles" tab if permissions are granted to edit them,
     // and at least one role exists
     if (Permission::check('APPLY_ROLES') && DataObject::get('PermissionRole')) {
         $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.ROLES', 'Roles'));
         $fields->addFieldToTab('Root.Roles', new LiteralField("", "<p>" . _t('SecurityAdmin.ROLESDESCRIPTION', "Roles are predefined sets of permissions, and can be assigned to groups.<br />" . "They are inherited from parent groups if required.") . '<br />' . sprintf('<a href="%s" class="add-role">%s</a>', singleton('SecurityAdmin')->Link('show/root#Root_Roles'), _t('Group.RolesAddEditLink', 'Manage roles')) . "</p>"));
         // Add roles (and disable all checkboxes for inherited roles)
         $allRoles = PermissionRole::get();
         if (!Permission::check('ADMIN')) {
             $allRoles = $allRoles->filter("OnlyAdminCanApply", 0);
         }
         if ($this->ID) {
             $groupRoles = $this->Roles();
             $inheritedRoles = new ArrayList();
             $ancestors = $this->getAncestors();
             foreach ($ancestors as $ancestor) {
                 $ancestorRoles = $ancestor->Roles();
                 if ($ancestorRoles) {
                     $inheritedRoles->merge($ancestorRoles);
                 }
             }
             $groupRoleIDs = $groupRoles->column('ID') + $inheritedRoles->column('ID');
             $inheritedRoleIDs = $inheritedRoles->column('ID');
         } else {
             $groupRoleIDs = array();
             $inheritedRoleIDs = array();
         }
         $rolesField = ListboxField::create('Roles', false, $allRoles->map()->toArray())->setDefaultItems($groupRoleIDs)->setAttribute('data-placeholder', _t('Group.AddRole', 'Add a role for this group'))->setDisabledItems($inheritedRoleIDs);
         if (!$allRoles->Count()) {
             $rolesField->setAttribute('data-placeholder', _t('Group.NoRoles', 'No roles found'));
         }
         $fields->addFieldToTab('Root.Roles', $rolesField);
     }
     $fields->push($idField = new HiddenField("ID"));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 /**
  * Gets all orphans from "Stage" and "Live" stages.
  * 
  * @param string $class
  * @param string $filter
  * @param string $sort
  * @param string $join
  * @param int|array $limit
  * @return SS_List
  */
 public function getOrphanedPages($class = 'SiteTree', $filter = '', $sort = null, $join = null, $limit = null)
 {
     $filter .= $filter ? ' AND ' : '';
     $filter .= sprintf("\"%s\".\"ParentID\" != 0 AND \"Parents\".\"ID\" IS NULL", $class);
     $orphans = new ArrayList();
     foreach (array('Stage', 'Live') as $stage) {
         $joinByStage = $join;
         $table = $class;
         $table .= $stage == 'Live' ? '_Live' : '';
         $stageOrphans = Versioned::get_by_stage($class, $stage, $filter, $sort, null, $limit)->leftJoin($table, "\"{$table}\".\"ParentID\" = \"Parents\".\"ID\"", "Parents");
         $orphans->merge($stageOrphans);
     }
     $orphans->removeDuplicates();
     return $orphans;
 }