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 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())); }
/** * 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); }
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; }
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> ', _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; }
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); }
/** * 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 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)); }
/** * @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; }
/** * @return SS_Datetime */ public function ConfirmTimeLimit() { $unconfirmed = $this->Status == 'Unconfirmed'; $limit = $this->Time()->Event()->ConfirmTimeLimit; if ($unconfirmed && $limit) { return DBField::create('SS_Datetime', strtotime($this->Created) + $limit); } }
function testLongDate() { $this->assertEquals('1 April 2008', DBField::create('Date', 1206968400)->Long(), "Date->Long() works with numeric timestamp"); $this->assertEquals('1 April 2008', DBField::create('Date', '1206968400')->Long(), "Date->Long() works with string timestamp"); $this->assertEquals('31 March 2008', DBField::create('Date', 1206882000)->Long(), "Date->Long() works with numeric timestamp"); $this->assertEquals('31 March 2008', DBField::create('Date', '1206882000')->Long(), "Date->Long() works with numeric timestamp"); $this->assertEquals('3 April 2003', DBField::create('Date', '2003-4-3')->Long(), "Date->Long() works with YYYY-M-D"); $this->assertEquals('3 April 2003', DBField::create('Date', '3/4/2003')->Long(), "Date->Long() works with D/M/YYYY"); }
/** * SaveInto checks if set-methods are available and use them instead of setting the values directly. saveInto * initiates a new LinkField class object to pass through the values to the setter method. */ public function saveInto(DataObjectInterface $dataObject) { $fieldName = $this->name; if ($dataObject->hasMethod("set{$fieldName}")) { $dataObject->{$fieldName} = DBField::create('LinkField', array("PageID" => $this->fieldPageID->Value(), "CustomURL" => $this->fieldCustomURL->Value())); } else { $dataObject->{$fieldName}->setPageID($this->fieldPageID->Value()); $dataObject->{$fieldName}->setCustomURL($this->fieldCustomURL->Value()); } }
/** * SaveInto checks if set-methods are available and use them instead of setting the values directly. saveInto * initiates a new LinkField class object to pass through the values to the setter method. */ function saveInto(DataObjectInterface $dataObject) { $fieldName = $this->name; if ($dataObject->hasMethod("set{$fieldName}")) { $dataObject->{$fieldName} = DBField::create('AlternativeField', array("SelectedValue" => $this->fieldSelectedValue->Value(), "AlternativeValue" => $this->fieldAlternativeValue->Value())); } else { $dataObject->{$fieldName}->setSelectedValue($this->fieldSelectedValue->Value()); $dataObject->{$fieldName}->setAlternativeValue($this->fieldAlternativeValue->Value()); } }
/** * @return SS_Datetime */ public function getExpiryDateTime() { if ($this->getSession()->RegistrationID) { $created = strtotime($this->getSession()->Registration()->Created); $limit = $this->controller->getDateTime()->Event()->RegistrationTimeLimit; if ($limit) { return DBField::create('SS_Datetime', $created + $limit); } } }
/** * 30/06/2009 - Enhancement: * SaveInto checks if set-methods are available and use them * instead of setting the values in the money class directly. saveInto * initiates a new Money class object to pass through the values to the setter * method. * * (see @link MoneyFieldTest_CustomSetter_Object for more information) */ function saveInto($dataObject) { $fieldName = $this->name; if ($dataObject->hasMethod("set{$fieldName}")) { $dataObject->{$fieldName} = DBField::create('Money', array("Currency" => $this->fieldCurrency->Value(), "Amount" => $this->fieldAmount->Value())); } else { $dataObject->{$fieldName}->setCurrency($this->fieldCurrency->Value()); $dataObject->{$fieldName}->setAmount($this->fieldAmount->Value()); } }
/** * @return SelectQuery **/ public function makeCountQuery() { $query = $this->makeFetchQuery(); if ($query->isDistinct()) { $countFunction = SQLFunction::create('count', DBField::create($this->container->getDao()->getIdName(), $this->container->getDao()->getTable()))->setAggregateDistinct(); $query->unDistinct(); } else { $countFunction = SQLFunction::create('count', DBValue::create('*')); } return $query->dropFields()->dropOrder()->dropLimit()->get($countFunction->setAlias('count')); }
function testContextSummary() { $testString1 = '<p>This is some text. It is a test</p>'; $testKeywords1 = 'test'; $testString2 = '<p>This is some test text. Test test what if you have multiple keywords.</p>'; $testKeywords2 = 'some test'; $textObj = DBField::create('Text', $testString1, 'Text'); $this->assertEquals('text. It is a <span class="highlight">test</span>', $textObj->ContextSummary(20, $testKeywords1)); $textObj->setValue($testString2); $this->assertEquals('This is <span class="highlight">some</span> <span class="highlight">test</span> text. <span class="highlight">test</span> <span class="highlight">test</span> what if you have', $textObj->ContextSummary(50, $testKeywords2)); }
function writeToManipulation(&$manipulation) { if ($this->getCurrency()) { $manipulation['fields'][$this->name . 'Currency'] = $this->prepValueForDB($this->getCurrency()); } else { $manipulation['fields'][$this->name . 'Currency'] = DBField::create('Varchar', $this->getCurrency())->nullValue(); } if ($this->getAmount()) { $manipulation['fields'][$this->name . 'Amount'] = $this->getAmount(); } else { $manipulation['fields'][$this->name . 'Amount'] = DBField::create('Decimal', $this->getAmount())->nullValue(); } }
function writeToManipulation(&$manipulation) { if ($this->getBuyableClassName()) { $manipulation['fields']['BuyableClassName'] = $this->prepValueForDB($this->getBuyableClassName()); } else { $manipulation['fields']['BuyableClassName'] = DBField::create('Varchar', $this->getBuyableClassName())->nullValue(); } if ($this->getBuyableID()) { $manipulation['fields']['BuyableID'] = $this->getBuyableID(); } else { $manipulation['fields']['BuyableID'] = DBField::create('Decimal', $this->getBuyableID())->nullValue(); } }
public function toSelectQuery() { if (!$this->range || !$this->interval) { throw new WrongStateException('define time range and interval units first'); } if (!$this->range->getStart() || !$this->range->getEnd()) { throw new WrongArgumentException('cannot operate with unlimited range'); } $firstIntervalStart = $this->interval->truncate($this->range->getStart(), !$this->overlapped); $maxIntervals = $this->interval->countInRange($this->range, $this->overlapped) - 1; $generator = $this->getSeriesGenerator(0, $maxIntervals); $result = OSQL::select()->from($generator, self::ITERATOR_ALIAS)->get(Expression::add(DBValue::create($firstIntervalStart->toString())->castTo(DataType::create(DataType::TIMESTAMP)->getName()), Expression::mul(DBValue::create("1 {$this->interval->getName()}")->castTo(DataType::create(DataType::INTERVAL)->getName()), DBField::create(self::ITERATOR_ALIAS))), $this->field); return $result; }
public function onBeforeSend() { $email = $this->owner; $letter = $email->Newsletter(); $body = new SS_HTMLValue($email->Body()->forTemplate()); $links = array(); $member = null; if (!$body || !$letter) { return; } if ($email->To()) { $member = DataObject::get_one('Member', sprintf('"Email" = \'%s\'', Convert::raw2sql($email->To()))); } // First build up a set of all the unique links within the newsletter, // along with the elements that link to them. foreach ($body->getElementsByTagName('a') as $link) { $href = $link->getAttribute('href'); if (strpos($href, '{$') !== false || strpos($href, 'mailto:') !== false) { // ignore links with keywords continue; } if (array_key_exists($href, $links)) { $links[$href][] = $link; } else { $links[$href] = array($link); } } // Then actually do the processing. Create a unique tracking object for // each link. Attempt to embed a member-specific tracking token if // the newsletter is being sent to a member. foreach ($links as $href => $elements) { $track = DataObject::get_one('Newsletter_TrackedLink', sprintf('"NewsletterID" = %d AND "Original" = \'%s\'', $letter->ID, Convert::raw2sql($href))); if (!$track) { $track = new Newsletter_TrackedLink(); $track->Original = $href; $track->NewsletterID = $letter->ID; $track->write(); } if ($member) { $trackHref = Controller::join_links(Director::baseURL(), 'newsletter-link', $member->NewsletterTrackingToken, $track->Hash); } else { $trackHref = Controller::join_links(Director::baseURL(), 'newsletter-link', $track->Hash); } foreach ($elements as $element) { $element->setAttribute('href', $trackHref); } } $dom = $body->getDocument(); $email->setBody(DBField::create('HTMLText', $dom->saveHTML())); }
function testNowWithMockDate() { // Test setting $mockDate = '2001-12-31 22:10:59'; SS_Datetime::set_mock_now($mockDate); $systemDatetime = DBField::create('SS_Datetime', date('Y-m-d H:i:s')); $nowDatetime = SS_Datetime::now(); $this->assertNotEquals($systemDatetime->Date(), $nowDatetime->Date()); $this->assertEquals($nowDatetime->getValue(), $mockDate); // Test clearing SS_Datetime::clear_mock_now(); $systemDatetime = DBField::create('SS_Datetime', date('Y-m-d H:i:s')); $nowDatetime = SS_Datetime::now(); $this->assertEquals($systemDatetime->Date(), $nowDatetime->Date()); }
public function updateNewsletterEmail(NewsletterEmail $email) { $newsletter = $email->Newsletter(); if ($newsletter->ContentSource != 'page' || !$newsletter->SourcePageID) { return; } $page = $newsletter->SourcePage(); $response = Director::test($page->RelativeLink()); $body = $this->emogrify($response->getBody()); $body = str_replace('xmlns="http://www.w3.org/1999/xhtml"', '', HTTP::absoluteURLs($body)); $re = '/\\.src\\s*=' . str_replace('/', '\\/', Director::absoluteBaseURL()) . '/'; $body = preg_replace($re, '.src =', $body); // undo the fudging that happens to keywords $body = preg_replace('/"[^"]*%7B%24(\\w+)%7D/', '"{\\$$1}', $body); $email->setBody(DBField::create('HTMLText', $body)); }
/** * Returns the total sum of all the tickets the user is purchasing. * * @return Money */ public function getTotal() { $amount = 0; $currency = null; $data = $this->loadData(); if (isset($data['Tickets'])) { foreach ($data['Tickets'] as $id => $quantity) { $ticket = DataObject::get_by_id('EventTicket', $id); $price = $ticket->obj('Price'); if ($ticket->Type == 'Free' || !$quantity) { continue; } $amount += $price->getAmount() * $quantity; $currency = $price->getCurrency(); } } return DBField::create('Money', array('Amount' => $amount, 'Currency' => $currency)); }
public function onBeforeSend() { if (!($to = $this->owner->To())) { return; } $member = DataObject::get_one('Member', sprintf('"Email" = \'%s\'', Convert::raw2sql($to))); if (!$member) { return; } $body = $this->owner->Body()->forTemplate(); $pos = strrpos($body, '</body>'); $img = sprintf('<img src="%s" alt="" width="1" height="1">', Controller::join_links(Director::absoluteBaseURL(), 'newsletter-view', $this->owner->Newsletter()->Token, "{$member->NewsletterTrackingToken}.gif")); if ($pos) { $body = substr($body, 0, $pos) . $img . substr($body, $pos); } else { $body .= $img; } $this->owner->setBody(DBField::create('HTMLText', $body)); }
function testContextSummary() { $testString1 = '<p>This is some text. It is a test</p>'; $testKeywords1 = 'test'; $testString2 = '<p>This is some test text. Test test what if you have multiple keywords.</p>'; $testKeywords2 = 'some test'; $testString3 = '<p>A dog ate a cat while looking at a Foobar</p>'; $testKeyword3 = 'a'; $testKeyword3a = 'ate'; $textObj = DBField::create('Text', $testString1, 'Text'); $this->assertEquals('... text. It is a <span class="highlight">test</span>...', $textObj->ContextSummary(20, $testKeywords1)); $textObj->setValue($testString2); $this->assertEquals('This is <span class="highlight">some</span> <span class="highlight">test</span> text. <span class="highlight">test</span> <span class="highlight">test</span> what if you have...', $textObj->ContextSummary(50, $testKeywords2)); $textObj->setValue($testString3); // test that it does not highlight too much (eg every a) $this->assertEquals('A dog ate a cat while looking at a Foobar', $textObj->ContextSummary(100, $testKeyword3)); // it should highlight 3 letters or more. $this->assertEquals('A dog <span class="highlight">ate</span> a cat while looking at a Foobar', $textObj->ContextSummary(100, $testKeyword3a)); }
public function getById($id, $expires = Cache::EXPIRES_MEDIUM) { if ($expires !== Cache::DO_NOT_CACHE && ($object = $this->getCachedById($id))) { if ($object === Cache::NOT_FOUND) { throw new CachedObjectNotFoundException("there is no such object for '" . $this->dao->getObjectName() . "' with id=" . $id); } return $this->dao->completeObject($object); } else { $query = $this->dao->makeSelectHead()->andWhere(Expression::eq(DBField::create($this->dao->getIdName(), $this->dao->getTable()), $id)); if ($expires === Cache::DO_NOT_CACHE) { $object = $this->fetchObject($query); } else { $object = $this->cachedFetchObject($query, $expires, true); } if ($object) { return $object; } else { throw new ObjectNotFoundException("there is no such object for '" . $this->dao->getObjectName() . "' with query == " . $query->toDialectString(DBPool::me()->getByDao($this->dao)->getDialect())); } } }
/** * Returns a part of the field's text with a word or words highlighted. * HTML is stripped, and words are highlighted using HTML strong tags. * * @param $numWords Integer Number of words to output. Default is * 25. * @param $addParaTags Boolean Whether to add HTML paragraph tags * around the output. Default is true. * @return An HTMLText object containing the highlighted text as HTML. */ public function SearchTextHighlight($numWords = 25, $addParaTags = true) { $words = isset($_REQUEST['Search']) ? explode(' ', $_REQUEST['Search']) : array(); $text = strip_tags($this->owner->value); $orig = $text; $text_lower = explode(' ', strtolower($text)); // Find the search words in the summary $found = array(); $first = 0; foreach ($words as $word) { $tmp = array_search($word, $text_lower); if ($tmp !== false) { $found[] = $tmp; } } if (count($found) > 0) { $first = $found[0]; } // Get 25 words, starting two words before a highlighted word. if (count(explode(' ', $text)) > $numWords) { $text = implode(' ', array_slice(explode(' ', $text), max(0, $first - 2), $numWords)); if (substr($orig, -10) != substr($text, -10) && strlen($text) < strlen($orig)) { $text .= '...'; } if ($first != 0) { $text = '...' . $text; } } foreach ($words as $word) { if ($word === '') { continue; } $word = preg_quote($word); $text = preg_replace("/\\b({$word})\\b/i", '<strong>\\1</strong>', $text); } if ($addParaTags) { $text = '<p>' . $text . '</p>'; } return DBField::create('HTMLText', $text, $this->owner->name); }
function PriceRange() { $maxprice = $minprice = $averageprice = $hasrange = null; $variations = $this->owner->Variations(); if ($variations->exists() && $variations->Count()) { $prices = $variations->map('ID', 'Price'); $count = count($prices); $sum = array_sum($prices); $maxprice = max($prices); $minprice = min($prices); $hasrange = $minprice != $maxprice; $maxprice = DBField::create("Currency", $maxprice); $minprice = DBField::create("Currency", $minprice); if ($count > 0) { $averageprice = $sum / $count; $averageprice = DBField::create("Currency", $averageprice); } } else { return null; } return new ArrayData(array('HasRange' => $hasrange, 'Max' => $maxprice, 'Min' => $minprice, 'Average' => $averageprice, 'Currency' => $this->owner->Currency())); }
function Field() { $content = ''; Requirements::javascript(SAPPHIRE_DIR . "/thirdparty/prototype/prototype.js"); Requirements::javascript(SAPPHIRE_DIR . "/thirdparty/behaviour/behaviour.js"); Requirements::javascript(SAPPHIRE_DIR . "/javascript/prototype_improvements.js"); Requirements::javascript(SAPPHIRE_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('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 <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 <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; }