public function testRSSFeedWithShortcode()
 {
     $list = new ArrayList();
     $list->push(new RSSFeedTest_ItemD());
     $rssFeed = new RSSFeed($list, "http://www.example.com", "Test RSS Feed", "Test RSS Feed Description");
     $content = $rssFeed->outputToBrowser();
     $this->assertContains('<link>http://www.example.org/item-d.html</link>', $content);
     $this->assertContains('<title>ItemD</title>', $content);
     $this->assertContains('<description><![CDATA[<p>ItemD Content test shortcode output</p>]]></description>', $content);
 }
 /**
  * Similar to {@link groupBy()}, but returns
  * the data in a format which is suitable for usage in templates.
  *
  * @param  string $index
  * @param  string $children Name of the control under which children can be iterated on
  * @return ArrayList
  */
 public function GroupedBy($index, $children = 'Children')
 {
     $grouped = $this->groupBy($index);
     $result = new ArrayList();
     foreach ($grouped as $indVal => $list) {
         $list = GroupedList::create($list);
         $result->push(new ArrayData(array($index => $indVal, $children => $list)));
     }
     return $result;
 }
 public function Times()
 {
     $output = new ArrayList();
     for ($i = 0; $i < $this->value; $i++) {
         $output->push(new ArrayData(array('Number' => $i + 1)));
     }
     return $output;
 }
 /**
  * Test different data sources
  */
 public function testSources()
 {
     // Array
     $items = array('a' => 'Apple', 'b' => 'Banana', 'c' => 'Cranberry');
     $field = new CheckboxSetField('Field', null, $items);
     $this->assertEquals($items, $field->getSource());
     // SS_List
     $list = new ArrayList(array(new ArrayData(array('ID' => 'a', 'Title' => 'Apple')), new ArrayData(array('ID' => 'b', 'Title' => 'Banana')), new ArrayData(array('ID' => 'c', 'Title' => 'Cranberry'))));
     $field2 = new CheckboxSetField('Field', null, $list);
     $this->assertEquals($items, $field2->getSource());
     $field3 = new CheckboxSetField('Field', null, $list->map());
     $this->assertEquals($items, $field3->getSource());
 }
 /**
  * Build a potentially nested fieldgroup
  *
  * @param mixed $valueOrGroup Value of item, or title of group
  * @param string|array $titleOrOptions Title of item, or options in grouip
  * @return ArrayData Data for this item
  */
 protected function getFieldOption($valueOrGroup, $titleOrOptions)
 {
     // Return flat option
     if (!is_array($titleOrOptions)) {
         return parent::getFieldOption($valueOrGroup, $titleOrOptions);
     }
     // Build children from options list
     $options = new ArrayList();
     foreach ($titleOrOptions as $childValue => $childTitle) {
         $options->push($this->getFieldOption($childValue, $childTitle));
     }
     return new ArrayData(array('Title' => $valueOrGroup, 'Options' => $options));
 }
 public function testArrayListInput()
 {
     $button = new GridFieldExportButton();
     $this->gridField->getConfig()->addComponent(new GridFieldPaginator());
     //Create an ArrayList 1 greater the Paginator's default 15 rows
     $arrayList = new ArrayList();
     for ($i = 1; $i <= 16; $i++) {
         $dataobject = new DataObject(array('ID' => $i));
         $arrayList->add($dataobject);
     }
     $this->gridField->setList($arrayList);
     $this->assertEquals("ID\n" . "1\n" . "2\n" . "3\n" . "4\n" . "5\n" . "6\n" . "7\n" . "8\n" . "9\n" . "10\n" . "11\n" . "12\n" . "13\n" . "14\n" . "15\n" . "16\n", $button->generateExportFileData($this->gridField));
 }
 /**
  * Gets the list of options to render in this formfield
  *
  * @return ArrayList
  */
 public function getOptions()
 {
     $selectedValues = $this->getValueArray();
     $defaultItems = $this->getDefaultItems();
     // Generate list of options to display
     $odd = 0;
     $formID = $this->ID();
     $options = new ArrayList();
     foreach ($this->getSource() as $itemValue => $title) {
         $itemID = Convert::raw2htmlid("{$formID}_{$itemValue}");
         $odd = ($odd + 1) % 2;
         $extraClass = $odd ? 'odd' : 'even';
         $extraClass .= ' val' . preg_replace('/[^a-zA-Z0-9\\-\\_]/', '_', $itemValue);
         $itemChecked = in_array($itemValue, $selectedValues) || in_array($itemValue, $defaultItems);
         $itemDisabled = $this->isDisabled() || in_array($itemValue, $defaultItems);
         $options->push(new ArrayData(array('ID' => $itemID, 'Class' => $extraClass, 'Name' => "{$this->name}[{$itemValue}]", 'Value' => $itemValue, 'Title' => $title, 'isChecked' => $itemChecked, 'isDisabled' => $itemDisabled)));
     }
     $this->extend('updateGetOptions', $options);
     return $options;
 }
 /**
  * Return this field's linked items
  */
 public function getItems()
 {
     // If the value has been set, use that
     if ($this->value != 'unchanged' && is_array($this->sourceObject)) {
         $items = array();
         $values = is_array($this->value) ? $this->value : preg_split('/ *, */', trim($this->value));
         foreach ($values as $value) {
             $item = new stdClass();
             $item->ID = $value;
             $item->Title = $this->sourceObject[$value];
             $items[] = $item;
         }
         return $items;
         // Otherwise, look data up from the linked relation
     }
     if ($this->value != 'unchanged' && is_string($this->value)) {
         $items = new ArrayList();
         $ids = explode(',', $this->value);
         foreach ($ids as $id) {
             if (!is_numeric($id)) {
                 continue;
             }
             $item = DataObject::get_by_id($this->sourceObject, $id);
             if ($item) {
                 $items->push($item);
             }
         }
         return $items;
     } else {
         if ($this->form) {
             $fieldName = $this->name;
             $record = $this->form->getRecord();
             if (is_object($record) && $record->hasMethod($fieldName)) {
                 return $record->{$fieldName}();
             }
         }
     }
 }
 /**
  * Retrieves a customised list of all File records to ensure they are
  * properly viewable when rendered in the field template.
  *
  * @return SS_List[ViewableData_Customised]
  */
 public function getCustomisedItems()
 {
     $customised = new ArrayList();
     foreach ($this->getItems() as $file) {
         $customised->push($this->customiseFile($file));
     }
     return $customised;
 }
 /**
  * Export core.
  *
  * @param GridField $gridField
  * @return ArrayData
  */
 public function generatePrintData(GridField $gridField)
 {
     $printColumns = $this->getPrintColumnsForGridField($gridField);
     $header = null;
     if ($this->printHasHeader) {
         $header = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $header->push(new ArrayData(array("CellString" => $label)));
         }
     }
     $items = $gridField->getManipulatedList();
     $itemRows = new ArrayList();
     /** @var DataObject $item */
     foreach ($items->limit(null) as $item) {
         $itemRow = new ArrayList();
         foreach ($printColumns as $field => $label) {
             $value = $gridField->getDataFieldValue($item, $field);
             if ($item->escapeTypeForField($field) != 'xml') {
                 $value = Convert::raw2xml($value);
             }
             $itemRow->push(new ArrayData(array("CellString" => $value)));
         }
         $itemRows->push(new ArrayData(array("ItemRow" => $itemRow)));
         if ($item->hasMethod('destroy')) {
             $item->destroy();
         }
     }
     $ret = new ArrayData(array("Title" => $this->getTitle($gridField), "Header" => $header, "ItemRows" => $itemRows, "Datetime" => DBDatetime::now(), "Member" => Member::currentUser()));
     return $ret;
 }
 /**
  * Returns all components extending a certain class, or implementing a certain interface.
  *
  * @param string $type Class name or interface
  * @return ArrayList Of GridFieldComponent
  */
 public function getComponentsByType($type)
 {
     $components = new ArrayList();
     foreach ($this->components as $component) {
         if ($component instanceof $type) {
             $components->push($component);
         }
     }
     return $components;
 }
 /**
  * Render server configuration file from a template file
  *
  * @param string $template
  * @return DBHTMLText Rendered results
  */
 protected function renderTemplate($template)
 {
     // Build allowed extensions
     $allowedExtensions = new ArrayList();
     foreach (\File::config()->allowed_extensions as $extension) {
         if ($extension) {
             $allowedExtensions->push(new \ArrayData(array('Extension' => preg_quote($extension))));
         }
     }
     $viewer = new \SSViewer(array($template));
     return (string) $viewer->process(new \ArrayData(array('AllowedExtensions' => $allowedExtensions)));
 }
 public function testTotalItems()
 {
     $list = GroupedList::create(ArrayList::create(array(ArrayData::create(array('Name' => 'AAA', 'Number' => '111')), ArrayData::create(array('Name' => 'BBB', 'Number' => '111')), ArrayData::create(array('Name' => 'AAA', 'Number' => '222')), ArrayData::create(array('Name' => 'BBB', 'Number' => '111')))));
     $this->assertEquals(4, $list->TotalItems());
 }
 /**
  * @param bool $unlinked
  * @return ArrayList
  */
 public function Breadcrumbs($unlinked = false)
 {
     $items = new ArrayList(array(new ArrayData(array('Title' => $this->menu_title(), 'Link' => $unlinked ? false : $this->Link()))));
     $record = $this->currentPage();
     if ($record && $record->exists()) {
         if ($record->hasExtension(Hierarchy::class)) {
             $ancestors = $record->getAncestors();
             $ancestors = new ArrayList(array_reverse($ancestors->toArray()));
             $ancestors->push($record);
             foreach ($ancestors as $ancestor) {
                 $items->push(new ArrayData(array('Title' => $ancestor->MenuTitle ? $ancestor->MenuTitle : $ancestor->Title, 'Link' => $unlinked ? false : Controller::join_links($this->Link('show'), $ancestor->ID))));
             }
         } else {
             $items->push(new ArrayData(array('Title' => $record->MenuTitle ? $record->MenuTitle : $record->Title, 'Link' => $unlinked ? false : Controller::join_links($this->Link('show'), $record->ID))));
         }
     }
     return $items;
 }
 /**
  * Returns all of the children for the CMS Tree.
  * Filters to only those groups that the current user can edit
  */
 public function AllChildrenIncludingDeleted()
 {
     /** @var Hierarchy $extInstance */
     $extInstance = $this->getExtensionInstance('SilverStripe\\ORM\\Hierarchy\\Hierarchy');
     $extInstance->setOwner($this);
     $children = $extInstance->AllChildrenIncludingDeleted();
     $extInstance->clearOwner();
     $filteredChildren = new ArrayList();
     if ($children) {
         foreach ($children as $child) {
             if ($child->canView()) {
                 $filteredChildren->push($child);
             }
         }
     }
     return $filteredChildren;
 }
 public function obj($fieldName, $arguments = null, $cache = false, $cacheName = null)
 {
     $childName = $this->argedName($fieldName, $arguments);
     // Special field name Loop### to create a list
     if (preg_match('/^Loop([0-9]+)$/', $fieldName, $matches)) {
         $output = new ArrayList();
         for ($i = 0; $i < $matches[1]; $i++) {
             $output->push(new SSViewerTestFixture($childName));
         }
         return $output;
     } else {
         if (preg_match('/NotSet/i', $fieldName)) {
             return new ViewableData();
         } else {
             return new SSViewerTestFixture($childName);
         }
     }
 }
 public function TestLoopCall()
 {
     $this->testLoopCalls++;
     return ArrayList::create(array(ArrayData::create(array('Message' => 'One')), ArrayData::create(array('Message' => 'Two'))));
 }
 /**
  * Get a SS_List of the changed fields.
  * Each element is an array data containing
  *  - Name: The field name
  *  - Title: The human-readable field title
  *  - Diff: An HTML diff showing the changes
  *  - From: The older version of the field
  *  - To: The newer version of the field
  */
 public function ChangedFields()
 {
     $changedFields = new ArrayList();
     if ($this->fromRecord) {
         $base = $this->fromRecord;
         $fields = array_keys($this->fromRecord->toMap());
     } else {
         $base = $this->toRecord;
         $fields = array_keys($this->toRecord->toMap());
     }
     foreach ($fields as $field) {
         if (in_array($field, $this->ignoredFields)) {
             continue;
         }
         if (!$this->fromRecord || $this->fromRecord->{$field} != $this->toRecord->{$field}) {
             // Only show HTML diffs for fields which allow HTML values in the first place
             $fieldObj = $this->toRecord->dbObject($field);
             if ($this->fromRecord) {
                 $fieldDiff = Diff::compareHTML($this->fromRecord->{$field}, $this->toRecord->{$field}, !$fieldObj || $fieldObj->stat('escape_type') != 'xml');
             } else {
                 if ($fieldObj && $fieldObj->stat('escape_type') == 'xml') {
                     $fieldDiff = "<ins>" . $this->toRecord->{$field} . "</ins>";
                 } else {
                     $fieldDiff = "<ins>" . Convert::raw2xml($this->toRecord->{$field}) . "</ins>";
                 }
             }
             $changedFields->push(new ArrayData(array('Name' => $field, 'Title' => $base->fieldLabel($field), 'Diff' => $fieldDiff, 'From' => $this->fromRecord ? $this->fromRecord->{$field} : null, 'To' => $this->toRecord ? $this->toRecord->{$field} : null)));
         }
     }
     return $changedFields;
 }
 /**
  * Note that, in the current implementation, the filtered list will be an ArrayList, but this may change in a
  * future implementation.
  * @see Filterable::filterByCallback()
  *
  * @example $list = $list->filterByCallback(function($item, $list) { return $item->Age == 9; })
  * @param callable $callback
  * @return ArrayList (this may change in future implementations)
  */
 public function filterByCallback($callback)
 {
     if (!is_callable($callback)) {
         throw new LogicException(sprintf("SS_Filterable::filterByCallback() passed callback must be callable, '%s' given", gettype($callback)));
     }
     $output = ArrayList::create();
     foreach ($this->list as $item) {
         if (call_user_func($callback, $item, $this->list)) {
             $output->push($item);
         }
     }
     return $output;
 }
 /**
  * Return a list of all the versions available.
  *
  * @param  string $filter
  * @param  string $sort
  * @param  string $limit
  * @param  string $join   Deprecated, use leftJoin($table, $joinClause) instead
  * @param  string $having
  * @return ArrayList
  */
 public function allVersions($filter = "", $sort = "", $limit = "", $join = "", $having = "")
 {
     // Make sure the table names are not postfixed (e.g. _Live)
     $oldMode = static::get_reading_mode();
     static::set_stage(static::DRAFT);
     $owner = $this->owner;
     $list = DataObject::get(get_class($owner), $filter, $sort, $join, $limit);
     if ($having) {
         $list->having($having);
     }
     $query = $list->dataQuery()->query();
     foreach ($query->getFrom() as $table => $tableJoin) {
         if (is_string($tableJoin) && $tableJoin[0] == '"') {
             $baseTable = str_replace('"', '', $tableJoin);
         } elseif (is_string($tableJoin) && substr($tableJoin, 0, 5) != 'INNER') {
             $query->setFrom(array($table => "LEFT JOIN \"{$table}\" ON \"{$table}\".\"RecordID\"=\"{$baseTable}_versions\".\"RecordID\"" . " AND \"{$table}\".\"Version\" = \"{$baseTable}_versions\".\"Version\""));
         }
         $query->renameTable($table, $table . '_versions');
     }
     // Add all <basetable>_versions columns
     foreach (Config::inst()->get('SilverStripe\\ORM\\Versioning\\Versioned', 'db_for_versions_table') as $name => $type) {
         $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
     }
     $query->addWhere(array("\"{$baseTable}_versions\".\"RecordID\" = ?" => $owner->ID));
     $query->setOrderBy($sort ? $sort : "\"{$baseTable}_versions\".\"LastEdited\" DESC, \"{$baseTable}_versions\".\"Version\" DESC");
     $records = $query->execute();
     $versions = new ArrayList();
     foreach ($records as $record) {
         $versions->push(new Versioned_Version($record));
     }
     Versioned::set_reading_mode($oldMode);
     return $versions;
 }
 /**
  * Generate a CSV import form for a single {@link DataObject} subclass.
  *
  * @return Form
  */
 public function ImportForm()
 {
     $modelSNG = singleton($this->modelClass);
     $modelName = $modelSNG->i18n_singular_name();
     // check if a import form should be generated
     if (!$this->showImportForm || is_array($this->showImportForm) && !in_array($this->modelClass, $this->showImportForm)) {
         return false;
     }
     $importers = $this->getModelImporters();
     if (!$importers || !isset($importers[$this->modelClass])) {
         return false;
     }
     if (!$modelSNG->canCreate(Member::currentUser())) {
         return false;
     }
     $fields = new FieldList(new HiddenField('ClassName', _t('ModelAdmin.CLASSTYPE'), $this->modelClass), new FileField('_CsvFile', false));
     // get HTML specification for each import (column names etc.)
     $importerClass = $importers[$this->modelClass];
     $importer = new $importerClass($this->modelClass);
     $spec = $importer->getImportSpec();
     $specFields = new ArrayList();
     foreach ($spec['fields'] as $name => $desc) {
         $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
     }
     $specRelations = new ArrayList();
     foreach ($spec['relations'] as $name => $desc) {
         $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
     }
     $specHTML = $this->customise(array('ClassName' => $this->sanitiseClassName($this->modelClass), 'ModelName' => Convert::raw2att($modelName), 'Fields' => $specFields, 'Relations' => $specRelations))->renderWith('Includes/ModelAdmin_ImportSpec');
     $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML));
     $fields->push(new CheckboxField('EmptyBeforeImport', _t('ModelAdmin.EMPTYBEFOREIMPORT', 'Replace data'), false));
     $actions = new FieldList(new FormAction('import', _t('ModelAdmin.IMPORT', 'Import from CSV')));
     $form = new Form($this, "ImportForm", $fields, $actions);
     $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ImportForm'));
     $this->extend('updateImportForm', $form);
     return $form;
 }
 /**
  * Push a single field onto the beginning of this FieldList instance.
  *
  * @param FormField $item The FormField to add
  */
 public function unshift($item)
 {
     $this->onBeforeInsert($item);
     $item->setContainerFieldList($this);
     return parent::unshift($item);
 }
 /**
  * Test that circular dependencies throw an exception
  */
 public function testGridFieldCustomFragmentsCircularDependencyThrowsException()
 {
     $config = GridFieldConfig::create()->addComponents(new GridFieldTest_HTMLFragments(array("level-one" => "first")), new GridFieldTest_HTMLFragments(array("before" => "<div>\$DefineFragment(level-one)</div>")), new GridFieldTest_HTMLFragments(array("level-one" => "<strong>\$DefineFragment(level-two)</strong>")), new GridFieldTest_HTMLFragments(array("level-two" => "<blink>\$DefineFragment(level-one)</blink>")));
     $field = new GridField('testfield', 'testfield', ArrayList::create(), $config);
     $form = new Form(new Controller(), 'testform', new FieldList(array($field)), new FieldList());
     $this->setExpectedException('LogicException');
     $field->FieldHolder();
 }
 /**
  * Return a SS_List of ArrayData objects containing the following pieces of info
  * about each batch action:
  *  - Link
  *  - Title
  *
  * @return ArrayList
  */
 public function batchActionList()
 {
     $actions = $this->batchActions();
     $actionList = new ArrayList();
     foreach ($actions as $urlSegment => $action) {
         $actionObj = $this->buildAction($action['class']);
         if ($actionObj->canView()) {
             $actionDef = new ArrayData(array("Link" => Controller::join_links($this->Link(), $urlSegment), "Title" => $actionObj->getActionTitle()));
             $actionList->push($actionDef);
         }
     }
     return $actionList;
 }
 /**
  * Return all the parents of this class in a set ordered from the lowest to highest parent.
  *
  * @return ArrayList
  */
 public function getAncestors()
 {
     $ancestors = new ArrayList();
     $object = $this->owner;
     while ($object = $object->getParent()) {
         $ancestors->push($object);
     }
     return $ancestors;
 }
 public function testByIDEmpty()
 {
     $list = new ArrayList();
     $element = $list->byID(1);
     $this->assertNull($element);
 }
 protected function extractValue($item, $key)
 {
     if (is_numeric($item)) {
         $item = DataObject::get_by_id($this->dataClass, $item);
     }
     return parent::extractValue($item, $key);
 }
 /**
  * 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 SS_Map Returns an SS_Map that returns all Member data.
  */
 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 a summarised pagination which limits the number of pages shown
  * around the current page for visually balanced.
  *
  * Example: 25 pages total, currently on page 6, context of 4 pages
  * [prev] [1] ... [4] [5] [[6]] [7] [8] ... [25] [next]
  *
  * Example template usage:
  * <code>
  *    <% if MyPages.MoreThanOnePage %>
  *        <% if MyPages.NotFirstPage %>
  *            <a class="prev" href="$MyPages.PrevLink">Prev</a>
  *        <% end_if %>
  *        <% loop MyPages.PaginationSummary(4) %>
  *            <% if CurrentBool %>
  *                $PageNum
  *            <% else %>
  *                <% if Link %>
  *                    <a href="$Link">$PageNum</a>
  *                <% else %>
  *                    ...
  *                <% end_if %>
  *            <% end_if %>
  *        <% end_loop %>
  *        <% if MyPages.NotLastPage %>
  *            <a class="next" href="$MyPages.NextLink">Next</a>
  *        <% end_if %>
  *    <% end_if %>
  * </code>
  *
  * @param  int $context The number of pages to display around the current
  *         page. The number should be event, as half the number of each pages
  *         are displayed on either side of the current one.
  * @return SS_List
  */
 public function PaginationSummary($context = 4)
 {
     $result = new ArrayList();
     $current = $this->CurrentPage();
     $total = $this->TotalPages();
     // Make the number even for offset calculations.
     if ($context % 2) {
         $context--;
     }
     // If the first or last page is current, then show all context on one
     // side of it - otherwise show half on both sides.
     if ($current == 1 || $current == $total) {
         $offset = $context;
     } else {
         $offset = floor($context / 2);
     }
     $left = max($current - $offset, 1);
     $range = range($current - $offset, $current + $offset);
     if ($left + $context > $total) {
         $left = $total - $context;
     }
     for ($i = 0; $i < $total; $i++) {
         $link = HTTP::setGetVar($this->getPaginationGetVar(), $i * $this->getPageLength());
         $num = $i + 1;
         $emptyRange = $num != 1 && $num != $total && ($num == $left - 1 || $num == $left + $context + 1);
         if ($emptyRange) {
             $result->push(new ArrayData(array('PageNum' => null, 'Link' => null, 'CurrentBool' => false)));
         } elseif ($num == 1 || $num == $total || in_array($num, $range)) {
             $result->push(new ArrayData(array('PageNum' => $num, 'Link' => $link, 'CurrentBool' => $current == $num)));
         }
     }
     return $result;
 }
 /**
  * Get the RSS feed entries
  *
  * @return SS_List Returns the {@link RSSFeed_Entry} objects.
  */
 public function Entries()
 {
     $output = new ArrayList();
     if (isset($this->entries)) {
         foreach ($this->entries as $entry) {
             $output->push(RSSFeed_Entry::create($entry, $this->titleField, $this->descriptionField, $this->authorField));
         }
     }
     return $output;
 }