/**
  * Remember the classname and the ID for the given $dbField
  * @param DBField $dbField
  * @param $value
  * @param null $record
  */
 public static function setValue(DBField $dbField, $value, $record = null)
 {
     $canEdit = Controller::curr() instanceof Page_Controller && Controller::curr()->data()->canEdit();
     if (!$canEdit) {
         $canEdit = is_object($record) && in_array(get_class($record), self::$EditableClasses) && method_exists($record, 'canEdit') && $record->canEdit();
     }
     if ($canEdit && $record && is_object($record) && $dbField->getName()) {
         $dbField->makeEditable = true;
         $dbField->editClassName = $record->ClassName;
         $dbField->editID = $record->ID;
     }
 }
 public function getEventsAction(SS_HTTPRequest $request)
 {
     // Search date
     $date = DBField::create_field("SS_Datetime", $request->param("SearchDate"));
     if (!$date->getValue()) {
         $date = SS_Datetime::now();
     }
     // Get event data
     $cache = SS_Cache::factory(self::EVENTS_CACHE_NAME);
     $cacheKey = $date->Format('Y_m_d');
     if ($result = $cache->load($cacheKey)) {
         $data = unserialize($result);
     } else {
         $data = EventsDataUtil::get_events_data_for_day($date);
         $cache->save(serialize($data), $cacheKey);
     }
     // Get init data
     if ($request->param("GetAppConfig")) {
         $cache = SS_Cache::factory(self::CONFIG_CACHE_NAME);
         $cacheKey = 'APP_CONFIG';
         if ($result = $cache->load($cacheKey)) {
             $configData = unserialize($result);
         } else {
             $configData = AppConfigDataUtil::get_config_data();
             $cache->save(serialize($configData), $cacheKey);
         }
         $data['appConfig'] = $configData;
     }
     return $this->sendResponse($data);
 }
 public function GlobalNav()
 {
     Requirements::css(Controller::join_links(GlobalNavSiteTreeExtension::get_toolbar_hostname(), Config::inst()->get('GlobalNav', 'css_path')));
     $html = DBField::create_field('HTMLText', $this->globalNav);
     $html->setOptions(array('shortcodes' => false));
     return $html;
 }
 /** 
  * @return HTMLText
  */
 public function getPostContent($post)
 {
     $text = isset($post->text) ? $post->text : '';
     $text = preg_replace('/(https?:\\/\\/[a-z0-9\\.\\/]+)/i', '<a href="$1" target="_blank">$1</a>', $text);
     $result = DBField::create_field('HTMLText', $text);
     return $result;
 }
 /**
  * Create a new Decimal field.
  */
 function __construct($name, $wholeSize = 9, $decimalSize = 2, $defaultValue = 0)
 {
     $this->wholeSize = isset($wholeSize) ? $wholeSize : 9;
     $this->decimalSize = isset($decimalSize) ? $decimalSize : 2;
     $this->defaultValue = $defaultValue;
     parent::__construct($name);
 }
 /**
  * Parses the snippet short code
  * @example [snippet id=123]
  * @example [snippet id=123 version=456]
  */
 public static function parse($arguments, $content = null, $parser = null)
 {
     //Ensure ID is pressent in the arguments
     if (!array_key_exists('id', $arguments)) {
         return '<p><b><i>' . _t('CodeBankShortCode.MISSING_ID_ATTRIBUTE', '_Short Code missing the id attribute') . '</i></b></p>';
     }
     //Fetch Snippet
     $snippet = Snippet::get()->byID(intval($arguments['id']));
     if (empty($snippet) || $snippet === false || $snippet->ID == 0) {
         return '<p><b><i>' . _t('CodeBankShortCode.SNIPPET_NOT_FOUND', '_Snippet not found') . '</i></b></p>';
     }
     //Fetch Text
     $snippetText = $snippet->SnippetText;
     //If the version exists fetch it, and replace the text with that of the version
     if (array_key_exists('version', $arguments)) {
         $version = $snippet->Version(intval($arguments['version']));
         if (empty($version) || $version === false || $version->ID == 0) {
             $snippetText = $version->Text;
         }
     }
     //Load CSS Requirements
     Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shCore.css');
     Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shCoreDefault.css');
     Requirements::css(CB_DIR . '/javascript/external/syntaxhighlighter/themes/shThemeDefault.css');
     //Load JS Requirements
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     Requirements::javascript(CB_DIR . '/javascript/external/syntaxhighlighter/brushes/shCore.js');
     Requirements::javascript(CB_DIR . '/javascript/external/syntaxhighlighter/brushes/' . self::getBrushName($snippet->Language()->HighlightCode) . '.js');
     Requirements::javascriptTemplate(CB_DIR . '/javascript/CodeBankShortCode.template.js', array('ID' => $snippet->ID), 'snippet-highlightinit-' . $snippet->ID);
     //Render the snippet
     $obj = new ViewableData();
     return $obj->renderWith('CodeBankShortCode', array('ID' => $snippet->ID, 'Title' => $snippet->getField('Title'), 'Description' => $snippet->getField('Description'), 'SnippetText' => DBField::create_field('Text', $snippetText), 'HighlightCode' => strtolower($snippet->Language()->HighlightCode)));
 }
 /**
  * Test import with manual column mapping and custom column names
  */
 function testLoadWithCustomHeaderAndRelation()
 {
     $loader = new CsvBulkLoader('CsvBulkLoaderTest_Player');
     $filepath = Director::baseFolder() . '/sapphire/tests/dev/CsvBulkLoaderTest_PlayersWithCustomHeaderAndRelation.csv';
     $file = fopen($filepath, 'r');
     $compareCount = $this->getLineCount($file);
     fgetcsv($file);
     // pop header row
     $compareRow = fgetcsv($file);
     $loader->columnMap = array('first name' => 'FirstName', 'bio' => 'Biography', 'bday' => 'Birthday', 'teamtitle' => 'Team.Title', 'teamsize' => 'Team.TeamSize', 'salary' => 'Contract.Amount');
     $loader->hasHeaderRow = true;
     $loader->relationCallbacks = array('Team.Title' => array('relationname' => 'Team', 'callback' => 'getTeamByTitle'));
     $results = $loader->load($filepath);
     // Test that right amount of columns was imported
     $this->assertEquals(1, $results->Count(), 'Test correct count of imported data');
     // Test of augumenting existing relation (created by fixture)
     $testTeam = DataObject::get_one('CsvBulkLoaderTest_Team', null, null, 'Created DESC');
     $this->assertEquals('20', $testTeam->TeamSize, 'Augumenting existing has_one relation works');
     // Test of creating relation
     $testContract = DataObject::get_one('CsvBulkLoaderTest_PlayerContract');
     $testPlayer = Dataobject::get_one("CsvBulkLoaderTest_Player", "FirstName = 'John'");
     $this->assertEquals($testPlayer->ContractID, $testContract->ID, 'Creating new has_one relation works');
     // Test nested setting of relation properties
     $contractAmount = DBField::create('Currency', $compareRow[5])->RAW();
     $this->assertEquals($testPlayer->Contract()->Amount, $contractAmount, 'Setting nested values in a relation works');
     fclose($file);
 }
 protected function handlePost(array $data, $settings = [])
 {
     $post = ['ID' => isset($data['id']) && isset($data['id']['videoId']) ? $data['id']['videoId'] : '0', 'Author' => isset($data['snippet']) && isset($data['snippet']['channelTitle']) ? \FormField::name_to_label($data['snippet']['channelTitle']) : '', 'AuthorID' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? $data['snippet']['channelId'] : 0, 'AuthorURL' => isset($data['snippet']) && isset($data['snippet']['channelId']) ? \Controller::join_links($this->url, 'channel', $data['snippet']['channelId']) : '', 'Title' => isset($data['snippet']) && isset($data['snippet']['title']) ? $data['snippet']['title'] : '', 'Content' => isset($data['snippet']) && isset($data['snippet']['description']) ? $this->textParser()->text($data['snippet']['description']) : '', 'Priority' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? strtotime($data['snippet']['publishedAt']) : 0, 'Posted' => isset($data['snippet']) && isset($data['snippet']['publishedAt']) ? \DBField::create_field('SS_Datetime', strtotime($data['snippet']['publishedAt'])) : null];
     if (isset($data['snippet']) && isset($data['snippet']['thumbnails'])) {
         if (isset($data['snippet']['thumbnails']['high']) && isset($data['snippet']['thumbnails']['high']['url'])) {
             $post['Cover'] = $data['snippet']['thumbnails']['high']['url'];
         } else {
             if (isset($data['snippet']['thumbnails']['medium']) && isset($data['snippet']['thumbnails']['medium']['url'])) {
                 $post['Cover'] = $data['snippet']['thumbnails']['medium']['url'];
             } else {
                 if (isset($data['snippet']['thumbnails']['default']) && isset($data['snippet']['thumbnails']['default']['url'])) {
                     $post['Cover'] = $data['snippet']['thumbnails']['default']['url'];
                 }
             }
         }
     }
     if ($post['ID']) {
         $params = (array) singleton('env')->get('Youtube.video_params');
         if (isset($settings['videoParams'])) {
             $params = array_merge($params, (array) $settings['videoParams']);
         }
         $params['v'] = $post['ID'];
         $post['Link'] = \Controller::join_links($this->url, 'watch', '?' . http_build_query($params));
         $this->setFromEmbed($post);
     }
     if (isset($post['ObjectDescription']) && $post['ObjectDescription'] == $post['Content']) {
         unset($post['ObjectDescription']);
     }
     if (isset($post['Description']) && $post['Description'] == $post['Content']) {
         unset($post['Description']);
     }
     return $post;
 }
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     $sqlResults = DB::query("\n\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     if ($this->ShowLastYears == 0) {
         $cutOffYear = 0;
     } else {
         $cutOffYear = (int) date("Y") - $this->ShowLastYears;
     }
     $years = array();
     if (Director::get_current_page()->ClassName == 'BlogHolder') {
         $urlParams = Director::urlParams();
         $yearParam = $urlParams['ID'];
         $monthParam = $urlParams['OtherID'];
     } else {
         $date = new DateTime(Director::get_current_page()->Date);
         $yearParam = $date->format("Y");
         $monthParam = $date->format("m");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = true;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $isMonthDisplay = $year > $cutOffYear;
             // $dateFormat = 'Month'; else $dateFormat = 'Year';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             if ($isMonthDisplay || !$isMonthDisplay && !in_array($year, $years)) {
                 $years[] = $year;
                 $current = false;
                 $children = new DataObjectSet();
                 $LinkingMode = "link";
                 if ($isMonthDisplay && $yearParam == $year && $monthParam == $month || !$isMonthDisplay && $yearParam == $year) {
                     $LinkingMode = "current";
                     $current = true;
                     if ($this->ShowChildren && $isMonthDisplay) {
                         $filter = $yearclause . ' = ' . $year . ' AND ' . $monthclause . ' = ' . $month;
                         $children = DataObject::get('BlogEntry', $filter, "Date DESC");
                     }
                 }
                 $results->push(new ArrayData(array('Date' => $date, 'Year' => $year, 'Link' => $link, 'NoMonth' => !$isMonthDisplay, 'LinkingMode' => $LinkingMode, 'Children' => $children)));
                 unset($children);
             }
         }
     }
     return $results;
 }
    public function Field($properties = array())
    {
        $content = '';
        Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
        Requirements::javascript(FRAMEWORK_DIR . "/javascript/ToggleField.js");
        if ($this->startClosed) {
            $this->addExtraClass('startClosed');
        }
        $valforInput = $this->value ? Convert::raw2att($this->value) : "";
        $rawInput = Convert::html2raw($valforInput);
        if ($this->charNum) {
            $reducedVal = substr($rawInput, 0, $this->charNum);
        } else {
            $reducedVal = DBField::create_field('Text', $rawInput)->{$this->truncateMethod}();
        }
        // only create togglefield if the truncated content is shorter
        if (strlen($reducedVal) < strlen($rawInput)) {
            $content = <<<HTML
\t\t\t<div class="readonly typography contentLess" style="display: none">
\t\t\t\t{$reducedVal}
\t\t\t\t&nbsp;<a href="#" class="triggerMore">{$this->labelMore}</a>
\t\t\t</div>
\t\t\t<div class="readonly typography contentMore">
\t\t\t\t{$this->value}
\t\t\t\t&nbsp;<a href="#" class="triggerLess">{$this->labelLess}</a>
\t\t\t</div>\t
\t\t\t<br />
\t\t\t<input type="hidden" name="{$this->name}" value="{$valforInput}" />
HTML;
        } else {
            $this->dontEscape = true;
            $content = parent::Field();
        }
        return $content;
    }
 public function Tweets()
 {
     $twitterApp = TwitterApp::get()->first();
     if (!$twitterApp) {
         return null;
     }
     $siteConfig = SiteConfig::current_site_config();
     $twitter = $twitterApp->getTwitter();
     $twitter->setAccess(new OAuthToken($twitterApp->TwitterAccessToken, $twitterApp->TwitterAccessSecret));
     if ($twitter->hasAccess()) {
         $result = $twitter->api("1.1/statuses/user_timeline.json", "GET", array("screen_name" => $this->TwitterHandle, "count" => $this->NumberOfTweets));
         if ($result->statusCode() == 200) {
             $rawTweets = json_decode($result->body(), true);
             if (count($rawTweets) > 0) {
                 $tweets = new ArrayList();
                 foreach ($rawTweets as $tweet) {
                     // Parse tweet links, users and hashtags.
                     $parsed = preg_replace("#(^|[\n ])([\\w]+?://[\\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" target=\"_blank\">\\2</a>'", $tweet['text']);
                     $parsed = preg_replace("#(^|[\n ])@([A-Za-z0-9\\_]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" target=\"_blank\">@\\2</a>'", $parsed);
                     $parsed = preg_replace("#(^|[\n ])\\#([A-Za-z0-9]*)#ise", "'\\1<a href=\"http://www.twitter.com/search?q=\\2\" target=\"_blank\">#\\2</a>'", $parsed);
                     $t = new ArrayData(array());
                     $t->Tweet = DBField::create_field("HTMLText", $parsed, "Tweet");
                     $t->TweetDate = DBField::create_field("SS_Datetime", strtotime($tweet['created_at']));
                     $t->TweetLink = DBField::create_field("Varchar", "http://www.twitter.com/" . rawurlencode($tweet['user']['screen_name']) . "/status/" . rawurlencode($tweet['id_str']));
                     $tweets->push($t);
                 }
                 return $tweets;
             }
         }
     }
     return null;
 }
 /**
  * 
  * @param SQLQuery $query
  */
 function addToQuery(&$query)
 {
     parent::addToQuery($query);
     $query->selectField("AsText({$this->name})", "{$this->name}");
     // $query->addSelect("AsText({$this->name}) AS {$this->name}_AsText");
     // $query->select[] = "AsText({$this->name}) AS {$this->name}_AsText";
 }
 function Form()
 {
     $fields = new FieldSet();
     $source = array();
     $fields->push(new HeaderField('Header', _t('RemoveOrphanedPagesTask.HEADER', 'Remove all orphaned pages task')));
     $fields->push(new LiteralField('Description', $this->description));
     $orphans = $this->getOrphanedPages($this->orphanedSearchClass);
     if ($orphans) {
         foreach ($orphans as $orphan) {
             $latestVersion = Versioned::get_latest_version($this->orphanedSearchClass, $orphan->ID);
             $latestAuthor = DataObject::get_by_id('Member', $latestVersion->AuthorID);
             $stageRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Stage', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
             $liveRecord = Versioned::get_one_by_stage($this->orphanedSearchClass, 'Live', sprintf("\"%s\".\"ID\" = %d", ClassInfo::baseDataClass($this->orphanedSearchClass), $orphan->ID));
             $label = sprintf('<a href="admin/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>', $orphan->ID, $orphan->Title, $orphan->ID, DBField::create('Date', $orphan->LastEdited)->Nice(), $latestAuthor ? $latestAuthor->Title : 'unknown', $liveRecord ? 'is published' : 'not published');
             $source[$orphan->ID] = $label;
         }
     }
     if ($orphans && $orphans->Count()) {
         $fields->push(new CheckboxSetField('OrphanIDs', false, $source));
         $fields->push(new LiteralField('SelectAllLiteral', sprintf('<p><a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'checked\'); return false;">%s</a>&nbsp;', _t('RemoveOrphanedPagesTask.SELECTALL', 'select all'))));
         $fields->push(new LiteralField('UnselectAllLiteral', sprintf('<a href="#" onclick="javascript:jQuery(\'#Form_Form_OrphanIDs :checkbox\').attr(\'checked\', \'\'); return false;">%s</a></p>', _t('RemoveOrphanedPagesTask.UNSELECTALL', 'unselect all'))));
         $fields->push(new OptionSetField('OrphanOperation', _t('RemoveOrphanedPagesTask.CHOOSEOPERATION', 'Choose operation:'), array('rebase' => _t('RemoveOrphanedPagesTask.OPERATION_REBASE', sprintf('Rebase selected to a new holder page "%s" and unpublish. None of these pages will show up for website visitors.', $this->rebaseHolderTitle())), 'remove' => _t('RemoveOrphanedPagesTask.OPERATION_REMOVE', 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)')), 'rebase'));
         $fields->push(new LiteralField('Warning', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.DELETEWARNING', 'Warning: These operations are not reversible. Please handle with care.'))));
     } else {
         $fields->push(new LiteralField('NotFoundLabel', sprintf('<p class="message">%s</p>', _t('RemoveOrphanedPagesTask.NONEFOUND', 'No orphans found'))));
     }
     $form = new Form($this, 'Form', $fields, new FieldSet(new FormAction('doSubmit', _t('RemoveOrphanedPagesTask.BUTTONRUN', 'Run'))));
     if (!$orphans || !$orphans->Count()) {
         $form->makeReadonly();
     }
     return $form;
 }
 public function testToDialect()
 {
     $expression = Expression::containsIp(IpRange::create('127.0.0.1-127.0.0.5'), IpAddress::create('127.0.0.3'));
     $this->assertEquals("'127.0.0.3' <<= '127.0.0.1-127.0.0.5'", $expression->toDialectString(PostgresDialect::me()));
     $expression = Expression::containsIp(DBField::create('range'), '192.168.1.1');
     $this->assertEquals('\'192.168.1.1\' <<= "range"', $expression->toDialectString(PostgresDialect::me()));
 }
Exemple #15
0
 public function testNice()
 {
     $time = DBField::create_field('Time', '17:15:55');
     $this->assertEquals('5:15pm', $time->Nice());
     Config::inst()->update('Time', 'nice_format', 'H:i:s');
     $this->assertEquals('17:15:55', $time->Nice());
 }
 function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if (!$this->DispatchedOn) {
         $this->DispatchedOn = DBField::create_field('Date', date('Y-m-d'));
     }
 }
 protected function renderRows($rows, ArrayIterator $splitcontent, &$pos = -1)
 {
     $output = "";
     $rownumber = 0;
     foreach ($rows as $row) {
         if ($row->cols) {
             $columns = array();
             foreach ($row->cols as $col) {
                 $nextcontent = $splitcontent->current();
                 $isholder = !isset($col->rows);
                 if ($isholder) {
                     $splitcontent->next();
                     //advance iterator if there are no sub-rows
                     $pos++;
                     //wrap split content in a HTMLText object
                     $dbObject = DBField::create_field('HTMLText', $nextcontent, "Content");
                     $dbObject->setOptions(array("shortcodes" => true));
                     $nextcontent = $dbObject;
                 }
                 $width = $col->width ? (int) $col->width : 1;
                 //width is at least 1
                 $columns[] = new ArrayData(array("Width" => $width, "EnglishWidth" => $this->englishWidth($width), "Content" => $isholder ? $nextcontent : $this->renderRows($col->rows, $splitcontent, $pos), "IsHolder" => $isholder, "GridPos" => $pos, "ExtraClasses" => isset($col->extraclasses) ? $col->extraclasses : null));
             }
             $output .= ArrayData::create(array("Columns" => new ArrayList($columns), "RowNumber" => (string) $rownumber++, "ExtraClasses" => isset($row->extraclasses) ? $row->extraclasses : null))->renderWith($this->template);
         } else {
             //every row should have columns!!
         }
     }
     return $output;
 }
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     if ($this->DisplayMode == 'month') {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     } else {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT {$yearclause} AS \"Year\" \n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = $this->DisplayMode == 'month';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             $results->push(new ArrayData(array('Date' => $date, 'Link' => $link)));
         }
     }
     return $results;
 }
 /**
  * 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;
 }
 /**
  * Create a new Decimal field.
  *
  * @param string $name
  * @param int $wholeSize
  * @param int $decimalSize
  * @param float $defaultValue
  */
 public function __construct($name = null, $wholeSize = 9, $decimalSize = 2, $defaultValue = 0)
 {
     $this->wholeSize = is_int($wholeSize) ? $wholeSize : 9;
     $this->decimalSize = is_int($decimalSize) ? $decimalSize : 2;
     $this->defaultValue = number_format((double) $defaultValue, $decimalSize);
     parent::__construct($name);
 }
 /**
  * @param   $key The nav key, e.g. "doc", "userhelp"
  * @return HTMLText
  */
 public static function GlobalNav($key)
 {
     $baseURL = GlobalNavSiteTreeExtension::get_toolbar_baseurl();
     Requirements::css(Controller::join_links($baseURL, Config::inst()->get('GlobalNav', 'css_path')));
     // If this method haven't been called before, get the toolbar and cache it
     if (self::$global_nav_html === null) {
         // Set the default to empty
         self::$global_nav_html = '';
         // Prevent recursion from happening
         if (empty($_GET['globaltoolbar'])) {
             $host = GlobalNavSiteTreeExtension::get_toolbar_hostname();
             $path = Director::makeRelative(GlobalNavSiteTreeExtension::get_navbar_filename($key));
             if (Config::inst()->get('GlobalNav', 'use_localhost')) {
                 self::$global_nav_html = file_get_contents(BASE_PATH . $path);
             } else {
                 $url = Controller::join_links($baseURL, $path, '?globaltoolbar=true');
                 $connectionTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'connection_timeout');
                 $transferTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'transfer_timeout');
                 // Get the HTML and cache it
                 self::$global_nav_html = self::curl_call($url, $connectionTimeout, $transferTimeout);
             }
         }
     }
     $html = DBField::create_field('HTMLText', self::$global_nav_html);
     $html->setOptions(array('shortcodes' => false));
     return $html;
 }
 /**
  * (non-PHPdoc)
  * @see core/model/fieldtypes/DBField#prepValueForDB($value)
  */
 function prepValueForDB($value)
 {
     if (!$this->nullifyEmpty && $value === '') {
         return DB::getConn()->prepStringForDB($value);
     } else {
         return parent::prepValueForDB($value);
     }
 }
 /**
  * Initialise the controller
  */
 function init()
 {
     Requirements::themedCSS('Forum');
     $member = $this->Member() ? $this->Member() : null;
     $nicknameText = $member ? $member->Nickname . '\'s ' : '';
     $this->Title = DBField::create('HTMLText', Convert::raw2xml($nicknameText) . _t('ForumMemberProfile.USERPROFILE', 'User Profile'));
     parent::init();
 }
 public function addToQuery(&$query)
 {
     parent::addToQuery($query);
     $query->selectField(sprintf('"%sPostcode"', $this->name));
     $query->selectField(sprintf('"%sCountry"', $this->name));
     $query->selectField(sprintf('"%sLatitude"', $this->name));
     $query->selectField(sprintf('"%sLongditude"', $this->name));
 }
 /**
  * @return SS_Datetime
  */
 public function ConfirmTimeLimit()
 {
     $unconfirmed = $this->Status == 'Unconfirmed';
     $limit = $this->Time()->Event()->ConfirmTimeLimit;
     if ($unconfirmed && $limit) {
         return DBField::create_field('SS_Datetime', strtotime($this->Created) + $limit);
     }
 }
 /**
  * @return string Date time string of next run for this task
  */
 public function getNextRun()
 {
     if (!$this->isEnabled()) {
         return '';
     }
     $cron = CronExpression::factory($this->ScheduleString);
     return DBField::create_field('SS_Datetime', $cron->getNextRunDate()->Format('U'))->getValue();
 }
 /**
  * @return JoinCapableQuery
  **/
 public function process(Criteria $criteria, JoinCapableQuery $query)
 {
     $dao = call_user_func(array($this->className, 'dao'));
     foreach ($dao->getFields() as $field) {
         $this->subProcess($query, DBField::create($field, $dao->getTable()));
     }
     return $query;
 }
 public function testToDialect()
 {
     $dialect = $this->getDbByType('PgSQL')->getDialect();
     $expression = Expression::containsIp(IpRange::create('127.0.0.1-127.0.0.5'), IpAddress::create('127.0.0.3'));
     $this->assertEquals("'127.0.0.3' <<= '127.0.0.1-127.0.0.5'", $expression->toDialectString($dialect));
     $expression = Expression::containsIp(DBField::create('range'), '192.168.1.1');
     $this->assertEquals('\'192.168.1.1\' <<= "range"', $expression->toDialectString($dialect));
 }
 public function writeToManipulation(&$manipulation)
 {
     // Write ID, checking that the value is valid
     $manipulation['fields'][$this->name . 'ID'] = $this->exists() ? $this->prepValueForDB($this->getIDValue()) : $this->nullValue();
     // Write class
     $classObject = DBField::create_field('Enum', $this->getClassValue(), $this->name . 'Class');
     $classObject->writeToManipulation($manipulation);
 }
 function updateForAjax(array &$js)
 {
     $total = DBField::create('EcommerceCurrency', $this->Total())->Nice();
     $js[] = array('id' => $this->TableTotalID(), 'parameter' => 'innerHTML', 'value' => $total);
     $js[] = array('id' => $this->CartTotalID(), 'parameter' => 'innerHTML', 'value' => $total);
     $js[] = array('id' => $this->CartQuantityID(), 'parameter' => 'innerHTML', 'value' => $this->Quantity);
     $js[] = array('name' => $this->QuantityFieldName(), 'parameter' => 'value', 'value' => $this->Quantity);
 }