public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     $fields->addFieldToTab('Root.Main', new TextField('Title', $this->fieldLabel('Title')));
     $filter = '';
     $reqParent = isset($_REQUEST['ParentID']) ? (int) $_REQUEST['ParentID'] : 0;
     $attachTo = $this->ActionID ? $this->ActionID : $reqParent;
     if ($attachTo) {
         $action = DataObject::get_by_id('WorkflowAction', $attachTo);
         if ($action && $action->ID) {
             $filter = '"WorkflowDefID" = ' . (int) $action->WorkflowDefID;
         }
     }
     $actions = DataObject::get('WorkflowAction', $filter);
     $options = array();
     if ($actions) {
         $options = $actions->map();
     }
     $defaultAction = $action ? $action->ID : "";
     $typeOptions = array('Active' => _t('WorkflowTransition.Active', 'Active'), 'Passive' => _t('WorkflowTransition.Passive', 'Passive'));
     $fields->addFieldToTab('Root.Main', new DropdownField('ActionID', $this->fieldLabel('ActionID'), $options, $defaultAction));
     $fields->addFieldToTab('Root.Main', $nextActionDropdownField = new DropdownField('NextActionID', $this->fieldLabel('NextActionID'), $options));
     $nextActionDropdownField->setEmptyString(_t('WorkflowTransition.SELECTONE', '(Select one)'));
     $fields->addFieldToTab('Root.Main', new DropdownField('Type', _t('WorkflowTransition.TYPE', 'Type'), $typeOptions));
     $members = Member::get();
     $fields->findOrMakeTab('Root.RestrictToUsers', _t('WorkflowTransition.TabTitle', 'Restrict to users'));
     $fields->addFieldToTab('Root.RestrictToUsers', new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Restrict to Users'), $members));
     $fields->addFieldToTab('Root.RestrictToUsers', new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Restrict to Groups'), 'Group'));
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 public function Breadcrumbs($unlinked = false)
 {
     $items = parent::Breadcrumbs($unlinked);
     //special case for building the breadcrumbs when calling the listchildren Pages ListView action
     if ($parentID = $this->getRequest()->getVar('ParentID')) {
         $page = DataObject::get_by_id('SiteTree', $parentID);
         //build a reversed list of the parent tree
         $pages = array();
         while ($page) {
             array_unshift($pages, $page);
             //add to start of array so that array is in reverse order
             $page = $page->Parent;
         }
         //turns the title and link of the breadcrumbs into template-friendly variables
         $params = array_filter(array('view' => $this->getRequest()->getVar('view'), 'q' => $this->getRequest()->getVar('q')));
         foreach ($pages as $page) {
             $params['ParentID'] = $page->ID;
             $item = new StdClass();
             $item->Title = $page->Title;
             $item->Link = Controller::join_links($this->Link(), '?' . http_build_query($params));
             $items->push(new ArrayData($item));
         }
     }
     return $items;
 }
 /** 
  * convertToCurrency
  * Convert the provided string/number to a number_format() string using configuration of the given currency.
  *
  * @param int $number The number we are to convert to the currency defined in $currency.
  * @param int $currency The database id of the currency to display. If blank, defaults to the system default.
  *
  * @return float
  */
 public static function convertToCurrency($number, $currency = 1)
 {
     //Fetch the config for the currency provided
     $conf = DataObject::get_by_id("StoreCurrency", $currency);
     //Return our currency.
     return number_format($number, $conf->DecimalPlaces, $conf->DecimalSeperator, $conf->ThousandsSeperator);
 }
Example #4
0
 public function getTask()
 {
     $Params = $this->getURLParams();
     if (is_numeric($Params['ID']) && ($task = DataObject::get_by_id('Task', $Params['ID']))) {
         return $task;
     }
 }
	function testAddingHasManyData() {
		$this->logInWithPermission('ADMIN');
		
		$team = DataObject::get_one('ComplexTableFieldTest_Team', "\"Name\" = 'The Awesome People'");
		
		$this->post('ComplexTableFieldTest_Controller/HasManyForm/field/Sponsors/AddForm', array(
			'Name' => 'Jim Beam',
			'ctf' => array(
				'ClassName' => 'ComplexTableFieldTest_Sponsor',
				'hasManyRelation' => 'Sponsors',
				'parentClass' => 'ComplexTableFieldTest_Team',
				'sourceID' => $team->ID
			)
		));

		$newSponsor = DataObject::get_one('ComplexTableFieldTest_Sponsor', "\"Name\" = 'Jim Beam'");
		$this->assertNotNull($newSponsor, 'A new ComplexTableFieldTest_Sponsor record was created, Name = "Jim Beam"');
		$this->assertEquals($newSponsor->TeamID, $team->ID, 'Automatic has-many/has-one relation was set correctly on the sponsor');
		$this->assertEquals($newSponsor->getComponent('Team')->ID, $team->ID, 'Automatic has-many/has-one relation was set correctly on the sponsor');
		
		$team = DataObject::get_by_id('ComplexTableFieldTest_Team', $team->ID);
		$sponsor = DataObject::get_by_id('ComplexTableFieldTest_Sponsor', $newSponsor->ID);
		$this->assertEquals($newSponsor->ID, $sponsor->ID, 'The sponsor is the same as the one we added');
		$foundTeam = $sponsor->getComponent('Team');
		$this->assertEquals($team->ID, $foundTeam->ID, 'The team ID matches on the other side of the relation');
	}
 /**
  * Alter file path to generated a static (static) error page file to handle error page template on different sub-sites 
  *
  * @see Error::get_filepath_for_errorcode()
  *
  * FIXME since {@link Subsite::currentSubsite()} partly relies on Session, viewing other sub-site (including main site) between 
  * opening ErrorPage in the CMS and publish ErrorPage causes static error page to get generated incorrectly. 
  */
 function alternateFilepathForErrorcode($statusCode, $locale = null)
 {
     $static_filepath = Object::get_static($this->owner->ClassName, 'static_filepath');
     $subdomainPart = "";
     // Try to get current subsite from session
     $subsite = Subsite::currentSubsite(false);
     // since this function is called from Page class before the controller is created, we have to get subsite from domain instead
     if (!$subsite) {
         $subsiteID = Subsite::getSubsiteIDForDomain();
         if ($subsiteID != 0) {
             $subsite = DataObject::get_by_id("Subsite", $subsiteID);
         } else {
             $subsite = null;
         }
     }
     if ($subsite) {
         $subdomain = $subsite->domain();
         $subdomainPart = "-{$subdomain}";
     }
     if (singleton('SiteTree')->hasExtension('Translatable') && $locale && $locale != Translatable::default_locale()) {
         $filepath = $static_filepath . "/error-{$statusCode}-{$locale}{$subdomainPart}.html";
     } else {
         $filepath = $static_filepath . "/error-{$statusCode}{$subdomainPart}.html";
     }
     return $filepath;
 }
 public function Field($properties = array())
 {
     if (!$this->config['readonly']) {
         Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
         Requirements::javascript(THIRDPARTY_DIR . '/jquery-livequery/jquery.livequery.js');
         Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/src/jquery.selector.affectedby.js');
         Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.core.js');
         Requirements::javascript('linkableobjects/javascript/DataObjectPicker.js');
     }
     Requirements::css('linkableobjects/css/DataObjectPicker.css');
     $current = $this->Value() ? DataObject::get_by_id($this->classToPick(), $this->Value()) : false;
     if ($current) {
         $sf = $this->summaryFields();
         $full = array();
         foreach ($sf as $f) {
             if ($current->{$f}) {
                 $full[] = $current->{$f};
             }
         }
         if (empty($full)) {
             $full[] = 'undefined dataobject';
         }
         $nice = implode(',', $full);
     } else {
         $nice = '-- none selected --';
     }
     $html = "<p><em class='DataObjectPickerMessage'>Type to search.</em></p>" . $this->createTag('input', array('type' => 'hidden', 'class' => 'DataObjectPicker', 'id' => $this->id(), 'name' => $this->getName(), 'value' => $this->Value()));
     if ($this->config['readonly']) {
         $html .= $this->createTag('span', array('class' => 'DataObjectPickerHelper text readonly' . ($this->extraClass() ? $this->extraClass() : ''), 'id' => $this->id() . '_helper', 'tabindex' => !!$this->getAttribute('tabindex'), 'readonly' => 'readonly'), $nice);
     } else {
         $html .= $this->createTag('input', array('type' => 'text', 'autocomplete' => 'off', 'class' => 'DataObjectPickerHelper text' . ($this->extraClass() ? $this->extraClass() : ''), 'id' => $this->id() . '_helper', 'name' => $this->getName() . '_helper', 'value' => $nice, 'tabindex' => !!$this->getAttribute('tabindex'), 'maxlength' => $this->maxLength ? $this->maxLength : null, 'size' => $this->maxLength ? min($this->maxLength, 30) : null, 'rel' => $this->form ? $this->Link() : 'admin/EditForm/field/' . $this->getName())) . $this->createTag('ul', array('class' => 'DataObjectPickerSuggestions', 'id' => $this->id() . '_suggestions'));
     }
     return $html . $this->createTag('div', array('style' => 'clear:both;'));
 }
 public function index($request)
 {
     $id = $request->param('ID');
     $token = $request->getVar('token');
     if (!$id || !ctype_digit($id)) {
         $this->httpError(404, 'A member ID was not specified.');
     }
     $member = DataObject::get_by_id('Member', $id);
     if (!$member) {
         $this->httpError(404, 'The specified member could not be found.');
     }
     if (!$member->canEdit()) {
         return Security::permissionFailure();
     }
     if ($token != $member->ValidationKey) {
         $this->httpError(400, 'An invalid token was specified.');
     }
     if (!$member->NeedsApproval) {
         $title = _t('MemberProfiles.ALREADYAPPROVED', 'Already Approved');
         $content = _t('MemberProfiles.ALREADYAPPROVEDNOTE', 'This member has already been approved');
         return $this->render(array('Title' => $title, 'Content' => "<p>{$content}</p>"));
     }
     $member->NeedsApproval = false;
     $member->write();
     $title = _t('MemberProfiles.MEMBERAPPROVED', 'Member Approved');
     $content = _t('MemberProfiles.MEMBERAPPROVEDCONTENT', 'The member "%s" has been approved and can now log in.');
     $content = sprintf($content, Convert::raw2xml("{$member->Name} <{$member->Email}>"));
     return $this->render(array('Title' => $title, 'Content' => $content));
 }
 public function processRecord($record, $columnMap, &$results, $preview = false)
 {
     $objID = parent::processRecord($record, $columnMap, $results, $preview);
     $_cache_groupByCode = array();
     // Add to predefined groups
     $member = DataObject::get_by_id($this->objectClass, $objID);
     foreach ($this->groups as $group) {
         // TODO This isnt the most memory effective way to add members to a group
         $member->Groups()->add($group);
     }
     // Add to groups defined in CSV
     if (isset($record['Groups']) && $record['Groups']) {
         $groupCodes = explode(',', $record['Groups']);
         foreach ($groupCodes as $groupCode) {
             $groupCode = Convert::raw2url($groupCode);
             if (!isset($_cache_groupByCode[$groupCode])) {
                 $group = Group::get()->filter('Code', $groupCode)->first();
                 if (!$group) {
                     $group = new Group();
                     $group->Code = $groupCode;
                     $group->Title = $groupCode;
                     $group->write();
                 }
                 $member->Groups()->add($group);
                 $_cache_groupByCode[$groupCode] = $group;
             }
         }
     }
     $member->destroy();
     unset($member);
     return $objID;
 }
 static function parse_Lightbox($arguments, $content = null, $parser, $tagName = null)
 {
     $lightbox = DataObject::get_by_id('Lightbox', $arguments['id']);
     if ($lightbox && ($link = $lightbox->Link())) {
         return "{$link}";
     }
 }
Example #11
0
 /**
  * Returns the parent {@link DataObject} this comment is attached too
  *
  * @return DataObject
  */
 public function getParent()
 {
     if (!$this->BaseClass) {
         $this->BaseClass = "SiteTree";
     }
     return DataObject::get_by_id($this->BaseClass, $this->ParentID);
 }
Example #12
0
	public function testSaveTreeNodeParentID() {
		$this->loginWithPermission('ADMIN');

		$page1 = $this->objFromFixture('LeftAndMainTest_Object', 'page1');
		$page2 = $this->objFromFixture('LeftAndMainTest_Object', 'page2');
		$page3 = $this->objFromFixture('LeftAndMainTest_Object', 'page3');
		$page31 = $this->objFromFixture('LeftAndMainTest_Object', 'page31');
		$page32 = $this->objFromFixture('LeftAndMainTest_Object', 'page32');

		// Move page2 into page3, between page3.1 and page 3.2
		$siblingIDs = array(
			$page31->ID,
			$page2->ID,
			$page32->ID
		);
		$data = array(
			'SiblingIDs' => $siblingIDs,
			'ID' => $page2->ID,
			'ParentID' => $page3->ID
		);
		$response = $this->post('LeftAndMainTest_Controller/savetreenode', $data);
		$this->assertEquals(200, $response->getStatusCode());
		$page2 = DataObject::get_by_id('LeftAndMainTest_Object', $page2->ID, false);
		$page31 = DataObject::get_by_id('LeftAndMainTest_Object', $page31->ID, false);
		$page32 = DataObject::get_by_id('LeftAndMainTest_Object', $page32->ID, false);

		$this->assertEquals($page3->ID, $page2->ParentID, 'Moved page gets new parent');
		$this->assertEquals(1, $page31->Sort, 'Children pages before insertaion are unaffected');
		$this->assertEquals(2, $page2->Sort, 'Moved page is correctly sorted');
		$this->assertEquals(3, $page32->Sort, 'Children pages after insertion are resorted');
	}
 public function __construct($controller, $name, $order)
 {
     /* Store Settings Object */
     $conf = StoreSettings::get_settings();
     /* Comments Box, if enabled */
     if ($conf->CheckoutSettings_OrderComments) {
         $comments = TextareaField::create("CustomerComments", "Order Comments");
         $comments->setRightTitle("These comments will be seen by staff.");
     } else {
         $comments = HiddenField::create("CustomerComments", "");
     }
     /* Terms and Conditions, if enabled */
     if ($conf->CheckoutSettings_TermsAndConditions) {
         $terms = CheckboxField::create("Terms", "I agree to " . $conf->StoreSettings_StoreName . "'s " . "<a href=" . DataObject::get_by_id("SiteTree", $conf->CheckoutSettings_TermsAndConditionsSiteTree)->URLSegment . ">" . "Terms &amp; Conditions</a>.");
     } else {
         $terms = HiddenField::create("Terms", "");
     }
     /* Fields */
     $fields = FieldList::create($comments, OptionsetField::create("PaymentMethod", "Payment Method", Gateway::create()->getGateways($order)), $terms ? HeaderField::create("Terms and Conditions", 5) : HiddenField::create("TermsHeaderField", ""), $terms);
     /* Actions */
     $actions = FieldList::create(FormAction::create('payment', 'Place Order &amp; Continue to Payment'));
     /* Required Fields */
     $required = new RequiredFields(array("PaymentMethod", $terms ? "Terms" : null));
     /*
      * Now we create the actual form with our fields and actions defined 
      * within this class.
      */
     return parent::__construct($controller, $name, $fields, $actions, $required);
 }
 /**
  * Execute this method invocation object. If there are problems, throws an exception,
  * including if user_error is called during the call (suppressed user_error, but detects
  * if a user_error was ignored).
  *
  * @param MessageFrame $msgframe		The message received
  * @param Map $config					Interface configuration if called
  *										from MessageQueue.
  * @return whatever the underlying method returns
  */
 function execute(&$msgFrame, &$config)
 {
     $lastError = error_get_last();
     switch ($this->invokeType) {
         case "static":
             $res = @call_user_func_array(array($this->objectOrClass, $this->method), $this->args);
             break;
         case "dataobject":
             $obj = DataObject::get_by_id($this->objectOrClass, $this->id);
             if (!$obj) {
                 throw new Exception("Can not execute non-existent Data object {$this->objectOrClass}->{$this->id}");
             }
             $res = @call_user_func_array(array($obj, $this->method), $this->args);
             break;
         case "object":
             $res = @call_user_func_array(array($this->objectOrClass, $this->method), $this->args);
             break;
         default:
             throw new Exception("Invalid method invocation type '{$this->invokeType}'");
     }
     // OK, see if there has been an error, because we have suppressed the calls with @.
     // We need to compare it with $lastError, which was the status before we made the call,
     // and only barf if the error is new. Sigh. Oh, ignore warnings and notices.
     $err = error_get_last();
     if ($err && !in_array($err['type'], self::$ignored_error_types) && (!$lastError || $err["type"] != $lastError["type"] || $err["message"] != $lastError["message"] || $err["file"] != $lastError["file"] || $err["line"] != $lastError["line"])) {
         throw new Exception("Error detected in method invocation:" . print_r($err, true));
     }
     return $res;
 }
 /**
  * @covers RegisterableDateTime::onBeforeWrite()
  */
 public function testEventDetailsChangedNotificationEmail()
 {
     $event = $this->objFromFixture('RegisterableEvent', 'event');
     $datetime = $this->objFromFixture('RegisterableDateTime', 'datetime');
     // First test that no emails are sent out for trivial changes.
     $datetime->StartTime = 0;
     $datetime->write();
     $this->assertNull($this->findEmail('*****@*****.**'));
     $this->assertNull($this->findEmail('*****@*****.**'));
     // Now do a non-emailed change and check they're still not send.
     $datetime->EndTime = '12:00:00';
     $datetime->write();
     $this->assertNull($this->findEmail('*****@*****.**'));
     $this->assertNull($this->findEmail('*****@*****.**'));
     // Now change a property that users are notified of a change in and
     // check an email is sent.
     $datetime->StartDate = '2011-01-02';
     $datetime->write();
     $this->assertEmailSent('*****@*****.**');
     $this->assertNull($this->findEmail('*****@*****.**'));
     $this->clearEmails();
     // Now disable notification and do the same and check no emails are
     // sent.
     $event->EmailNotifyChanges = false;
     $event->write();
     $datetime->StartDate = '2011-01-03';
     $datetime->flushCache();
     $datetime = DataObject::get_by_id('RegisterableDateTime', $datetime->ID);
     $datetime->write();
     $this->assertNull($this->findEmail('*****@*****.**'));
     $this->assertNull($this->findEmail('*****@*****.**'));
 }
 public function transition($request)
 {
     if (!Member::currentUserID()) {
         return Security::permissionFailure($this, _t('AdvancedWorkflowActionController.ACTION_ERROR', "You must be logged in"));
     }
     $id = $this->request->requestVar('id');
     $transition = $this->request->requestVar('transition');
     $instance = DataObject::get_by_id('WorkflowInstance', (int) $id);
     if ($instance && $instance->canEdit()) {
         $transition = DataObject::get_by_id('WorkflowTransition', (int) $transition);
         if ($transition) {
             if ($this->request->requestVar('comments')) {
                 $action = $instance->CurrentAction();
                 $action->Comment = $this->request->requestVar('comments');
                 $action->write();
             }
             singleton('WorkflowService')->executeTransition($instance->getTarget(), $transition->ID);
             $result = array('success' => true, 'link' => $instance->getTarget()->AbsoluteLink());
             if (Director::is_ajax()) {
                 return Convert::raw2json($result);
             } else {
                 return $this->redirect($instance->getTarget()->Link());
             }
         }
     }
     if (Director::is_ajax()) {
         $result = array('success' => false);
         return Convert::raw2json($result);
     } else {
         $this->redirect($instance->getTarget()->Link());
     }
 }
 /**
  * Debug method to allow manual reindexing with output via the URL 
  * /Lucene/reindex
  *
  * @access public
  * Note that this should NOT be used as a reindexing
  * process in production, as it doesn't allow for out of memory or script 
  * execution time problems.
  */
 public function reindex()
 {
     set_time_limit(600);
     $start = microtime(true);
     echo '<h1>Reindexing</h1>' . "\n";
     flush();
     echo 'Note that this process may die due to time limit or memory ' . 'exhaustion, and is purely for debugging purposes.  Use the ' . 'Queued Jobs reindex process for production indexing.' . "<br />\n<br />\n";
     flush();
     ZendSearchLuceneWrapper::getIndex(true);
     $indexable = ZendSearchLuceneWrapper::getAllIndexableObjects();
     foreach ($indexable as $item) {
         $obj = DataObject::get_by_id($item[0], $item[1]);
         if ($obj) {
             $obj_start = microtime(true);
             echo $item[0] . ' ' . $item[1] . ' (' . $obj->class . ')';
             flush();
             ZendSearchLuceneWrapper::index($obj);
             echo ' - ' . round(microtime(true) - $obj_start, 3) . ' seconds' . "<br />\n";
             flush();
         } else {
             echo 'Object ' . $item[0] . ' ' . $item[1] . ' was not found.' . "<br />\n";
             flush();
         }
     }
     echo "<br />\n" . 'Finished (' . round(microtime(true) - $start, 3) . ' seconds)' . "<br />\n";
     flush();
 }
	/**
	 * Return the link that we should redirect to.
	 * Only return a value if there is a legal redirection destination.
	 */
	function redirectionLink() {
		if($this->RedirectionType == 'External') {
			if($this->ExternalURL) {
				return Convert::raw2att($this->ExternalURL);
			}
			
		} else {
			$linkTo = $this->LinkToID ? DataObject::get_by_id("SiteTree", $this->LinkToID) : null;

			if($linkTo) {
				// We shouldn't point to ourselves - that would create an infinite loop!  Return null since we have a
				// bad configuration
				if($this->ID == $linkTo->ID) {
					return null;
			
				// If we're linking to another redirectorpage then just return the URLSegment, to prevent a cycle of redirector
				// pages from causing an infinite loop.  Instead, they will cause a 30x redirection loop in the browser, but
				// this can be handled sufficiently gracefully by the browser.
				} elseif($linkTo instanceof RedirectorPage) {
					return $linkTo->regularLink();

				// For all other pages, just return the link of the page.
				} else {
					return $linkTo->Link();
				}
			}
		}
	}
 public function handleSave(GridField $grid, DataObjectInterface $record)
 {
     $list = $grid->getList();
     $value = $grid->Value();
     if (!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) {
         // throw error ?
         return;
     }
     $updatedList = ArrayList::create();
     foreach ($value[__CLASS__] as $id => $v) {
         if (!is_numeric($id)) {
             continue;
         }
         $updatedList->push($id);
     }
     $list->exclude(['ID' => $updatedList->toArray()])->removeAll();
     foreach ($updatedList->toArray() as $i => $id) {
         // if list already contains item, leave it there
         if ($list->byID($id)) {
             continue;
         }
         $gridfieldItem = DataObject::get_by_id($list->dataClass, $id);
         if (!$gridfieldItem || !$gridfieldItem->canEdit()) {
             continue;
         }
         $list->add($gridfieldItem);
     }
 }
 /**
  * Lets process a single node, and publish it if necessary
  */
 public function process()
 {
     $remainingChildren = $this->remainingChildren;
     // if there's no more, we're done!
     if (!count($remainingChildren)) {
         $this->isComplete = true;
         return;
     }
     // we need to always increment! This is important, because if we don't then our container
     // that executes around us thinks that the job has died, and will stop it running.
     $this->currentStep++;
     // lets process our first item - note that we take it off the list of things left to do
     $ID = array_shift($remainingChildren);
     // get the page
     $page = DataObject::get_by_id('Page', $ID);
     if ($page) {
         // publish it
         $page->doPublish();
         // and add its children to the list to be published
         foreach ($page->Children() as $child) {
             $remainingChildren[] = $child->ID;
             // we increase how many steps we need to do - this means our total steps constantly rises,
             // but it gives users an idea of exactly how many more we know about
             $this->totalSteps++;
         }
         $page->destroy();
         unset($page);
     }
     // and now we store the new list of remaining children
     $this->remainingChildren = $remainingChildren;
     if (!count($remainingChildren)) {
         $this->isComplete = true;
         return;
     }
 }
 /**
  * standard SS function - we dont need to show the Wish List field in the CMS.
  */
 function updateCMSFields(&$fields)
 {
     $fields->removeByName("WishList");
     $member = Member::currentUser();
     if ($member && $member->IsAdmin()) {
         $html = "";
         $array = unserialize($this->owner->WishList);
         $links = array();
         if (is_array($array) && count($array)) {
             foreach ($array as $item) {
                 $object = DataObject::get_by_id($item[0], $item[1]);
                 if ($object) {
                     $links[] = "<a href=\"" . $object->Link() . "\">" . $object->Title . "</a>";
                 } else {
                     $links[] = "error in retrieving object " . implode(", ", $item);
                 }
             }
         } else {
             $links[] = "no items on wishlist";
         }
         $html = "<ul><li>" . implode("</li><li>", $links) . "</li></ul>";
         $field = new LiteralField("WishListOverview", $html);
         $fields->addFieldToTab("Root.WishList", $field);
     } else {
         $fields->removeByName("WishList");
     }
 }
Example #22
0
	/**
	 * Return this field's linked items
	 */
	function getItems() {
		// If the value has been set, use that
		if($this->value != 'unchanged' && is_array($this->sourceObject)) {
			$items = array();
			$values = is_array($this->value) ? $this->value : preg_split('/ *, */', trim($this->value));
			foreach($values as $value) {
				$item = new stdClass;
				$item->ID = $value;
				$item->Title = $this->sourceObject[$value];
				$items[] = $item;
			}
			return $items;
			
		// Otherwise, look data up from the linked relation
		} if($this->value != 'unchanged' && is_string($this->value)) {
			$items = new ArrayList();
			$ids = explode(',', $this->value);
			foreach($ids as $id) {
				if(!is_numeric($id)) continue;
				$item = DataObject::get_by_id($this->sourceObject, $id);
				if($item) $items->push($item);
			}
			return $items;
		} else if($this->form) {
			$fieldName = $this->name;
			$record = $this->form->getRecord();
			if(is_object($record) && $record->hasMethod($fieldName)) 
				return $record->$fieldName();
		}	
	}
Example #23
0
 public function tearDown()
 {
     if ($this->origBackend) {
         Image::set_backend($this->origBackend);
     }
     // Remove the test files that we've created
     $fileIDs = $this->allFixtureIDs('Image');
     foreach ($fileIDs as $fileID) {
         $file = DataObject::get_by_id('Image', $fileID);
         if ($file && file_exists(BASE_PATH . "/{$file->Filename}")) {
             unlink(BASE_PATH . "/{$file->Filename}");
         }
     }
     // Remove the test folders that we've created
     $folderIDs = $this->allFixtureIDs('Folder');
     foreach ($folderIDs as $folderID) {
         $folder = DataObject::get_by_id('Folder', $folderID);
         if ($folder && file_exists(BASE_PATH . "/{$folder->Filename}")) {
             Filesystem::removeFolder(BASE_PATH . "/{$folder->Filename}");
         }
         if ($folder && file_exists(BASE_PATH . "/" . $folder->Filename . "_resampled")) {
             Filesystem::removeFolder(BASE_PATH . "/" . $folder->Filename . "_resampled");
         }
     }
     parent::tearDown();
 }
 function run($request)
 {
     $orderItemSingleton = singleton('OrderItem');
     $query = $orderItemSingleton->buildSQL("\"Quantity\" > 0");
     $select = $query->select;
     $select['NewNumberSold'] = self::$number_sold_calculation_type . "(\"OrderItem\".\"Quantity\") AS \"NewNumberSold\"";
     $query->select($select);
     $query->groupby("\"BuyableClassName\", \"BuyableID\" ");
     $query->orderby("\"BuyableClassName\", \"BuyableID\" ");
     //$q->leftJoin('OrderItem','"Product"."ID" = "OrderItem"."BuyableID"');
     //$q->where("\"OrderItem\".\"BuyableClassName\" = 'Product'");
     $records = $query->execute();
     $orderItems = $orderItemSingleton->buildDataObjectSet($records, "DataObjectSet", $query, 'OrderItem');
     if ($orderItems) {
         foreach ($orderItems as $orderItem) {
             if (!$orderItem->NewNumberSold) {
                 $orderItem->NewNumberSold = 0;
             }
             $buyable = DataObject::get_by_id($orderItem->BuyableClassName, $orderItem->BuyableID);
             if ($buyable) {
                 if ($orderItem->NewNumberSold != $buyable->NumberSold) {
                     $buyable->NumberSold = $orderItem->NewNumberSold;
                     if ($buyable instanceof SiteTree) {
                     }
                 }
             } else {
                 DB::alteration_message("could not find " . $orderItem->BuyableClassName . "." . $orderItem->BuyableID . " ... ", "deleted");
             }
         }
     }
 }
 public function processRecord($record, $columnMap, &$results, $preview = false)
 {
     // Get Current Object
     $objID = parent::processRecord($record, $columnMap, $results, $preview);
     $object = DataObject::get_by_id($this->objectClass, $objID);
     $this->extend("onBeforeProcess", $object, $record, $columnMap, $results, $preview);
     // Loop through all fields and setup associations
     foreach ($record as $key => $value) {
         // Find any categories (denoted by a 'CategoryXX' column)
         if (strpos($key, 'Category') !== false) {
             $category = CatalogueCategory::get()->filter("Title", $value)->first();
             if ($category) {
                 $object->Categories()->add($category);
             }
         }
         // Find any Images (denoted by a 'ImageXX' column)
         if (strpos($key, 'Image') !== false && $key != "Images") {
             $image = Image::get()->filter("Name", $value)->first();
             if ($image) {
                 $object->Images()->add($image);
             }
         }
         // Find any related products (denoted by a 'RelatedXX' column)
         if (strpos($key, 'Related') !== false && $key != "RelatedProducts") {
             $product = Product::get()->filter("StockID", $value)->first();
             if ($product) {
                 $object->RelatedProducts()->add($product);
             }
         }
     }
     $this->extend("onAfterProcess", $object, $record, $columnMap, $results, $preview);
     $object->destroy();
     unset($object);
     return $objID;
 }
 /**
  * This function is an extension of the default SiteTree canView(), and allows viewing permissions for a SiteTree
  * object which has allowed a page to be presented to logged in users. With RealMe a logged in user is a user
  * which has authenticated with the identity provider, and we have stored a FLT in session.
  *
  * Return true, if the CanViewType is LoggedInUsers, and we have a valid RealMe Session authenticated.
  *
  * @param Member|int $member
  *
  * @return bool True if the current user can view this page
  */
 public function canView($member)
 {
     switch ($this->owner->CanViewType) {
         case 'Anyone':
             return true;
         case 'Inherit':
             if ($this->owner->ParentID) {
                 return $this->owner->Parent()->canView($member);
             }
             return $this->owner->getSiteConfig()->canViewPages($member);
         case 'LoggedInUsers':
             // check for any logged-in RealMe Sessions
             $data = $this->service->getUserData();
             if (!is_null($data)) {
                 return true;
             }
             if ($member && is_numeric($member)) {
                 return true;
             }
             return false;
         case 'OnlyTheseUsers':
             if ($member && is_numeric($member)) {
                 $member = DataObject::get_by_id('Member', $member);
                 /** @var Member $member */
                 if ($member && $member->inGroups($this->owner->ViewerGroups())) {
                     return true;
                 }
             }
     }
     return false;
 }
 public function Form()
 {
     $fields = new FieldList();
     $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/pages/edit/show/%d">%s</a> <small>(#%d, Last Modified Date: %s, Last Modifier: %s, %s)</small>', $orphan->ID, $orphan->Title, $orphan->ID, Date::create($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 FieldList(new FormAction('doSubmit', _t('RemoveOrphanedPagesTask.BUTTONRUN', 'Run'))));
     if (!$orphans || !$orphans->Count()) {
         $form->makeReadonly();
     }
     return $form;
 }
 public function processRecord($record, $columnMap, &$results, $preview = false)
 {
     // We match by 'Code', the ID property is confusing the importer
     if (isset($record['ID'])) {
         unset($record['ID']);
     }
     $objID = parent::processRecord($record, $columnMap, $results, $preview);
     $group = DataObject::get_by_id($this->objectClass, $objID);
     // set group hierarchies - we need to do this after all records
     // are imported to avoid missing "early" references to parents
     // which are imported later on in the CSV file.
     if (isset($record['ParentCode']) && $record['ParentCode']) {
         $parentGroup = DataObject::get_one('Group', array('"Group"."Code"' => $record['ParentCode']));
         if ($parentGroup) {
             $group->ParentID = $parentGroup->ID;
             $group->write();
         }
     }
     // set permission codes - these are all additive, meaning
     // existing permissions arent cleared.
     if (isset($record['PermissionCodes']) && $record['PermissionCodes']) {
         foreach (explode(',', $record['PermissionCodes']) as $code) {
             $p = DataObject::get_one('Permission', array('"Permission"."Code"' => $code, '"Permission"."GroupID"' => $group->ID));
             if (!$p) {
                 $p = new Permission(array('Code' => $code));
                 $p->write();
             }
             $group->Permissions()->add($p);
         }
     }
     return $objID;
 }
Example #29
0
 public function testSQLInsert()
 {
     $object1 = DataObject::get_by_id("YamlFixtureTest_DataObject", $this->idFromFixture("YamlFixtureTest_DataObject", "testobject1"));
     $this->assertTrue($object1->ManyMany()->Count() == 2, "Should be 2 items in this manymany relationship");
     $object2 = DataObject::get_by_id("YamlFixtureTest_DataObject", $this->idFromFixture("YamlFixtureTest_DataObject", "testobject2"));
     $this->assertTrue($object2->ManyMany()->Count() == 2, "Should be 2 items in this manymany relationship");
 }
	public function run($request) {
		$pages = 0;
		$links = 0;

		$linkedPages = new DataList('SiteTree');
		$linkedPages->innerJoin('SiteTree_LinkTracking', '"SiteTree_LinkTracking"."SiteTreeID" = "SiteTree"."ID"');
		if($linkedPages) foreach($linkedPages as $page) {
			$tracking = DB::query(sprintf('SELECT "ChildID", "FieldName" FROM "SiteTree_LinkTracking" WHERE "SiteTreeID" = %d', $page->ID))->map();

			foreach($tracking as $childID => $fieldName) {
				$linked = DataObject::get_by_id('SiteTree', $childID);
				
				// TOOD: Replace in all HTMLText fields
				$page->Content = preg_replace (
					"/href *= *([\"']?){$linked->URLSegment}\/?/i",
					"href=$1[sitetree_link id={$linked->ID}]",
					$page->Content,
					-1,
					$replaced
				);
				
				if($replaced) {
					$links += $replaced;
				}
			}
			
			$page->write();
			$pages++;
		}
		
		echo "Rewrote $links link(s) on $pages page(s) to use shortcodes.\n";
	}