예제 #1
0
 /**
  * Creates a rendered Programme Crawler Field using the .ss template
  * @param type $properties an array of values to decorate the field
  * @return type a rendered template
  */
 function Field($properties = array())
 {
     $obj = $properties ? $this->customise($properties) : $this;
     $obj->Options = ArrayList::create();
     $dobj = DataObject::create();
     $dobj->MyTitle = 'No Color';
     $dobj->Value = '';
     $dobj->CSSRGB = '255 255 255';
     $dobj->CSSHex = '#ffffff';
     $dobj->CSSCMYK = '0 0 0 0';
     $obj->Options->push($dobj);
     $source = ColourSchemes::get()->sort('ID');
     if ($source) {
         foreach ($source as $value) {
             $mobj = DataObject::create();
             $mobj->MyTitle = $value->OPColor;
             $mobj->Value = $value->CSSColor;
             $mobj->CSSRGB = $value->CSSRGB;
             $mobj->CSSHex = $value->CSSHex;
             $mobj->CSSCMYK = $value->CSSCMYK;
             $obj->Options->push($mobj);
         }
     }
     // directly point to the template file
     $tmp = $obj->renderWith(BASE_PATH . '/' . OPCOLORWORKINGFOLDER . "/templates/OpColorField.ss");
     return $tmp;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $subsites = DataObject::get('Subsite');
     if (!$subsites) {
         $subsites = new ArrayList();
     } else {
         $subsites = ArrayList::create($subsites->toArray());
     }
     $subsites->push(new ArrayData(array('Title' => 'Main site', 'ID' => 0)));
     $fields->addFieldToTab('Root.Main', DropdownField::create("CopyContentFromID_SubsiteID", _t('SubsitesVirtualPage.SubsiteField', "Subsite"), $subsites->map('ID', 'Title'))->addExtraClass('subsitestreedropdownfield-chooser no-change-track'), 'CopyContentFromID');
     // Setup the linking to the original page.
     $pageSelectionField = new SubsitesTreeDropdownField("CopyContentFromID", _t('VirtualPage.CHOOSE', "Choose a page to link to"), "SiteTree", "ID", "MenuTitle");
     if (Controller::has_curr() && Controller::curr()->getRequest()) {
         $subsiteID = Controller::curr()->getRequest()->requestVar('CopyContentFromID_SubsiteID');
         $pageSelectionField->setSubsiteID($subsiteID);
     }
     $fields->replaceField('CopyContentFromID', $pageSelectionField);
     // Create links back to the original object in the CMS
     if ($this->CopyContentFromID) {
         $editLink = "admin/pages/edit/show/{$this->CopyContentFromID}/?SubsiteID=" . $this->CopyContentFrom()->SubsiteID;
         $linkToContent = "\n\t\t\t\t<a class=\"cmsEditlink\" href=\"{$editLink}\">" . _t('VirtualPage.EDITCONTENT', 'Click here to edit the content') . "</a>";
         $fields->removeByName("VirtualPageContentLinkLabel");
         $fields->addFieldToTab("Root.Main", $linkToContentLabelField = new LabelField('VirtualPageContentLinkLabel', $linkToContent), 'Title');
         $linkToContentLabelField->setAllowHTML(true);
     }
     $fields->addFieldToTab('Root.Main', TextField::create('CustomMetaTitle', $this->fieldLabel('CustomMetaTitle'))->setDescription(_t('SubsitesVirtualPage.OverrideNote', 'Overrides inherited value from the source')), 'MetaTitle');
     $fields->addFieldToTab('Root.Main', TextareaField::create('CustomMetaKeywords', $this->fieldLabel('CustomMetaTitle'))->setDescription(_t('SubsitesVirtualPage.OverrideNote')), 'MetaKeywords');
     $fields->addFieldToTab('Root.Main', TextareaField::create('CustomMetaDescription', $this->fieldLabel('CustomMetaTitle'))->setDescription(_t('SubsitesVirtualPage.OverrideNote')), 'MetaDescription');
     $fields->addFieldToTab('Root.Main', TextField::create('CustomExtraMeta', $this->fieldLabel('CustomMetaTitle'))->setDescription(_t('SubsitesVirtualPage.OverrideNote')), 'ExtraMeta');
     return $fields;
 }
 public function ChartData()
 {
     $chartData = array();
     $list = ArrayList::create(array());
     $sqlQuery = new SQLQuery();
     $sqlQuery->setFrom('Addon');
     $sqlQuery->setSelect('Created');
     $sqlQuery->selectField('COUNT(*)', 'CountInOneDay');
     $sqlQuery->addWhere('"Created" >= DATE_SUB(NOW(), INTERVAL 30 DAY)');
     $sqlQuery->addGroupBy('DATE(Created)');
     $result = $sqlQuery->execute();
     if (count($result)) {
         foreach ($result as $row) {
             $date = date('j M Y', strtotime($row['Created']));
             if (!isset($chartData[$date])) {
                 $chartData[$date] = $row['CountInOneDay'];
             }
         }
     }
     if (count($chartData)) {
         foreach ($chartData as $x => $y) {
             $list->push(ArrayData::create(array('XValue' => $x, 'YValue' => $y)));
         }
     }
     return $list;
 }
 public function addMessage($message, $type)
 {
     if (!is_a($this->Messages, 'ArrayList')) {
         $this->Messages = ArrayList::create();
     }
     $this->Messages->add(ArrayData::create(array('Message' => $message, 'Type' => $type)));
 }
 public function Inputs()
 {
     if (count($this->linkedFields)) {
         return \ArrayList::create();
     }
     $ranged = is_array($this->settings['start']) && count($this->settings['start']) > 1;
     $minName = $ranged ? 'min' : 'value';
     $fields[$minName] = ['Render' => $this->castedCopy(\NumericField::create($this->Name . '[' . $minName . ']'))];
     $fields[$minName]['Render']->Value = is_array($this->settings['start']) ? $this->settings['start'][0] : $this->settings['start'];
     if ($ranged) {
         $fields['max'] = ['Render' => $this->castedCopy(\NumericField::create($this->Name . '[max]'))];
         $fields['max']['Render']->Value = $this->settings['start'][1];
     }
     $count = 0;
     array_walk($fields, function ($field) use(&$count) {
         if (!isset($field['Handle'])) {
             $field['Handle'] = $count % 2 ? 'upper' : 'lower';
         }
         if (isset($field['Render'])) {
             $field['Render']->removeExtraClass('rangeslider-display')->addExtraClass('rangeslider-linked')->setAttribute('data-rangeslider-handle', $field['Handle']);
         }
         $count++;
     });
     $fields = \ArrayList::create(array_map(function ($field) {
         return \ArrayData::create($field);
     }, $fields));
     if ($this->inputCallback && is_callable($this->inputCallback)) {
         call_user_func_array($this->inputCallback, [$fields]);
     }
     $this->extend('updateInputs', $fields);
     return $fields;
 }
 public function InstaTagMedia($tag = false, $num = false, $shuffle = true)
 {
     $instagram = new Instagram(array('apiKey' => $this->InstagramApiKey, 'apiSecret' => $this->InstagramApiSecret, 'apiCallback' => $this->InstagramApiCallback));
     $media = false;
     $output = false;
     $out = array();
     if (!$tag) {
         $tag = $this->InstagramSearchTerm;
     }
     if (!$num) {
         $num = $this->InstagramItemsCount;
     }
     try {
         $media = $instagram->getTagMedia($tag, 50);
     } catch (Exception $e) {
         SS_Log::log(new Exception(print_r($e, true)), SS_Log::ERR);
     }
     if (is_object($media) && isset($media->data)) {
         foreach ($media->data as $data) {
             if (is_object($data)) {
                 $item = array('caption' => $data->caption ? $data->caption->text : "", 'thumb' => $data->images->thumbnail->url, 'image' => $data->images->standard_resolution->url, 'username' => $data->user->username);
                 array_push($out, $item);
             }
         }
         if ($shuffle) {
             shuffle($out);
         }
         $output = ArrayList::create($out);
         $output = $output->limit($num);
     }
     return $output;
 }
 /**
  * @return FieldList
  */
 public function getCMSFields()
 {
     Requirements::javascript(USERFORMS_DIR . '/javascript/Recipient.js');
     // Determine optional field values
     $form = $this->getFormParent();
     // predefined choices are also candidates
     $multiOptionFields = EditableMultipleOptionField::get()->filter('ParentID', $form->ID);
     // if they have email fields then we could send from it
     $validEmailFromFields = EditableEmailField::get()->filter('ParentID', $form->ID);
     // For the subject, only one-line entry boxes make sense
     $validSubjectFields = ArrayList::create(EditableTextField::get()->filter('ParentID', $form->ID)->exclude('Rows:GreaterThan', 1)->toArray());
     $validSubjectFields->merge($multiOptionFields);
     // To address cannot be unbound, so restrict to pre-defined lists
     $validEmailToFields = $multiOptionFields;
     // Build fieldlist
     $fields = FieldList::create(Tabset::create('Root')->addExtraClass('EmailRecipientForm'));
     // Configuration fields
     $fields->addFieldsToTab('Root.EmailDetails', array(FieldGroup::create(TextField::create('EmailSubject', _t('UserDefinedForm.TYPESUBJECT', 'Type subject'))->setAttribute('style', 'min-width: 400px;'), DropdownField::create('SendEmailSubjectFieldID', _t('UserDefinedForm.SELECTAFIELDTOSETSUBJECT', '.. or select a field to use as the subject'), $validSubjectFields->map('ID', 'Title'))->setEmptyString(''))->setTitle(_t('UserDefinedForm.EMAILSUBJECT', 'Email subject')), FieldGroup::create(TextField::create('EmailAddress', _t('UserDefinedForm.TYPETO', 'Type to address'))->setAttribute('style', 'min-width: 400px;'), DropdownField::create('SendEmailToFieldID', _t('UserDefinedForm.ORSELECTAFIELDTOUSEASTO', '.. or select a field to use as the to address'), $validEmailToFields->map('ID', 'Title'))->setEmptyString(' '))->setTitle(_t('UserDefinedForm.SENDEMAILTO', 'Send email to'))->setDescription(_t('UserDefinedForm.SENDEMAILTO_DESCRIPTION', 'You may enter multiple email addresses as a comma separated list.')), TextField::create('EmailFrom', _t('UserDefinedForm.FROMADDRESS', 'Send email from'))->setDescription(_t('UserDefinedForm.EmailFromContent', "The from address allows you to set who the email comes from. On most servers this " . "will need to be set to an email address on the same domain name as your site. " . "For example on yoursite.com the from address may need to be something@yoursite.com. " . "You can however, set any email address you wish as the reply to address.")), FieldGroup::create(TextField::create('EmailReplyTo', _t('UserDefinedForm.TYPEREPLY', 'Type reply address'))->setAttribute('style', 'min-width: 400px;'), DropdownField::create('SendEmailFromFieldID', _t('UserDefinedForm.ORSELECTAFIELDTOUSEASFROM', '.. or select a field to use as reply to address'), $validEmailFromFields->map('ID', 'Title'))->setEmptyString(' '))->setTitle(_t('UserDefinedForm.REPLYADDRESS', 'Email for reply to'))->setDescription(_t('UserDefinedForm.REPLYADDRESS_DESCRIPTION', 'The email address which the recipient is able to \'reply\' to.'))));
     // Only show the preview link if the recipient has been saved.
     if (!empty($this->EmailTemplate)) {
         $preview = sprintf('<p><a href="%s" target="_blank" class="ss-ui-button">%s</a></p><em>%s</em>', "admin/pages/edit/EditForm/field/EmailRecipients/item/{$this->ID}/preview", _t('UserDefinedForm.PREVIEW_EMAIL', 'Preview email'), _t('UserDefinedForm.PREVIEW_EMAIL_DESCRIPTION', 'Note: Unsaved changes will not appear in the preview.'));
     } else {
         $preview = sprintf('<em>%s</em>', _t('UserDefinedForm.PREVIEW_EMAIL_UNAVAILABLE', 'You can preview this email once you have saved the Recipient.'));
     }
     // Email templates
     $fields->addFieldsToTab('Root.EmailContent', array(CheckboxField::create('HideFormData', _t('UserDefinedForm.HIDEFORMDATA', 'Hide form data from email?')), CheckboxField::create('SendPlain', _t('UserDefinedForm.SENDPLAIN', 'Send email as plain text? (HTML will be stripped)')), DropdownField::create('EmailTemplate', _t('UserDefinedForm.EMAILTEMPLATE', 'Email template'), $this->getEmailTemplateDropdownValues())->addExtraClass('toggle-html-only'), HTMLEditorField::create('EmailBodyHtml', _t('UserDefinedForm.EMAILBODYHTML', 'Body'))->addExtraClass('toggle-html-only'), TextareaField::create('EmailBody', _t('UserDefinedForm.EMAILBODY', 'Body'))->addExtraClass('toggle-plain-only'), LiteralField::create('EmailPreview', '<div id="EmailPreview" class="field toggle-html-only">' . $preview . '</div>')));
     // Custom rules for sending this field
     $grid = new GridField("CustomRules", _t('EditableFormField.CUSTOMRULES', 'Custom Rules'), $this->CustomRules(), $this->getRulesConfig());
     $grid->setDescription(_t('UserDefinedForm.RulesDescription', 'Emails will only be sent to the recipient if the custom rules are met. If no rules are defined, this receipient will receive notifications for every submission.'));
     $fields->addFieldsToTab('Root.CustomRules', array(new DropdownField('CustomRulesCondition', _t('UserDefinedForm.SENDIF', 'Send condition'), array('Or' => 'Any conditions are true', 'And' => 'All conditions are true')), $grid));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 public function handleSave(GridField $grid, DataObjectInterface $record)
 {
     $list = $grid->getList();
     $value = $grid->Value();
     if (!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) {
         // throw error ?
         return;
     }
     $updatedList = ArrayList::create();
     foreach ($value[__CLASS__] as $id => $v) {
         if (!is_numeric($id)) {
             continue;
         }
         $updatedList->push($id);
     }
     $list->exclude(['ID' => $updatedList->toArray()])->removeAll();
     foreach ($updatedList->toArray() as $i => $id) {
         // if list already contains item, leave it there
         if ($list->byID($id)) {
             continue;
         }
         $gridfieldItem = DataObject::get_by_id($list->dataClass, $id);
         if (!$gridfieldItem || !$gridfieldItem->canEdit()) {
             continue;
         }
         $list->add($gridfieldItem);
     }
 }
 public function getInstagramFeedItems()
 {
     $api_url = 'https://api.instagram.com/v1/tags/' . $this->configSettings['DefaultHash'] . '/media/recent?client_id=' . $this->configSettings['ClientID'];
     $ch = curl_init();
     curl_setopt_array($ch, array(CURLOPT_URL => $api_url, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false));
     $output = curl_exec($ch);
     $instagram_json = json_decode($output);
     $whitelist_fields = array('created_time', 'link', 'images', 'likes');
     $row_array = array();
     foreach ($instagram_json->data as $items) {
         $coloumn_array = array();
         foreach ($items as $key => $value) {
             if (in_array($key, $whitelist_fields)) {
                 if ($key == 'images') {
                     $coloumn_array['LowResImage'] = $value->low_resolution->url;
                     $coloumn_array['StandardResImage'] = $value->standard_resolution->url;
                     $coloumn_array['Thumbnail'] = $value->thumbnail->url;
                 } elseif ($key == 'likes') {
                     $coloumn_array['Likes'] = $value->count;
                 } else {
                     $coloumn_array[$key] = $value;
                 }
             }
         }
         array_push($row_array, ArrayData::create($coloumn_array));
     }
     $instagram_feed_arraylist = ArrayList::create($row_array);
     return $instagram_feed_arraylist->renderWith('InstagramFeed');
 }
 /**
  * Gets a list of all the items in the RSS feed given a user-provided URL, limit, and date format
  *
  * @return ArrayList
  */
 public function RSSItems()
 {
     if (!$this->FeedURL) {
         return false;
     }
     $doc = new DOMDocument();
     @$doc->load($this->FeedURL);
     $items = $doc->getElementsByTagName('item');
     $feeds = array();
     foreach ($items as $node) {
         $itemRSS = array('title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue);
         $feeds[] = $itemRSS;
     }
     $output = ArrayList::create(array());
     $count = 0;
     foreach ($feeds as $item) {
         if ($count >= $this->Count) {
             break;
         }
         // Cast the Date
         $date = new Date('Date');
         $date->setValue($item['date']);
         // Cast the Title
         $title = new Text('Title');
         $title->setValue($item['title']);
         $output->push(new ArrayData(array('Title' => $title, 'Date' => $date->Format($this->DateFormat), 'Link' => $item['link'])));
         $count++;
     }
     return $output;
 }
 /**
  * Setup the list of records to show.
  *
  * @param array $params array of filter-rules.
  * @param array $sort
  * @param integer $limit
  *
  * @return ArrayList with the records.
  */
 public function sourceRecords($params, $sort, $limit)
 {
     if ($sort) {
         $parts = explode(' ', $sort);
         $field = $parts[0];
         $direction = $parts[1];
     }
     $filter = array('Comments.ID:GreaterThan' => 0);
     if (count($params) > 0 && isset($params['Title'])) {
         $filter['News.Title:PartialMatch'] = $params['Title'];
     }
     /** @var ArrayList|News[] $ret */
     $ret = News::get()->filter($filter);
     /** @var ArrayList $returnSet */
     $returnSet = ArrayList::create();
     if ($ret) {
         foreach ($ret as $record) {
             $record->Commentcount = $record->Comments()->count();
             $record->Spamcount = $record->Comments()->filter(array('AkismetMarked' => 1))->count();
             $record->Hiddencount = $record->Comments()->filter(array('AkismetMarked' => 0, 'Visible' => 0))->count();
             if (isset($params['Comment']) && $params['Comment'] == 'SPAMCOUNT' && $record->Spamcount > 0) {
                 $returnSet->push($record);
             } elseif (isset($params['Comment']) && $params['Comment'] == 'HIDDENCOUNT' && $record->Hiddencount > 0) {
                 $returnSet->push($record);
             } elseif (isset($params['Comment']) && $params['Comment'] == '' || !isset($params['Comment'])) {
                 $returnSet->push($record);
             }
         }
     }
     return $returnSet;
 }
 public function getItems()
 {
     $viewables = ArrayList::create();
     $source = $this->AbsoluteSource ? $this->Source() : Controller::curr()->data();
     $items = $this->EnforceShowInMenu ? $source->Children() : $source->AllChildren();
     if (!$items || !$items->Count()) {
         return $viewables;
     }
     if ($this->PageTypes) {
         $types = $this->obj('PageTypes')->getValues();
         if (count($types)) {
             $items = $items->filter(array('ClassName' => array_values($types)));
         }
     }
     if ($this->ExcludeItems && $this->AbsoluteSource && $items->Count()) {
         $excludes = $this->obj('ExcludeItems')->getValues();
         if (count($excludes)) {
             $items = $items->exclude(array('ID' => array_values($excludes)));
         }
     }
     foreach ($items as $item) {
         if ($item->canView()) {
             $viewables->push($item);
         }
     }
     return $viewables;
 }
 public function generateMenuItems()
 {
     $all = array();
     $allids = array();
     $public = $this->getPublicNodes();
     foreach ($public as $row) {
         $allids[$row['ID']] = true;
         $all[] = $row;
     }
     // and private nodes
     $private = $this->getPrivateNodes();
     foreach ($private as $row) {
         $allids[$row['ID']] = true;
         $all[] = $row;
     }
     $others = $this->getAdditionalNodes();
     foreach ($others as $row) {
         $allids[$row['ID']] = true;
         $all[] = $row;
     }
     $deferred = array();
     $final = array();
     $hierarchy = array();
     $counter = 0;
     $this->iterateNodes($final, $all, $allids, 0);
     $ordered = ArrayList::create();
     // start at 0
     if (isset($final[0]['kids'])) {
         foreach ($final[0]['kids'] as $id) {
             $node = $final[$id];
             $this->buildLinks($node, null, $ordered, $final);
         }
     }
 }
 public function Weather()
 {
     if (!$this->Location) {
         return false;
     }
     $rnd = time();
     $url = "http://query.yahooapis.com/v1/public/yql?format=json&rnd={$rnd}&diagnostics=true&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q=";
     $query = urlencode("select * from weather.forecast where location in (select id from weather.search where query=\"{$this->Location}\") and u=\"{$this->Units}\"");
     $response = file_get_contents($url . $query);
     if ($response) {
         $result = Convert::json2array($response);
         if (!$result["query"]["results"]) {
             return false;
         }
         $days = ArrayList::create(array());
         $channel = isset($result["query"]["results"]["channel"][0]) ? $result["query"]["results"]["channel"][0] : $result["query"]["results"]["channel"];
         $label = $channel["title"];
         $link = $channel["link"];
         $forecast = $channel["item"]["forecast"];
         for ($i = 0; $i < 2; $i++) {
             $item = $forecast[$i];
             $days->push(ArrayData::create(array('High' => $item["high"], 'Low' => $item["low"], 'ImageURL' => "http://l.yimg.com/a/i/us/we/52/" . $item["code"] . ".gif", 'Label' => $i == 0 ? _t('Dashboard.TODAY', 'Today') : _t('Dashboard.TOMORROW', 'Tomorrow'))));
         }
         $html = $this->customise(array('Location' => str_replace("Yahoo! Weather - ", "", $label), 'Link' => $link, 'Days' => $days))->renderWith('DashboardWeatherContent');
         $this->WeatherHTML = $html;
         $this->write();
         return $html;
     }
     return $this->WeatherHTML;
 }
예제 #15
0
 /**
  * Creates a rendered Programme Crawler Field using the .ss template
  * @param type $properties an array of values to decorate the field
  * @return type a rendered template
  */
 function Field($properties = array())
 {
     $obj = $properties ? $this->customise($properties) : $this;
     $obj->Options = ArrayList::create();
     $dobj = DataObject::create(array('MyTitle' => 'No Color', 'Value' => '', 'CSSRGB' => '255 255 255', 'CSSHex' => '#ffffff', 'CSSCMYK' => '0 0 0 0'));
     $obj->Options->push($dobj);
     //go through source, if object it is a custom color, if not, get data from ColourSchemes
     foreach ($this->getSource() as $value) {
         $mobj = DataObject::create();
         if ($value instanceof Object) {
             $mobj->MyTitle = $value->OPColor;
             $mobj->Value = $value->CSSColor;
             $mobj->CSSRGB = $value->CSSRGB;
             $mobj->CSSHex = $value->CSSHex;
             $mobj->CSSCMYK = $value->CSSCMYK;
         } else {
             $cs = ColourSchemes::get()->filter('OPColor', $value)->first();
             if (!empty($cs)) {
                 $mobj->MyTitle = $cs->OPColor;
                 $mobj->Value = $cs->CSSColor;
                 $mobj->CSSRGB = $cs->CSSRGB;
                 $mobj->CSSHex = $cs->CSSHex;
                 $mobj->CSSCMYK = $cs->CSSCMYK;
             }
         }
         $obj->Options->push($mobj);
     }
     // directly point to the template file
     $tmp = $obj->renderWith(BASE_PATH . '/' . OPCOLORWORKINGFOLDER . "/templates/OpColorField.ss");
     return $tmp;
 }
 /**
  * @return ArrayList Of GridFieldComponent
  */
 public function getComponents()
 {
     if (!$this->components) {
         $this->components = ArrayList::create();
     }
     return $this->components;
 }
 /**
  * Returns a DataList containing Pages.
  * The provided links point to their translated pages.
  * You can use it in templates like this:
  *
  * <% loop LanguageChooser %>
  *   $Title, $Current, and any other vars in your page instance
  * <% end_loop %>
  *
  * @return DataList
  */
 public function LanguageChooser()
 {
     if (!Controller::curr()) {
         return;
     }
     if ($langs = Translatable::get_allowed_locales()) {
         $data = ArrayList::create();
         foreach ($langs as $key => $code) {
             if ($code == Translatable::get_current_locale()) {
                 $this->owner->Current = 'current';
                 $data->push($this->owner);
             } else {
                 $translation = $this->owner->getTranslation($code);
                 if ($translation) {
                     $data->push($translation);
                 } else {
                     $page = Translatable::get_one_by_locale("SiteTree", $code, "URLSegment LIKE 'home%'");
                     if ($page) {
                         $data->push($page);
                     }
                 }
             }
         }
         return $data;
     }
     return false;
 }
 /**
  * Requires the necessary JS and sends the required HTML structure to the template
  * for a responsive image set
  *
  * @param array $config The configuration of the responsive image set from the config
  * @param array $args The arguments passed to the responsive image method, e.g. $MyImage.ResponsiveSet1(800x600)
  * @param string $method The method, or responsive image set, to generate
  * @return SSViewer
  */
 protected function createResponsiveSet($config, $args, $method)
 {
     Requirements::javascript(RESPONSIVE_IMAGES_DIR . '/javascript/picturefill/external/matchmedia.js');
     Requirements::javascript(RESPONSIVE_IMAGES_DIR . '/javascript/picturefill/picturefill.js');
     if (!isset($config['sizes']) || !is_array($config['sizes'])) {
         throw new Exception("Responsive set {$method} does not have sizes defined in its config.");
     }
     if (isset($args[0])) {
         $defaultDimensions = $args[0];
     } elseif (isset($config['default_size'])) {
         $defaultDimensions = $config['default_size'];
     } else {
         $defaultDimensions = Config::inst()->forClass("ResponsiveImageExtension")->default_size;
     }
     if (isset($args[1])) {
         $methodName = $args[1];
     } elseif (isset($config['method'])) {
         $methodName = $config['method'];
     } else {
         $methodName = Config::inst()->forClass("ResponsiveImageExtension")->default_method;
     }
     $sizes = ArrayList::create();
     foreach ($config['sizes'] as $i => $arr) {
         if (!isset($arr['query'])) {
             throw new Exception("Responsive set {$method} does not have a 'query' element defined for size index {$i}");
         }
         if (!isset($arr['size'])) {
             throw new Exception("Responsive set {$method} does not have a 'size' element defined for size index {$i}");
         }
         list($width, $height) = $this->parseDimensions($arr['size']);
         $sizes->push(ArrayData::create(array('Image' => $this->owner->getFormattedImage($methodName, $width, $height), 'Query' => $arr['query'])));
     }
     list($default_width, $default_height) = $this->parseDimensions($defaultDimensions);
     return $this->owner->customise(array('Sizes' => $sizes, 'DefaultImage' => $this->owner->getFormattedImage($methodName, $default_width, $default_height)))->renderWith('ResponsiveImageSet');
 }
예제 #19
0
 public function AllEvents()
 {
     $future = $this->ComingEvents();
     $past = $this->PastEvents();
     $array = array_merge($future->toArray(), $past->toArray());
     return ArrayList::create($array);
 }
 /**
  * Get a set of content languages (for quick language navigation)
  * @example
  * <code>
  * <!-- in your template -->
  * <ul class="langNav">
  * 		<% loop Languages %>
  * 		<li><a href="$Link" class="$LinkingMode" title="$Title.ATT">$Language</a></li>
  * 		<% end_loop %>
  * </ul>
  * </code>
  *
  * @return ArrayList|null
  */
 public function Languages()
 {
     $locales = TranslatableUtility::get_content_languages();
     // there's no need to show a navigation when there's less than 2 languages. So return null
     if (count($locales) < 2) {
         return null;
     }
     $currentLocale = Translatable::get_current_locale();
     $homeTranslated = null;
     if ($home = SiteTree::get_by_link('home')) {
         /** @var SiteTree $homeTranslated */
         $homeTranslated = $home->getTranslation($currentLocale);
     }
     /** @var ArrayList $langSet */
     $langSet = ArrayList::create();
     foreach ($locales as $locale => $name) {
         Translatable::set_current_locale($locale);
         /** @var SiteTree $translation */
         $translation = $this->owner->hasTranslation($locale) ? $this->owner->getTranslation($locale) : null;
         $langSet->push(new ArrayData(array('Locale' => $locale, 'RFC1766' => i18n::convert_rfc1766($locale), 'Language' => DBField::create_field('Varchar', strtoupper(i18n::get_lang_from_locale($locale))), 'Title' => DBField::create_field('Varchar', html_entity_decode(i18n::get_language_name(i18n::get_lang_from_locale($locale), true), ENT_NOQUOTES, 'UTF-8')), 'LinkingMode' => $currentLocale == $locale ? 'current' : 'link', 'Link' => $translation ? $translation->AbsoluteLink() : ($homeTranslated ? $homeTranslated->Link() : ''))));
     }
     Translatable::set_current_locale($currentLocale);
     i18n::set_locale($currentLocale);
     return $langSet;
 }
 /**
  * Add quantity, variation and remove fields to the
  * item set.
  *
  * @param SS_List $items
  */
 protected function editableItems()
 {
     $editables = ArrayList::create();
     foreach ($this->items as $item) {
         $buyable = $item->Product();
         if (!$buyable) {
             continue;
         }
         $name = $this->name . "[{$item->ID}]";
         $quantity = NumericField::create($name . "[Quantity]", "Quantity", $item->Quantity)->setAttribute('type', 'number')->setAttribute('min', '0');
         $variationfield = false;
         if ($buyable->has_many("Variations")) {
             $variations = $buyable->Variations();
             if ($variations->exists()) {
                 $variationfield = DropdownField::create($name . "[ProductVariationID]", _t('CartEditField.VARIATION', "Variation"), $variations->map('ID', 'Title'), $item->ProductVariationID);
             }
         }
         $remove = CheckboxField::create($name . "[Remove]", _t('CartEditField.REMOVE', "Remove"));
         $editables->push($item->customise(array("QuantityField" => $quantity, "VariationField" => $variationfield, "RemoveField" => $remove)));
     }
     if (is_callable($this->editableItemsCallback)) {
         $callback = $this->editableItemsCallback;
         $editables = $callback($editables);
     }
     return $editables;
 }
 /**
  * Returns list of categories used in GoogleBase.ss template
  * Override with getGoogleBaseCategoryList on Product defaults to getGoogleBaseCategoryList on GoogleBaseProduct
  * @return ArrayList of categories
  */
 public function getGoogleBaseCategoryList()
 {
     $list = $this->owner->GoogleBaseCategories;
     if ($list) {
         $allCategories = ArrayList::create();
         $categories = explode(' > ', $list);
         $string = '';
         $count = 0;
         $used = array();
         foreach ($categories as $k => $category) {
             if (isset($used[$category])) {
                 continue;
             }
             $used[$category] = $category;
             ++$count;
             if ($count == 1) {
                 $string = trim($category);
             } else {
                 $string .= ' > ' . trim($category);
             }
             $allCategories->push(ArrayData::create(array('Category' => $string)));
         }
         return $allCategories;
     }
     return false;
 }
 public function getPopularInteractions($interactionType, $itemClass, $days, $number = 10)
 {
     $since = date('Y-m-d H:i:s', strtotime("-{$days} days"));
     // Execute an SQL query so we can group by and count.
     $interactions = UserInteraction::get()->filter(array('Type' => $interactionType, 'ItemClass' => $itemClass, 'Created:GreaterThan' => $since));
     $interactionType = Convert::raw2sql($interactionType);
     $itemClass = Convert::raw2sql($itemClass);
     $subs = ClassInfo::subclassesFor($itemClass);
     $subs[] = $itemClass;
     if ($i = array_search('ErrorPage', $subs)) {
         unset($subs[$i]);
     }
     $in = "'" . implode("','", $subs) . "'";
     $query = new SQLQuery('*', 'UserInteraction', "Type = '{$interactionType}' AND ItemClass IN ({$in}) AND DATEDIFF(NOW(), Created) <= {$days}", 'Views DESC, Title ASC', 'Title', '', $number);
     $query->selectField('COUNT(Title)', 'Views');
     $results = $query->execute();
     $container = ArrayList::create();
     // The array list will need to be populated with objects so the template accepts it.
     for ($i = 0; $i < $results->numRecords(); $i++) {
         $object = UserInteraction::create($results->record());
         if ($object->canView()) {
             $container->add($object);
         }
     }
     return $container;
 }
 public static function getAllListsByCategory($SummitCategoryID)
 {
     $category = PresentationCategory::get()->byID($SummitCategoryID);
     // An empty array list that we'll use to return results
     $results = ArrayList::create();
     // Get any existing lists made for this category
     $AllLists = SummitSelectedPresentationList::get()->filter('CategoryID', $SummitCategoryID)->sort('ListType', 'ASC');
     // Filter to lists of any other track chairs
     $OtherTrackChairLists = $AllLists->filter('ListType', 'Individual')->exclude('MemberID', Member::currentUser()->ID);
     $MemberList = $category->MemberList(Member::currentUser()->ID);
     $GroupList = $category->GroupList();
     if ($MemberList) {
         $results->push($MemberList);
     }
     foreach ($OtherTrackChairLists as $list) {
         $results->push($list);
     }
     if ($GroupList) {
         $results->push($GroupList);
     }
     // Add each of those lists to our results
     foreach ($results as $list) {
         if ($list->ListType == "Individual") {
             $list->name = $list->Member()->FirstName . ' ' . $list->Member()->Surname;
         }
         if ($list->ListType == "Group") {
             $list->name = 'Team Selections';
         }
     }
     return $results;
 }
예제 #25
0
파일: EBSResponse.php 프로젝트: otago/ebs
 /**
  * Recursivity creates the SilverStripe dataobject representation of content
  * @param mixed $array
  * @return \DataObject|\DataList|null
  */
 private function parseobject($array)
 {
     if (is_object($array)) {
         if (get_class($array) == 'DataObject') {
             return $array;
         }
         $do = DataObject::create();
         foreach (get_object_vars($array) as $key => $obj) {
             if ($key == '__Type') {
                 $do->setField('Title', $obj);
             } else {
                 if (is_array($obj) || is_object($obj)) {
                     $do->setField($key, $this->parseobject($obj));
                 } else {
                     $do->setField($key, $obj);
                 }
             }
         }
         return $do;
     } else {
         if (is_array($array)) {
             $dataList = ArrayList::create();
             foreach ($array as $key => $obj) {
                 $dataList->push($this->parseobject($obj));
             }
             return $dataList;
         }
     }
     return null;
 }
 public function Field($properties = array())
 {
     if ($this->firstActive) {
         $this->makeFirstActive();
     }
     $properties['endCarousel'] = true;
     $properties['outerCarouselNavigation'] = true;
     $properties['carouselNavigationClasses'] = 'carousel-static';
     if (!isset($properties['startCarousel'])) {
         $properties['startCarousel'] = $this->ID();
     }
     if (!isset($properties['carouselParentAttributes'])) {
         $properties['carouselParentAttributes'] = $this->JSONAttributesHTML;
     }
     if (!isset($properties['slides'])) {
         $properties['slides'] = $this->children;
     }
     if (!isset($properties['carouselNavigation']) && $this->children && $this->children->exists()) {
         $properties['carouselName'] = $this->ID();
         $properties['carouselNavigation'] = ArrayList::create();
         foreach ($this->children as $child) {
             $properties['carouselNavigation']->push(ArrayData::create(array('carouselTitle' => $child->Title(), 'carouselActive' => $child->isActive(), 'carouselName' => $this->ID())));
         }
     }
     return parent::Field($properties);
 }
 public function getOptions()
 {
     $options = ArrayList::create();
     foreach ($this->optionsList as $val => $label) {
         $options->push(ArrayData::create(array('Label' => $label, 'Value' => $val, 'Selected' => $this->Value() == $val)));
     }
     return $options;
 }
 /** 
  * Action to emulate a specific user
  * @param $request = HTTPRequest
  * @return redirect
  **/
 public function emulateuser($request)
 {
     Requirements::clear();
     Requirements::css(DEVTOOLS_DIR . '/css/dev-tools.css');
     // not enabled, or not allowed >> get out
     if (!$this->CanEmulateUser()) {
         echo 'You cannot do that';
         die;
     }
     // get URL parameters
     $params = $this->owner->getRequest()->params();
     // URL attribute?
     if (!isset($params['ID'])) {
         $members = Member::get();
         $membersList = array();
         foreach ($members as $member) {
             $membersList[$member->ID] = $member;
         }
         $membersList = ArrayList::create($membersList);
         $membersList = PaginatedList::create($membersList, $this->owner->getRequest());
         $membersList->setPageLength(20);
         return $this->owner->customise(array('Users' => $membersList))->renderWith('EmulateUserPage');
     }
     $member = Member::get()->byID($params['ID']);
     if (!isset($member->ID)) {
         echo 'Could not find user by #' . $params['ID'];
         die;
     }
     $member->logIn();
     return $this->owner->redirect($this->owner->Link());
 }
 /**
  * Get a paginated list of products
  *
  * @return PaginatedList
  */
 public function PaginatedAllProducts($limit = 10)
 {
     if ($this->dataRecord instanceof ProductCategory) {
         return PaginatedList::create($this->AllProducts(), $this->request)->setPageLength($limit);
     } else {
         return ArrayList::create();
     }
 }
예제 #30
-2
 public function index(SS_HTTPRequest $request)
 {
     $properties = Property::get();
     $filters = ArrayList::create();
     if ($search = $request->getVar('Keywords')) {
         $filters->push(ArrayData::create(array('Label' => "Keywords: '{$search}'", 'RemoveLink' => HTTP::setGetVar('Keywords', null))));
         $properties = $properties->filter(array('Title:PartialMatch' => $search));
     }
     if ($arrival = $request->getVar('ArrivalDate')) {
         $arrivalStamp = strtotime($arrival);
         $nightAdder = '+' . $request->getVar('Nights') . ' days';
         $startDate = date('Y-m-d', $arrivalStamp);
         $endDate = date('Y-m-d', strtotime($nightAdder, $arrivalStamp));
         $properties = $properties->filter(array('AvailableStart:GreaterThanOrEqual' => $startDate, 'AvailableEnd:LessThanOrEqual' => $endDate));
     }
     if ($bedrooms = $request->getVar('Bedrooms')) {
         $filters->push(ArrayData::create(array('Label' => "{$bedrooms} bedrooms", 'RemoveLink' => HTTP::setGetVar('Bedrooms', null))));
         $properties = $properties->filter(array('Bedrooms:GreaterThanOrEqual' => $bedrooms));
     }
     if ($bathrooms = $request->getVar('Bathrooms')) {
         $filters->push(ArrayData::create(array('Label' => "{$bathrooms} bathrooms", 'RemoveLink' => HTTP::setGetVar('Bathrooms', null))));
         $properties = $properties->filter(array('Bathrooms:GreaterThanOrEqual' => $bathrooms));
     }
     if ($minPrice = $request->getVar('MinPrice')) {
         $filters->push(ArrayData::create(array('Label' => "Min. \${$minPrice}", 'RemoveLink' => HTTP::setGetVar('MinPrice', null))));
         $properties = $properties->filter(array('PricePerNight:GreaterThanOrEqual' => $minPrice));
     }
     if ($maxPrice = $request->getVar('MaxPrice')) {
         $filters->push(ArrayData::create(array('Label' => "Max. \${$maxPrice}", 'RemoveLink' => HTTP::setGetVar('MaxPrice', null))));
         $properties = $properties->filter(array('PricePerNight:LessThanOrEqual' => $maxPrice));
     }
     $paginatedProperties = PaginatedList::create($properties, $request)->setPageLength(15)->setPaginationGetVar('s');
     return array('Results' => $paginatedProperties, 'ActiveFilters' => $filters);
 }