function testReadOnlyTransaction()
 {
     if (DB::get_conn()->supportsTransactions() == true && DB::get_conn() instanceof PostgreSQLDatabase) {
         $page = new Page();
         $page->Title = 'Read only success';
         $page->write();
         DB::get_conn()->transactionStart('READ ONLY');
         try {
             $page = new Page();
             $page->Title = 'Read only page failed';
             $page->write();
         } catch (Exception $e) {
             //could not write this record
             //We need to do a rollback or a commit otherwise we'll get error messages
             DB::get_conn()->transactionRollback();
         }
         DB::get_conn()->transactionEnd();
         DataObject::flush_and_destroy_cache();
         $success = DataObject::get('Page', "\"Title\"='Read only success'");
         $fail = DataObject::get('Page', "\"Title\"='Read only page failed'");
         //This page should be in the system
         $this->assertTrue(is_object($success) && $success->exists());
         //This page should NOT exist, we had 'read only' permissions
         $this->assertFalse(is_object($fail) && $fail->exists());
     } else {
         $this->markTestSkipped('Current database is not PostgreSQL');
     }
 }
 /**
  * @return string
  */
 public function sort($request)
 {
     $service = singleton('WorkflowService');
     $type = $request->postVar('type');
     $order = $request->postVar('ids');
     $parentId = $request->postVar('parent_id');
     switch ($type) {
         case 'WorkflowDefinition':
             $current = $service->getDefinitions();
             break;
         case 'WorkflowAction':
             $current = DataObject::get('WorkflowAction', sprintf('"WorkflowDefID" = %d', $parentId));
             break;
         case 'WorkflowTransition':
             $current = DataObject::get('WorkflowTransition', sprintf('"ActionID" = %d', $parentId));
             break;
         default:
             return $this->httpError(400, _t('AdvancedWorkflowAdmin.INVALIDSORTTYPE', 'Invalid sort type.'));
     }
     if (!$order || count($order) != count($current)) {
         return new SS_HTTPResponse(null, 400, _t('AdvancedWorkflowAdmin.INVALIDSORT', 'An invalid sort order was specified.'));
     }
     $service->reorder($current, $order);
     return new SS_HTTPResponse(null, 200, _t('AdvancedWorkflowAdmin.SORTORDERSAVED', 'The sort order has been saved.'));
 }
Example #3
0
 /**
  * Returns a DataObjectSet containing the subscribers who have never been sent this Newsletter
  *
  */
 function UnsentSubscribers()
 {
     // Get a list of everyone who has been sent this newsletter
     $sent_recipients = DataObject::get("Newsletter_SentRecipient", "ParentID='" . $this->ID . "'");
     // If this Newsletter has not been sent to anyone yet, $sent_recipients will be null
     if ($sent_recipients != null) {
         $sent_recipients_array = $sent_recipients->toNestedArray('MemberID');
     } else {
         $sent_recipients_array = array();
     }
     // Get a list of all the subscribers to this newsletter
     $subscribers = DataObject::get('Member', "`GroupID`='" . $this->Parent()->GroupID . "'", null, "INNER JOIN `Group_Members` ON `MemberID`=`Member`.`ID`");
     // If this Newsletter has no subscribers, $subscribers will be null
     if ($subscribers != null) {
         $subscribers_array = $subscribers->toNestedArray();
     } else {
         $subscribers_array = array();
     }
     // Get list of subscribers who have not been sent this newsletter:
     $unsent_subscribers_array = array_diff_key($subscribers_array, $sent_recipients_array);
     // Create new data object set containing the subscribers who have not been sent this newsletter:
     $unsent_subscribers = new DataObjectSet();
     foreach ($unsent_subscribers_array as $key => $data) {
         $unsent_subscribers->push(new ArrayData($data));
     }
     return $unsent_subscribers;
 }
 function run($request)
 {
     $br = Director::is_cli() ? "\n" : "<br/>";
     $verbose = true;
     //TODO: include order total calculation, once that gets written
     //TODO: figure out how to make this run faster
     //TODO: better memory managment...the destroy calls are not enough it appears.
     if ($orders = DataObject::get("Order")) {
         echo $br . "Writing all order items ";
         foreach ($orders as $order) {
             if ($items = $order->Items()) {
                 foreach ($items as $item) {
                     if ($item->Product()) {
                         if ($verbose) {
                             echo $item->ID . " ";
                         }
                         $item->write();
                         //OrderItem->onBeforeWrite calls 'CalculateTotal'
                     }
                     $item->destroy();
                 }
             }
             $order->destroy();
         }
         echo $br . "done." . $br;
     }
 }
 /**
  * @return Form
  */
 public function InviteForm()
 {
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-metadata/jquery.metadata.js');
     Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery_improvements.js');
     Requirements::javascript('eventmanagement/javascript/EventInvitationField_invite.js');
     if ($times = $this->form->getRecord()->DateTimes()) {
         $times = $times->map('ID', 'Summary');
     } else {
         $times = array();
     }
     // Get past date times attached to the parent calendar, so we can get
     // all registered members from them.
     $past = DataObject::get('RegisterableDateTime', sprintf('"CalendarID" = %d AND "StartDate" < \'%s\'', $this->form->getRecord()->CalendarID, date('Y-m-d')));
     if ($past) {
         $pastTimes = array();
         foreach ($past->groupBy('EventID') as $value) {
             $pastTimes[$value->First()->EventTitle()] = $value->map('ID', 'Summary');
         }
     } else {
         $pastTimes = array();
     }
     $fields = new Tab('Main', new HeaderField('Select A Date/Time To Invite To'), new DropdownField('TimeID', '', $times, null, null, true), new HeaderField('AddPeopleHeader', 'Add People To Invite From'), new SelectionGroup('AddPeople', array('From a member group' => $group = new DropdownField('GroupID', '', DataObject::get('Group')->map(), null, null, true), 'From a past event' => $time = new GroupedDropdownField('PastTimeID', '', $pastTimes, null, null, true))), new HeaderField('EmailsToSendHeader', 'People To Send Invite To'), $emails = new TableField('Emails', 'EventInvitation', array('Name' => 'Name', 'Email' => 'Email Address'), array('Name' => 'TextField', 'Email' => 'TextField')));
     $group->addExtraClass(sprintf("{ link: '%s' }", $this->Link('loadfromgroup')));
     $time->addExtraClass(sprintf("{ link: '%s' }", $this->Link('loadfromtime')));
     $emails->setCustomSourceItems(new DataObjectSet());
     $fields = new FieldSet(new TabSet('Root', $fields));
     $validator = new RequiredFields('TimeID');
     return new Form($this, 'InviteForm', $fields, new FieldSet(new FormAction('doInvite', 'Invite')), $validator);
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->scaffoldSearchFields($className);
         // convert that list into something we can pass to Datalist::filter
         $keywordFilter = array();
         if (!empty($keywords)) {
             foreach ($keywordFields as $searchField) {
                 $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:PartialMatch";
                 $keywordFilter[$name] = $keywords;
             }
         }
         if (count($keywordFilter) > 0) {
             $list = $list->filterAny($keywordFilter);
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 /**
  * Send email to subscribers, notifying them the thread has been created or post added.
  */
 public function notifySubscribers()
 {
     // all members id except current user
     $member_id = Member::currentUserID();
     $list = DataObject::get("Forum_Subscribers", "\"ForumID\" = '" . $this->owner->ForumID . "' AND \"MemberID\" != '{$member_id}'");
     if ($list) {
         foreach ($list as $obj) {
             $SQL_id = Convert::raw2sql((int) $obj->MemberID);
             // Get the members details
             $member = DataObject::get_one("Member", "\"Member\".\"ID\" = '{$SQL_id}'");
             if ($member) {
                 //error_log("email sent ".$member->Email);
                 $type = $obj->Type;
                 switch ($type) {
                     // send all email notification
                     case 'all':
                         $this->createEmail($member);
                         break;
                         // send new thread only email notification
                     // send new thread only email notification
                     case 'thread':
                         //if($this->owner->isFirstPost()){
                         $this->createEmail($member);
                         //}
                         break;
                         //
                     //
                     default:
                         break;
                 }
             }
         }
     }
 }
 /**
  * Get the most recent posts on a blog.
  */
 function getRecentPosts($blogid, $username, $password, $numberOfPosts)
 {
     $member = MemberAuthenticator::authenticate(array('Email' => $username, 'Password' => $password));
     // TODO Throw approriate error.
     if (!$member) {
         die;
     }
     $posts = DataObject::get('BlogEntry', '"ParentID" = ' . (int) $blogid, '"Date" DESC');
     $res = array();
     $postsSoFar = 0;
     foreach ($posts as $post) {
         if (!$post->canEdit($member)) {
             continue;
         }
         $parr = array();
         $parr['title'] = $post->Title;
         $parr['link'] = $post->AbsoluteLink();
         $parr['description'] = $post->Content;
         $parr['postid'] = (int) $post->ID;
         $res[] = $parr;
         if (++$postsSoFar >= $numberOfPosts) {
             break;
         }
     }
     return $res;
 }
 /**
  * @param ManyManyList $products
  */
 public function updateRelatedProducts(&$products, $limit, $random)
 {
     $curCount = $products->count();
     if ($curCount < $limit) {
         $cfg = Config::inst()->forClass(get_class($this->owner));
         $class = $cfg->get('related_products_class');
         // look up the fields
         $fields = $cfg->get('related_products_fields');
         if (empty($fields)) {
             return;
         }
         if (!is_array($fields)) {
             $fields = array($fields);
         }
         // create a filter from the fields
         $filter = array();
         foreach ($fields as $f) {
             $filter[$f] = $this->owner->getField($f);
         }
         // Convert to an array list so we can add to it
         $products = new ArrayList($products->toArray());
         // Look up products that match the filter
         $generated = DataObject::get($class)->filterAny($filter)->exclude('ID', $this->owner->ID)->sort('RAND()')->limit($limit - $curCount);
         foreach ($generated as $prod) {
             $products->push($prod);
         }
     }
 }
 /**
  * OrderedGalleryItems()
  * @note return gallery items ordered as set in admin
  */
 public function OrderedGalleryItems()
 {
     if ($this->Visible == 1) {
         return DataObject::get('DisplayAnythingFile', 'GalleryID=' . $this->ID . ' AND Visible = 1', '`File`.`Sort` ASC, `File`.`Created` DESC');
     }
     return FALSE;
 }
 public function finish($data, $form)
 {
     parent::finish($data, $form);
     $steps = DataObject::get('MultiFormStep', "SessionID = {$this->session->ID}");
     if ($steps) {
         foreach ($steps as $step) {
             if ($step->class == 'Page2PersonalDetailsFormStep') {
                 $member = new Member();
                 $data = $step->loadData();
                 if ($data) {
                     $member->update($data);
                     $member->write();
                 }
             }
             if ($step->class == 'Page2OrganisationDetailsFormStep') {
                 $organisation = new Organisation();
                 $data = $step->loadData();
                 if ($data) {
                     $organisation->update($data);
                     if ($member && $member->ID) {
                         $organisation->MemberID = $member->ID;
                     }
                     $organisation->write();
                 }
             }
             // Debug::show($step->loadData()); // Shows the step data (unserialized by loadData)
         }
     }
     $controller = $this->getController();
     $controller->redirect($controller->Link() . 'finished');
 }
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->getSearchFields($className);
         // build the filter
         $filter = array();
         // Use parametrized query if SilverStripe >= 3.2
         if (SHOP_SEARCH_IS_SS32) {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = array("MATCH ({$indexFields}) AGAINST (?)" => $keywords);
             }
             $list = $list->whereAny($filter);
         } else {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = sprintf("MATCH ({$indexFields}) AGAINST ('%s')", Convert::raw2sql($keywords));
             }
             // join all the filters with an "OR" statement
             $list = $list->where(implode(' OR ', $filter));
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }
 /**
  * Returns all members of a group by ID .
  * 
  * @param int $ID  group ID
  * @return DataList
  */
 public function MemberGroup($ID = 1)
 {
     if ($group = DataObject::get('Group')->byID($ID)) {
         return $group->Members();
     }
     return false;
 }
 public function getRandomQuestion()
 {
     $qid = Session::get('QACaptchaField.Retry');
     if (isset($qid) && $qid) {
         // Retry the same question
         return DataObject::get_by_id('QACaptchaQuestion', $qid);
     }
     // Provide empty answer field - the question has not been answered yet
     $this->setValue('');
     // Get a comma separated list of past questions
     $backlog = Session::get('QACaptchaField.Backlog');
     if (!$backlog) {
         $backlog = array();
     }
     $sqlBacklog = implode($backlog, ', ');
     // Get questions that have not been used before
     $random = DataObject::get('QACaptchaQuestion', $sqlBacklog ? "\"QACaptchaQuestion\".\"ID\" NOT IN ({$sqlBacklog})" : '', DB::getConn()->random());
     if (!($random && $random->exists())) {
         // We have ran out of questions - reset the list
         $backlog = array();
         Session::clear('QACaptchaField.Backlog');
         $random = DataObject::get('QACaptchaQuestion', '', DB::getConn()->random());
     }
     if ($random && $random->exists()) {
         $q = $random->First();
         // Add the question to backlog
         $backlog[] = $q->ID;
         Session::set('QACaptchaField.Backlog', $backlog);
         return $q;
     }
 }
Example #15
0
 public function testCreateWithTransaction()
 {
     if (DB::getConn()->supportsTransactions() == true) {
         DB::getConn()->transactionStart();
         $obj = new TransactionTest_Object();
         $obj->Title = 'First page';
         $obj->write();
         $obj = new TransactionTest_Object();
         $obj->Title = 'Second page';
         $obj->write();
         //Create a savepoint here:
         DB::getConn()->transactionSavepoint('rollback');
         $obj = new TransactionTest_Object();
         $obj->Title = 'Third page';
         $obj->write();
         $obj = new TransactionTest_Object();
         $obj->Title = 'Fourth page';
         $obj->write();
         //Revert to a savepoint:
         DB::getConn()->transactionRollback('rollback');
         DB::getConn()->transactionEnd();
         $first = DataObject::get('TransactionTest_Object', "\"Title\"='First page'");
         $second = DataObject::get('TransactionTest_Object', "\"Title\"='Second page'");
         $third = DataObject::get('TransactionTest_Object', "\"Title\"='Third page'");
         $fourth = DataObject::get('TransactionTest_Object', "\"Title\"='Fourth page'");
         //These pages should be in the system
         $this->assertTrue(is_object($first) && $first->exists());
         $this->assertTrue(is_object($second) && $second->exists());
         //These pages should NOT exist, we reverted to a savepoint:
         $this->assertFalse(is_object($third) && $third->exists());
         $this->assertFalse(is_object($fourth) && $fourth->exists());
     } else {
         $this->markTestSkipped('Current database does not support transactions');
     }
 }
 /**
  * Helper method for applicablePages() methods.  Acts as a skeleton implementation.
  * 
  * @param $ids The IDs passed to applicablePages
  * @param $methodName The canXXX() method to call on each page to check if the action is applicable
  * @param $checkStagePages Set to true if you want to check stage pages
  * @param $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
  */
 function applicablePagesHelper($ids, $methodName, $checkStagePages = true, $checkLivePages = true)
 {
     if (!is_array($ids)) {
         user_error("Bad \$ids passed to applicablePagesHelper()", E_USER_WARNING);
     }
     if (!is_string($methodName)) {
         user_error("Bad \$methodName passed to applicablePagesHelper()", E_USER_WARNING);
     }
     $applicableIDs = array();
     $SQL_ids = implode(', ', array_filter($ids, 'is_numeric'));
     $draftPages = DataObject::get("SiteTree", "\"SiteTree\".\"ID\" IN ({$SQL_ids})");
     $onlyOnLive = array_fill_keys($ids, true);
     if ($checkStagePages) {
         foreach ($draftPages as $page) {
             unset($onlyOnLive[$page->ID]);
             if ($page->{$methodName}()) {
                 $applicableIDs[] = $page->ID;
             }
         }
     }
     // Get the pages that only exist on live (deleted from stage)
     if ($checkLivePages && $onlyOnLive) {
         $SQL_ids = implode(', ', array_keys($onlyOnLive));
         $livePages = Versioned::get_by_stage("SiteTree", "Live", "\"SiteTree\".\"ID\" IN ({$SQL_ids})");
         if ($livePages) {
             foreach ($livePages as $page) {
                 if ($page->{$methodName}()) {
                     $applicableIDs[] = $page->ID;
                 }
             }
         }
     }
     return $applicableIDs;
 }
 function testForcedDisplay()
 {
     $poll = DataObject::get('Poll')->first();
     $response = $this->get('TestPollForm_Controller?poll_results');
     $selected = $this->cssParser()->getBySelector('form#PollForm_PollForm');
     $this->assertEquals(count($selected), 0, 'Input form is not shown');
 }
 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 run($request)
 {
     $algo = Security::get_password_encryption_algorithm();
     if ($algo == 'none') {
         $this->debugMessage('Password encryption disabled');
         return;
     }
     // Are there members with a clear text password?
     $members = DataObject::get("Member", "\"PasswordEncryption\" = 'none' AND \"Password\" IS NOT NULL");
     if (!$members) {
         $this->debugMessage('No passwords to encrypt');
         return;
     }
     // Encrypt the passwords...
     $this->debugMessage('Encrypting all passwords');
     $this->debugMessage(sprintf('The passwords will be encrypted using the %s algorithm', $algo));
     foreach ($members as $member) {
         // Force the update of the member record, as new passwords get
         // automatically encrypted according to the settings, this will do all
         // the work for us
         $member->PasswordEncryption = $algo;
         $member->forceChange();
         $member->write();
         $this->debugMessage(sprintf('Encrypted credentials for member #%d;', $member->ID));
     }
 }
 function testProcess()
 {
     $form = $this->setupFormFrontend();
     $controller = new UserDefinedFormControllerTest_Controller($form);
     $this->autoFollowRedirection = false;
     $this->clearEmails();
     // load the form
     $this->get($form->URLSegment);
     $response = $this->submitForm('Form_Form', null, array('basic-text-name' => 'Basic Value'));
     // should have a submitted form field now
     $submitted = DataObject::get('SubmittedFormField', "\"Name\" = 'basic-text-name'");
     $this->assertDOSAllMatch(array('Name' => 'basic-text-name', 'Value' => 'Basic Value', 'Title' => 'Basic Text Field'), $submitted);
     // check emails
     $this->assertEmailSent('*****@*****.**', '*****@*****.**', 'Email Subject');
     $email = $this->findEmail('*****@*****.**', '*****@*****.**', 'Email Subject');
     // assert that the email has the field title and the value html email
     $parser = new CSSContentParser($email['content']);
     $title = $parser->getBySelector('strong');
     $this->assertEquals('Basic Text Field', (string) $title[0], 'Email contains the field name');
     $value = $parser->getBySelector('dd');
     $this->assertEquals('Basic Value', (string) $value[0], 'Email contains the value');
     // no html
     $this->assertEmailSent('*****@*****.**', '*****@*****.**', 'Email Subject');
     $nohtml = $this->findEmail('*****@*****.**', '*****@*****.**', 'Email Subject');
     $this->assertContains('Basic Text Field - Basic Value', $nohtml['content'], 'Email contains no html');
     // no data
     $this->assertEmailSent('*****@*****.**', '*****@*****.**', 'Email Subject');
     $nodata = $this->findEmail('*****@*****.**', '*****@*****.**', 'Email Subject');
     $parser = new CSSContentParser($nodata['content']);
     $list = $parser->getBySelector('dl');
     $this->assertFalse(isset($list[0]), 'Email contains no fields');
     // check to see if the user was redirected (301)
     $this->assertEquals($response->getStatusCode(), 302);
     $this->assertStringEndsWith('finished', $response->getHeader('Location'));
 }
Example #21
0
 /**
  * @param String $password
  * @param Member $member
  * @return ValidationResult
  */
 public function validate($password, $member)
 {
     $valid = new ValidationResult();
     if ($this->minLength) {
         if (strlen($password) < $this->minLength) {
             $valid->error(sprintf("Password is too short, it must be %s or more characters long.", $this->minLength), "TOO_SHORT");
         }
     }
     if ($this->minScore) {
         $score = 0;
         $missedTests = array();
         foreach ($this->testNames as $name) {
             if (preg_match(self::$character_strength_tests[$name], $password)) {
                 $score++;
             } else {
                 $missedTests[] = $name;
             }
         }
         if ($score < $this->minScore) {
             $valid->error("You need to increase the strength of your passwords by adding some of the following characters: " . implode(", ", $missedTests), "LOW_CHARACTER_STRENGTH");
         }
     }
     if ($this->historicalPasswordCount) {
         $previousPasswords = DataObject::get("MemberPassword", "\"MemberID\" = {$member->ID}", "\"Created\" DESC, \"ID\" Desc", "", $this->historicalPasswordCount);
         if ($previousPasswords) {
             foreach ($previousPasswords as $previousPasswords) {
                 if ($previousPasswords->checkPassword($password)) {
                     $valid->error("You've already used that password in the past, please choose a new password", "PREVIOUS_PASSWORD");
                     break;
                 }
             }
         }
     }
     return $valid;
 }
 /**
  * Get all orders for current member / session.
  * @return DataObjectSet of Orders
  */
 public function allorders($filter = "", $orderby = "")
 {
     if ($filter && $filter != "") {
         $filter = " AND " . $filter;
     }
     return DataObject::get('Order', $this->orderfilter() . $filter, $orderby);
 }
 public function run($request)
 {
     $gp = ShopConfig::current()->CustomerGroup();
     if (empty($gp)) {
         return false;
     }
     $allCombos = DB::query("SELECT \"ID\", \"MemberID\", \"GroupID\" FROM \"Group_Members\" WHERE \"Group_Members\".\"GroupID\" = " . $gp->ID . ";");
     //make an array of all combos
     $alreadyAdded = array();
     $alreadyAdded[-1] = -1;
     if ($allCombos) {
         foreach ($allCombos as $combo) {
             $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"];
         }
     }
     $unlistedMembers = DataObject::get("Member", $where = "\"Member\".\"ID\" NOT IN (" . implode(",", $alreadyAdded) . ")", $sort = null, $join = "INNER JOIN \"Order\" ON \"Order\".\"MemberID\" = \"Member\".\"ID\"");
     //add combos
     if ($unlistedMembers) {
         $existingMembers = $gp->Members();
         foreach ($unlistedMembers as $member) {
             $existingMembers->add($member);
             echo ".";
         }
     } else {
         echo "no new members added";
     }
 }
 public function run($request)
 {
     $sent = 0;
     $filter = '"WorkflowStatus" IN (\'Active\', \'Paused\') AND "RemindDays" > 0';
     $join = 'INNER JOIN "WorkflowDefinition" ON "DefinitionID" = "WorkflowDefinition"."ID"';
     $active = DataObject::get('WorkflowInstance', $filter, null, $join);
     if ($active) {
         foreach ($active as $instance) {
             $edited = strtotime($instance->LastEdited);
             $days = $instance->Definition()->RemindDays;
             if ($edited + $days * 3600 * 24 > time()) {
                 continue;
             }
             $email = new Email();
             $bcc = '';
             $members = $instance->getAssignedMembers();
             $target = $instance->getTarget();
             if (!$members || !count($members)) {
                 continue;
             }
             $email->setSubject("Workflow Reminder: {$instance->Title}");
             $email->setBcc(implode(', ', $members->column('Email')));
             $email->setTemplate('WorkflowReminderEmail');
             $email->populateTemplate(array('Instance' => $instance, 'Link' => $target instanceof SiteTree ? "admin/show/{$target->ID}" : ''));
             $email->send();
             $sent++;
             $instance->LastEdited = time();
             $instance->write();
         }
     }
     echo "Sent {$sent} workflow reminder emails.\n";
 }
 /**
  * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
  * link is trimmed of leading and trailing slashes before returning to ensure consistency.
  *
  * @return string
  */
 public static function get_homepage_link()
 {
     if (!self::$cached_homepage_link) {
         // TODO Move to 'homepagefordomain' module
         if (class_exists('HomepageForDomainExtension')) {
             $host = str_replace('www.', null, $_SERVER['HTTP_HOST']);
             $SQL_host = Convert::raw2sql($host);
             $candidates = DataObject::get('SiteTree', "\"HomepageForDomain\" LIKE '%{$SQL_host}%'");
             if ($candidates) {
                 foreach ($candidates as $candidate) {
                     if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
                         self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
                     }
                 }
             }
         }
         if (!self::$cached_homepage_link) {
             // TODO Move to 'translatable' module
             if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) {
                 self::$cached_homepage_link = $link;
             } else {
                 self::$cached_homepage_link = self::get_default_homepage_link();
             }
         }
     }
     return self::$cached_homepage_link;
 }
 public function Form()
 {
     $player = DataObject::get('GridFieldTest_Player')->find('Email', '*****@*****.**');
     $config = GridFieldConfig::create()->addComponents($relationComponent = new GridFieldAddExistingAutocompleter('before', 'Name'), new GridFieldDataColumns());
     $field = new GridField('testfield', 'testfield', $player->Teams(), $config);
     return new Form($this, 'Form', new FieldList($field), new FieldList());
 }
 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;
 }
 function submitPoll($data, $form)
 {
     $choiceIDs = is_array($data['PollChoices']) ? $data['PollChoices'] : array($data['PollChoices']);
     $choicesIDs = implode(',', $choiceIDs);
     $choices = DataObject::get('PollChoice', sprintf('"ID" IN (%s)', $choicesIDs));
     if ($choices) {
         foreach ($choices as $choice) {
             $choice->addVote();
         }
         $form->poll->markAsVoted();
     }
     // Redirect back to anchor (partly copied from Director::redirectBack)
     if (self::$redirect_to_anchor) {
         if ($this->request->requestVar('_REDIRECT_BACK_URL')) {
             $url = $this->request->requestVar('_REDIRECT_BACK_URL');
         } else {
             if ($this->request->getHeader('Referer')) {
                 $url = $this->request->getHeader('Referer');
             } else {
                 $url = Director::baseURL();
             }
         }
         $url .= '#' . self::$redirect_to_anchor . '-' . $this->poll->ID;
         $this->controller->redirect($url);
     } else {
         $this->controller->redirectBack();
     }
 }
 public function testDelete()
 {
     $role = $this->objFromFixture('PermissionRole', 'role');
     $role->delete();
     $this->assertEquals(0, DataObject::get('PermissionRole', "\"ID\"={$role->ID}")->count(), 'Role is removed');
     $this->assertEquals(0, DataObject::get('PermissionRoleCode', "\"RoleID\"={$role->ID}")->count(), 'Permissions removed along with the role');
 }
Example #30
0
 public function isFoundationMember()
 {
     $res = $this->owner->inGroup(IFoundationMember::FoundationMemberGroupSlug);
     $legal_agreements = DataObject::get("LegalAgreement", " LegalDocumentPageID=422 AND MemberID =" . $this->owner->ID);
     $res = $res && $legal_agreements->count() > 0;
     return $res;
 }