Example #1
0
 /**
  * Add a member to a group.
  *
  * @param DataObject $member
  * @param string $groupcode
  */
 static function addToGroupByName($member, $groupcode)
 {
     $group = DataObject::get_one('Group', "Code = '" . Convert::raw2sql($groupcode) . "'");
     if ($group) {
         $member->Groups()->add($group);
         $member->write();
     }
 }
 function saveInto(DataObject $record)
 {
     $fieldName = $this->name;
     $fieldNameID = $fieldName . 'ID';
     $record->{$fieldNameID} = 0;
     if ($val = $this->value[$this->htmlListField]) {
         if ($val != 'undefined') {
             $record->{$fieldNameID} = $val;
         }
     }
     $record->write();
 }
 /**
  * record points in order object
  * or in case this is not selected, it will send a message to the shop admin only
  * The latter is useful in case the payment does not go through (and no receipt is received).
  * @param DataObject $order Order
  * @return Boolean
  **/
 public function doStep($order)
 {
     if (!DataObject::get_one("OrderStep_RecordPoints_Log", "\"OrderID\" = " . $order->ID)) {
         if ($order->PointsTotal == 0) {
             $order->PointsTotal = $order->CalculatePointsTotal();
         }
         if ($order->RewardsTotal == 0) {
             $order->RewardsTotal = $order->CalculateRewardsTotal();
         }
         $order->write();
         $log = new OrderStep_RecordPoints_Log();
         $log->PointsTotal = $order->PointsTotal;
         $log->RewardsTotal = $order->RewardsTotal;
         $log->OrderID = $order->ID;
         $log->MemberID = $order->MemberID;
         $log->write();
     }
     return true;
 }
 /**
  * @param \DataObject $object
  * @param Field $field
  * @throws \ValidationException
  * @throws null
  */
 public function write(\DataObject $object, Field $field)
 {
     if ($object->has_extension('Versioned')) {
         $object->writeToStage('Stage');
         $args = $field->options;
         $publish = isset($args['publish']) ? $args['publish'] : true;
         if ($publish) {
             $object->publish('Stage', 'Live');
         }
     } else {
         $object->write();
     }
     if (!$object->isSeeded()) {
         $seed = new \SeedRecord();
         $seed->SeedClassName = $object->ClassName;
         $seed->SeedID = $object->ID;
         $seed->Key = $field->key;
         $seed->Root = $field->fieldType === Field::FT_ROOT;
         $seed->write();
         $object->setIsSeeded();
     }
 }
 function doSave($data, $form)
 {
     $new_record = $this->record->ID == 0;
     $controller = Controller::curr();
     try {
         $form->saveInto($this->record);
         $this->record->write();
         $this->gridField->getList()->add($this->record);
     } catch (ValidationException $e) {
         $form->sessionMessage($e->getResult()->message(), 'bad');
         $responseNegotiator = new PjaxResponseNegotiator(array('CurrentForm' => function () use(&$form) {
             return $form->forTemplate();
         }, 'default' => function () use(&$controller) {
             return $controller->redirectBack();
         }));
         if ($controller->getRequest()->isAjax()) {
             $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
         }
         return $responseNegotiator->respond($controller->getRequest());
     }
     // TODO Save this item into the given relationship
     $message = sprintf(_t('GridFieldDetailForm.Saved', 'Saved %s %s'), $this->record->singular_name(), '<a href="' . $this->Link('edit') . '">"' . htmlspecialchars($this->record->Title, ENT_QUOTES) . '"</a>');
     $form->sessionMessage($message, 'good');
     if ($new_record) {
         return Controller::curr()->redirect($this->Link());
     } elseif ($this->gridField->getList()->byId($this->record->ID)) {
         // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
         // to the same URL (it assumes that its content is already current, and doesn't reload)
         return $this->edit(Controller::curr()->getRequest());
     } else {
         // Changes to the record properties might've excluded the record from
         // a filtered list, so return back to the main view if it can't be found
         $noActionURL = $controller->removeAction($data['url']);
         $controller->getRequest()->addHeader('X-Pjax', 'Content');
         return $controller->redirect($noActionURL, 302);
     }
 }
 private function write(DataObject $dataObject)
 {
     Versioned::reading_stage('Stage');
     $dataObject->write();
     if ($dataObject instanceof SiteTree) {
         $dataObject->publish('Stage', 'Live');
     }
     Versioned::reading_stage('Live');
 }
 /**
  * Updates the Upload/Attach response from the UploadField
  * with the new DataObject records for the JS template
  * 
  * @param  DataObject $record Newly create DataObject record
  * @param  array $uploadResponse Upload or Attach response from UploadField
  * @return array                 Updated $uploadResponse with $record data
  */
 protected function newRecordJSTemplateData(DataObject &$record, &$uploadResponse)
 {
     // fetch uploadedFile record and sort out previewURL
     // update $uploadResponse datas in case changes happened onAfterWrite()
     $uploadedFile = DataObject::get_by_id($this->component->getFileRelationClassName($this->gridField), $uploadResponse['id']);
     if ($uploadedFile) {
         $uploadResponse['name'] = $uploadedFile->Name;
         $uploadResponse['url'] = $uploadedFile->getURL();
         if ($uploadedFile instanceof Image) {
             $uploadResponse['thumbnail_url'] = $uploadedFile->CroppedImage(30, 30)->getURL();
         } else {
             $uploadResponse['thumbnail_url'] = $uploadedFile->Icon();
         }
         // check if our new record has a Title, if not create one automatically
         $title = $record->getTitle();
         if (!$title || $title === $record->ID) {
             if ($record->hasDatabaseField('Title')) {
                 $record->Title = $uploadedFile->Title;
                 $record->write();
             } else {
                 if ($record->hasDatabaseField('Name')) {
                     $record->Name = $uploadedFile->Title;
                     $record->write();
                 }
             }
         }
     }
     // Collect all data for JS template
     $return = array_merge($uploadResponse, array('record' => array('id' => $record->ID)));
     return $return;
 }
 public function write()
 {
     SS_Log::log("Write Iteration " . $this->getWriteCount(), SS_Log::NOTICE);
     $cf = $this->getOriginalChangedFields();
     // Only Do 'Email Already Exists' Check If E-mail Has Changed
     if (isset($cf["Email"])) {
         // Check If The Updated E-mail Is In Use
         $dl = new DataList("MCSubscription");
         // DO Include Unsubscribed List Members As listSubscribe() Using An E-mail Address Still In The List (Even Unsubscribed From It) Errors
         $duplicate = $dl->where("\"MCListID\" = '" . $this->MCListID . "' && LOWER(\"Email\") = '" . strtolower($this->Email) . "' && \"ID\" != '" . $this->ID . "'")->first();
         if (!empty($duplicate)) {
             $this->setOriginalChangedFields($cf);
             // Store Original (First Write) Change Fields For Use On Second Write
             $vr = new ValidationResult(false, "Error: This E-mail Is Already In Use Within This List!");
             throw new ValidationException($vr);
         }
     }
     // Ensure the MCSubscription object is always written twice as it is
     // the second write (for components) where our MCSync logic is called
     if ($this->getWriteCount() < 2) {
         $this->setForceAdditionalWrite(true);
     }
     if ($this->getForceAdditionalWrite()) {
         // If an additional write is being forced, ensure that DataObject::write()
         // doesnt decide nothing needs saving and fails to call onAfterWrite()
         $this->DummyField = time();
     }
     parent::write();
     // Do E-mail Comparison and related member setting AFTER 1st Write
     // Otherwise, when saving existing subscriptions, we Can Have All
     // Subscriber Data Fields (inc Forign Key Fields) Writen on the 1st Write,
     // Meaning when the second write() for components occours, DataObject::write()
     // determins that nothing on the record has changed and does not call
     // onAfterWrite() on the second write itteration meaning the MailChimp
     // Sync Logic Never Fires
     if (isset($cf["Email"])) {
         // Check For Related Member E-mails and Link to Member If Found
         $dl = new DataList("Member");
         $relatedMember = $dl->where("LOWER(\"Email\") = '" . strtolower($this->Email) . "'")->first();
         if (!empty($relatedMember->ID)) {
             $this->setField("MemberID", $relatedMember->ID);
         }
     }
 }
Example #9
0
 /**
  * Writes an object in a certain language. Use this instead of $object->write() if you want to write
  * an instance in a determinated language independently of the currently set working language
  *
  * @param DataObject $object Object to be written
  * @param string $lang The name of the language
  */
 static function write(DataObject $object, $lang)
 {
     $oldLang = self::current_lang();
     self::set_reading_lang($lang);
     $result = $object->write();
     self::set_reading_lang($oldLang);
 }
 /**
  * Converts either the given HTTP Body into an array
  * (based on the DataFormatter instance), or returns
  * the POST variables.
  * Automatically filters out certain critical fields
  * that shouldn't be set by the client (e.g. ID).
  *
  * @param DataObject $obj
  * @param DataFormatter $formatter
  * @return DataObject The passed object
  */
 protected function updateDataObject($obj, $formatter)
 {
     // if neither an http body nor POST data is present, return error
     $body = $this->request->getBody();
     if (!$body && !$this->request->postVars()) {
         $this->getResponse()->setStatusCode(204);
         // No Content
         return 'No Content';
     }
     if (!empty($body)) {
         $data = $formatter->convertStringToArray($body);
     } else {
         // assume application/x-www-form-urlencoded which is automatically parsed by PHP
         $data = $this->request->postVars();
     }
     // @todo Disallow editing of certain keys in database
     $data = array_diff_key($data, array('ID', 'Created'));
     $apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
     if (is_array($apiAccess) && isset($apiAccess['edit'])) {
         $data = array_intersect_key($data, array_combine($apiAccess['edit'], $apiAccess['edit']));
     }
     $obj->update($data);
     $obj->write();
     return $obj;
 }
 /**
  * Writes the given language object
  *
  * @param DataObject $languageObj Language object to write
  * @param array      $mainRecord  Main record data of the multilingual DataObject
  *
  * @return void 
  * 
  * @author Roland Lehmann <*****@*****.**>
  * @since 04.01.2012
  */
 public static function writeLanguageObject($languageObj, $mainRecord)
 {
     $record = array();
     foreach ($languageObj->db() as $dbFieldName => $dbFieldType) {
         if (array_key_exists($dbFieldName, $mainRecord)) {
             $record[$dbFieldName] = $mainRecord[$dbFieldName];
         }
     }
     $languageObj->update($record);
     $languageObj->write();
 }
 /**
  * Update all has_ones that are linked to assets
  *
  * @param \DataObject $localObject
  * @param \ArrayData $remoteObject
  * @return null
  */
 protected function updateLocaleAssetRelations(\DataObject $localObject, \ArrayData $remoteObject)
 {
     // Now update all has_one => file relations
     $changed = false;
     $relations = $localObject->has_one();
     if (empty($relations)) {
         $this->task->message(" ** No has_ones on {$localObject->Title}", 2);
         return;
     }
     foreach ($relations as $relation => $class) {
         $this->task->message(" *** Checking relation name {$relation}", 3);
         // Link file
         if (!ImportHelper::is_a($class, 'File')) {
             $this->task->message(" **** {$relation} is not a File", 4);
             continue;
         }
         // Don't link folders
         if (ImportHelper::is_a($class, 'Folder')) {
             $this->task->message(" **** {$relation} is a folder", 4);
             continue;
         }
         // No need to import if found in a previous step
         $field = $relation . "ID";
         if ($localObject->{$field}) {
             $this->task->message(" **** {$relation} already has value {$localObject->{$field}} on local object", 4);
             continue;
         }
         // If the remote object doesn't have this field then can also skip it
         $remoteFileID = intval($remoteObject->{$field});
         if (empty($remoteFileID)) {
             $this->task->message(" **** {$relation} has no value on remote object", 4);
             continue;
         }
         // Find remote file with this ID
         $remoteFile = $this->findRemoteFile(array(sprintf('"ID" = %d', intval($remoteFileID))));
         if (!$remoteFile) {
             $this->task->error("Could not find {$relation} file with id {$remoteFileID}");
             continue;
         }
         // Ensure that this file has a valid name
         if (!$this->isValidFile($remoteFile->Name)) {
             $this->task->error("Remote {$relation} file does not have a valid name '" . $remoteFile->Name . "'");
             continue;
         }
         // Copy file to filesystem and save
         $localFile = $this->findOrImportFile($remoteFile);
         if (!$localFile) {
             $this->task->error("Failed to import {$relation} file '" . $remoteFile->Name . "'");
             continue;
         }
         // Save new file
         $changed = true;
         $this->task->message(" *** {$relation} assigned local value {$localFile->ID}", 3);
         $localObject->{$field} = $localFile->ID;
     }
     if ($changed) {
         $localObject->write();
     } else {
         $this->task->message(" ** No changes made to relations on {$localObject->Title}", 2);
     }
 }
	/**
	 * Saves the data in this form field into a database record.
	 *
	 * @param DataObject $record The record being updated by the form
	 */
	public function saveInto(DataObject $record) {
		// Can't do has_many without a parent id
		if(!$record->isInDB()) {
			$record->write();
		}
		if(!$file_class = $this->getFileClass($record)) {
			return false;
		}
		if(isset($_REQUEST[$this->name]) && is_array($_REQUEST[$this->name])) {
			if($relation_name = $this->getForeignRelationName($record)) {
				// Null out all the existing relations and reset.
				$currentComponentSet = $record->{$this->name}();
				$currentComponentSet->removeAll();
				// Assign all the new relations (may have already existed)
				foreach($_REQUEST[$this->name] as $id) {
					if($file = DataObject::get_by_id($this->baseFileClass, $id)) {
						$new = ($file_class != $this->baseFileClass) ? $file->newClassInstance($file_class) : $file;
						$new->write();
						$currentComponentSet->add($new);
					}
				}
			}
		}		
	}
 public function write()
 {
     $id = parent::write();
     foreach (json_decode(SS_LANGUAGES) as $slang => $lang) {
         if (isset($this->record['Title-' . $slang])) {
             $existingTrans = BlockTranslation::get()->filter(['BlockID' => $id, 'Language' => $slang])->first();
             $trans = ['Language' => $slang];
             foreach ($this->record as $key => $value) {
                 if (strpos($key, $slang) !== false) {
                     $key = explode('-', $key);
                     $trans[$key[0]] = $value;
                 }
             }
             if ($existingTrans) {
                 DB::query('UPDATE "BlockTranslation" SET "Title"=\'' . $trans['Title'] . '\', "Content"=\'' . pg_escape_string($trans['Content']) . '\' WHERE "ID" = ' . $existingTrans->ID . ';');
             } else {
                 $newTrans = BlockTranslation::create();
                 $newTrans->Title = $trans['Title'];
                 $newTrans->Content = $trans['Content'];
                 $newTrans->Language = $slang;
                 $newTrans->BlockID = $id;
                 $newTrans->write();
             }
         }
     }
 }
Example #15
0
 function doSave($data, $form)
 {
     $new_record = $this->record->ID == 0;
     try {
         $form->saveInto($this->record);
         $this->record->write();
         $this->gridField->getList()->add($this->record);
     } catch (ValidationException $e) {
         $form->sessionMessage($e->getResult()->message(), 'bad');
         return Controller::curr()->redirectBack();
     }
     // TODO Save this item into the given relationship
     $message = sprintf(_t('GridFieldDetailForm.Saved', 'Saved %s %s'), $this->record->singular_name(), '<a href="' . $this->Link('edit') . '">"' . htmlspecialchars($this->record->Title, ENT_QUOTES) . '"</a>');
     $form->sessionMessage($message, 'good');
     return Controller::curr()->redirect($this->Link());
 }
 /**
  * Vote for a particular post
  * 
  * @param DataObject $post 
  */
 public function vote(DataObject $post, $dir = 1)
 {
     $member = $this->securityContext->getMember();
     if ($member->VotesToGive <= 0) {
         $post->RemainingVotes = 0;
         return $post;
     }
     // we allow multiple votes - as many as the user has to give! unless
     // configured not to...
     $currentVote = null;
     if ($this->singleVotes) {
         $votes = $post->currentVotesByUser();
         if (count($votes)) {
             $currentVote = $votes[0];
         }
     }
     if (!$currentVote) {
         $currentVote = MicroPostVote::create();
         $currentVote->UserID = $member->ID;
         $currentVote->PostID = $post->ID;
     }
     $currentVote->Direction = $dir > 0 ? 1 : -1;
     $currentVote->write();
     $list = DataList::create('MicroPostVote');
     $upList = $list->filter(array('PostID' => $post->ID, 'Direction' => 1));
     $post->Up = $upList->count();
     $downList = $list->filter(array('PostID' => $post->ID, 'Direction' => -1));
     $post->Down = $downList->count();
     $owner = $post->Owner();
     if (!$post->OwnerID || !$owner || !$owner->exists()) {
         $owner = Security::findAnAdministrator();
     }
     // write the post as the owner, and calculate some changes for the author
     $this->transactionManager->run(function () use($post, $currentVote, $member) {
         $author = $post->Owner();
         if ($author && $author->exists() && $author->ID != $member->ID) {
             if ($currentVote->Direction > 0) {
                 $author->Up += 1;
             } else {
                 $author->Down += 1;
             }
             $author->write();
         }
         $post->write();
     }, $owner);
     $this->rewardMember($member, -1);
     $post->RemainingVotes = $member->VotesToGive;
     return $post;
 }
 /**
  * Loads the given form data into the underlying dataobject and relation
  *
  * @param array $data
  * @param Form $form
  * @throws ValidationException On error
  * @return DataObject Saved record
  */
 protected function saveFormIntoRecord($data, $form)
 {
     $list = $this->gridField->getList();
     // Check object matches the correct classname
     if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
         $newClassName = $data['ClassName'];
         // The records originally saved attribute was overwritten by $form->saveInto($record) before.
         // This is necessary for newClassInstance() to work as expected, and trigger change detection
         // on the ClassName attribute
         $this->record->setClassName($this->record->ClassName);
         // Replace $record with a new instance
         $this->record = $this->record->newClassInstance($newClassName);
     }
     // Save form and any extra saved data into this dataobject
     $form->saveInto($this->record);
     $this->record->write();
     $extraData = $this->getExtraSavedData($this->record, $list);
     $list->add($this->record, $extraData);
     return $this->record;
 }
 /**
  * Notes identification between two records
  *
  * Does NOT mark the remote record as _ImportedDate = current
  *
  * @param DataObject $localRecord
  * @param ArrayData $remoteRecord
  * @param bool $markImported True if should set the _ImportedDate to NOW(). Default to false because
  * sometimes we just want to identify a record, not update it at the same time.
  */
 protected function identifyRecords($localRecord, $remoteRecord, $markImported = false)
 {
     // Given the newly matched item save it
     $localRecord->LegacyID = $remoteRecord->ID;
     $localRecord->write();
     // Match remote object to this
     $conn = $this->task->getRemoteConnection();
     $baseTable = $this->getRemoteBaseTable();
     $query = $markImported ? 'UPDATE "%s" SET "_ImportedID" = %d, "_ImportedDate" = NOW() WHERE "ID" = %d' : 'UPDATE "%s" SET "_ImportedID" = %d WHERE "ID" = %d';
     $conn->query(sprintf($query, $baseTable, intval($localRecord->ID), intval($remoteRecord->ID)));
 }
Example #19
0
 public function doSave($data, $form)
 {
     $new_record = $this->record->ID == 0;
     $controller = $this->getToplevelController();
     $list = $this->gridField->getList();
     if ($list instanceof ManyManyList) {
         // Data is escaped in ManyManyList->add()
         $extraData = isset($data['ManyMany']) ? $data['ManyMany'] : null;
     } else {
         $extraData = null;
     }
     if (!$this->record->canEdit()) {
         return $controller->httpError(403);
     }
     if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
         $newClassName = $data['ClassName'];
         // The records originally saved attribute was overwritten by $form->saveInto($record) before.
         // This is necessary for newClassInstance() to work as expected, and trigger change detection
         // on the ClassName attribute
         $this->record->setClassName($this->record->ClassName);
         // Replace $record with a new instance
         $this->record = $this->record->newClassInstance($newClassName);
     }
     try {
         $form->saveInto($this->record);
         $this->record->write();
         $list->add($this->record, $extraData);
     } catch (ValidationException $e) {
         $form->sessionMessage($e->getResult()->message(), 'bad', false);
         $responseNegotiator = new PjaxResponseNegotiator(array('CurrentForm' => function () use(&$form) {
             return $form->forTemplate();
         }, 'default' => function () use(&$controller) {
             return $controller->redirectBack();
         }));
         if ($controller->getRequest()->isAjax()) {
             $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
         }
         return $responseNegotiator->respond($controller->getRequest());
     }
     // TODO Save this item into the given relationship
     $link = '<a href="' . $this->Link('edit') . '">"' . htmlspecialchars($this->record->Title, ENT_QUOTES) . '"</a>';
     $message = _t('GridFieldDetailForm.Saved', 'Saved {name} {link}', array('name' => $this->record->i18n_singular_name(), 'link' => $link));
     $form->sessionMessage($message, 'good', false);
     if ($new_record) {
         return $controller->redirect($this->Link());
     } elseif ($this->gridField->getList()->byId($this->record->ID)) {
         // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
         // to the same URL (it assumes that its content is already current, and doesn't reload)
         return $this->edit($controller->getRequest());
     } else {
         // Changes to the record properties might've excluded the record from
         // a filtered list, so return back to the main view if it can't be found
         $noActionURL = $controller->removeAction($data['url']);
         $controller->getRequest()->addHeader('X-Pjax', 'Content');
         return $controller->redirect($noActionURL, 302);
     }
 }
 /**
  * Saves the form data into a record. Nulls out all of the existing file relationships
  * and rebuilds them, in order to accommodate any deletions.
  *
  * @param DataObject $record The record associated with the parent form
  * 
  * @See Modified for pull request by Micah Sheets to add manymanysortable
  */
 public function saveInto(DataObject $record)
 {
     // Can't do has_many without a parent id
     if (!$record->isInDB()) {
         $record->write();
     }
     if (!($file_class = $this->getFileClass($record))) {
         return false;
     }
     // Null out all the existing relations and reset.
     $currentComponentSet = $record->{$this->name}();
     $currentComponentSet->removeAll();
     if (isset($_REQUEST[$this->name]) && is_array($_REQUEST[$this->name])) {
         if ($relation_name = $this->getForeignRelationName($record)) {
             // Assign all the new relations (may have already existed)
             $data = $_REQUEST;
             for ($count = 0; $count < count($data[$this->name]); ++$count) {
                 $id = $data[$this->name][$count];
                 $sort = $data['sort'][$count];
                 if ($file = DataObject::get_by_id("File", $id)) {
                     $new = $file_class != "File" ? $file->newClassInstance($file_class) : $file;
                     $new->write();
                     $currentComponentSet->add($new, array('ManyManySort' => $sort));
                 }
             }
         }
     }
 }