public function saveInto(DataObject $record) { if (!isset($_FILES[$this->name])) { return false; } if ($this->relationAutoSetting) { // assume that the file is connected via a has-one $hasOnes = $record->has_one($this->name); // try to create a file matching the relation $file = is_string($hasOnes) ? Object::create($hasOnes) : new File(); } else { $file = new File(); } $this->upload->loadIntoFile($_FILES[$this->name], $file, $this->folderName); if ($this->upload->isError()) { return false; } $file = $this->upload->getFile(); if ($this->relationAutoSetting) { if (!$hasOnes) { return false; } // save to record $record->{$this->name . 'ID'} = $file->ID; } }
public function saveInto(DataObjectInterface $record) { if (!isset($_FILES[$this->name])) { return false; } $fileClass = File::get_class_for_file_extension(pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION)); if ($this->relationAutoSetting) { // assume that the file is connected via a has-one $hasOnes = $record->has_one($this->name); // try to create a file matching the relation $file = is_string($hasOnes) ? Object::create($hasOnes) : new $fileClass(); } else { $file = new $fileClass(); } $this->upload->loadIntoFile($_FILES[$this->name], $file, $this->folderName); if ($this->upload->isError()) { return false; } $file = $this->upload->getFile(); if ($this->relationAutoSetting) { if (!$hasOnes) { return false; } // save to record $record->{$this->name . 'ID'} = $file->ID; } return $this; }
public function handleswfupload() { if (isset($_FILES["swfupload_file"]) && is_uploaded_file($_FILES["swfupload_file"]["tmp_name"])) { $file = new File(); $u = new Upload(); $u->loadIntoFile($_FILES['swfupload_file'], $file, "Resumes"); $file->write(); echo $file->ID; } else { echo ' '; // return something or SWFUpload won't fire uploadSuccess } }
public function index(SS_HTTPRequest $r) { if(isset($_FILES["Filedata"]) && is_uploaded_file($_FILES["Filedata"]["tmp_name"])) { $upload_folder = urldecode($r->requestVar('uploadFolder')); if(isset($_REQUEST['FolderID'])) { if($folder = DataObject::get_by_id("Folder", Convert::raw2sql($_REQUEST['FolderID']))) { $upload_folder = UploadifyField::relative_asset_dir($folder->Filename); } } $ext = strtolower(end(explode('.', $_FILES['Filedata']['name']))); $class = in_array($ext, UploadifyField::$image_extensions) ? $r->requestVar('imageClass') : $r->requestVar('fileClass'); $file = new $class(); $u = new Upload(); $u->loadIntoFile($_FILES['Filedata'], $file, $upload_folder); $file->write(); echo $file->ID; } else { echo ' '; // return something or SWFUpload won't fire uploadSuccess } }
function doUpload($data, $form) { if (isset($data['UploadedMedia']['tmp_name'])) { if (!empty($data['UploadedMedia']['name'])) { // create new single file array from file uploads array $file = array(); $file['name'] = $data['UploadedMedia']['name']; $file['type'] = $data['UploadedMedia']['type']; $file['tmp_name'] = $data['UploadedMedia']['tmp_name']; $file['error'] = $data['UploadedMedia']['error']; $file['size'] = $data['UploadedMedia']['size']; // create & write uploaded file in DB try { $newfile = new File(); $upload = new Upload(); // get folder from form upload field $folder = $form->Fields()->fieldByName('UploadedMedia')->getFolderName(); $upload->loadIntoFile($file, $newfile, $folder); $fileObj = $upload->getFile(); $EventID = Session::get('UploadMedia.PresentationID'); if ($EventID) { $Event = VideoPresentation::get()->byID($EventID); } if (isset($Event)) { $Event->UploadedMediaID = $fileObj->ID; $Event->MediaType = 'File'; $Event->write(); Session::set('UploadMedia.Success', TRUE); Session::set('UploadMedia.FileName', $fileObj->Name); Session::set('UploadMedia.Type', 'File'); Controller::curr()->redirect($form->controller()->link() . 'Success'); } } catch (ValidationException $e) { $form->sessionMessage('Extension not allowed...', 'bad'); return $this->controller()->redirectBack(); } } } }
public function saveInto(DataObjectInterface $record) { if (!isset($_FILES[$this->name])) { return false; } $fileClass = File::get_class_for_file_extension(File::get_file_extension($_FILES[$this->name]['name'], PATHINFO_EXTENSION)); if ($this->relationAutoSetting) { // assume that the file is connected via a has-one $objectClass = $record->hasOne($this->name); if ($objectClass === 'File' || empty($objectClass)) { // Create object of the appropriate file class $file = Object::create($fileClass); } else { // try to create a file matching the relation $file = Object::create($objectClass); } } else { if ($record instanceof File) { $file = $record; } else { $file = Object::create($fileClass); } } $this->upload->loadIntoFile($_FILES[$this->name], $file, $this->getFolderName()); if ($this->upload->isError()) { return false; } if ($this->relationAutoSetting) { if (!$objectClass) { return false; } $file = $this->upload->getFile(); $record->{$this->name . 'ID'} = $file->ID; } return $this; }
public function imageupload() { if (!Member::currentUserID()) { $return = array('error' => 1, 'text' => "Cannot upload there"); return Convert::raw2json($return); } if (isset($_FILES['NewImage']) && ($tempfile = $_FILES['NewImage'])) { // validate // $allowed = array('jpg', 'jpeg', 'gif', 'png', 'ico'); $nameBits = explode('.', $tempfile['name']); $ext = end($nameBits); if (!in_array(strtolower($ext), $allowed)) { $return = array('error' => 1, 'text' => "Your image must be in jpg, gif or png format"); return Convert::raw2json($return); } $maxsize = $_POST['MAX_FILE_SIZE']; if ($tempfile['size'] > $maxsize) { $size = number_format($maxsize / 1024 / 1024, 2) . 'MB'; $return = array('error' => 1, 'text' => "Your image must be smaller than {$size}"); return Convert::raw2json($return); } // upload // $upload = new Upload(); $file = new Image(); $upload->loadIntoFile($tempfile, $file); if ($upload->isError()) { return false; } $file = $upload->getFile(); $return = array('link' => $file->Link()); return Convert::raw2json($return); } else { // no file to upload return false; } }
/** * Process the form that is submitted through the site * * @param Array Data * @param Form Form * @return Redirection */ public function process($data, $form) { Session::set("FormInfo.{$form->FormName()}.data", $data); Session::clear("FormInfo.{$form->FormName()}.errors"); foreach ($this->Fields() as $field) { $messages[$field->Name] = $field->getErrorMessage()->HTML(); if ($field->Required && $field->CustomRules()->Count() == 0) { if (!isset($data[$field->Name]) || !$data[$field->Name] || !$field->getFormField()->validate($this->validator)) { $form->addErrorMessage($field->Name, $field->getErrorMessage()->HTML(), 'bad'); } } } if (Session::get("FormInfo.{$form->FormName()}.errors")) { Controller::curr()->redirectBack(); return; } $submittedForm = Object::create('SubmittedForm'); $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; // if saving is not disabled save now to generate the ID if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } $values = array(); $attachments = array(); $submittedFields = new ArrayList(); foreach ($this->Fields() as $field) { if (!$field->showInReports()) { continue; } $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->getField('Title'); // save the value from the data if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { // create the file from post data $upload = new Upload(); $file = new File(); $file->ShowInSearch = 0; try { $upload->loadIntoFile($_FILES[$field->Name], $file); } catch (ValidationException $e) { $validationResult = $e->getResult(); $form->addErrorMessage($field->Name, $validationResult->message(), 'bad'); Controller::curr()->redirectBack(); return; } // write file to form field $submittedField->UploadedFileID = $file->ID; // attach a file only if lower than 1MB if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); // email users on submit. if ($this->EmailRecipients()) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); $email->populateTemplate($emailData); if ($attachments) { foreach ($attachments as $file) { if ($file->ID != 0) { $email->attachFile($file->Filename, $file->Filename, HTTP::get_mime_type($file->Filename)); } } } foreach ($this->EmailRecipients() as $recipient) { $email->populateTemplate($recipient); $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($recipient->EmailBody); $email->setSubject($recipient->EmailSubject); $email->setTo($recipient->EmailAddress); // check to see if they are a dynamic sender. eg based on a email field a user selected if ($recipient->SendEmailFromField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField) { $email->setFrom($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected if ($recipient->SendEmailToField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField) { $email->setTo($submittedFormField->Value); } } $this->extend('updateEmail', $email, $recipient, $emailData); if ($recipient->SendPlain) { $body = strip_tags($recipient->EmailBody) . "\n "; if (isset($emailData['Fields']) && !$recipient->HideFormData) { foreach ($emailData['Fields'] as $Field) { $body .= $Field->Title . ' - ' . $Field->Value . ' \\n'; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } Session::clear("FormInfo.{$form->FormName()}.errors"); Session::clear("FormInfo.{$form->FormName()}.data"); $referrer = isset($data['Referrer']) ? '?referrer=' . urlencode($data['Referrer']) : ""; return $this->redirect($this->Link() . 'finished' . $referrer); }
/** * Process the form that is submitted through the site * * @param Array Data * @param Form Form * @return Redirection */ function process($data, $form) { $submittedForm = Object::create('SubmittedForm'); $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; // if saving is not disabled save now to generate the ID if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } $values = array(); $attachments = array(); $submittedFields = new DataObjectSet(); foreach ($this->Fields() as $field) { if (!$field->showInReports()) { continue; } // create a new submitted form field. $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->Title; // save the value from the data if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { // create the file from post data $upload = new Upload(); $file = new File(); $upload->loadIntoFile($_FILES[$field->Name], $file); // write file to form field $submittedField->UploadedFileID = $file->ID; // attach a file only if lower than 1MB if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); // email users on submit. if ($this->EmailRecipients()) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); $email->populateTemplate($emailData); if ($attachments) { foreach ($attachments as $file) { if ($file->ID != 0) { $email->attachFile($file->Filename, $file->Filename, $file->getFileType()); } } } foreach ($this->EmailRecipients() as $recipient) { $email->populateTemplate($recipient); $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($recipient->EmailBody); $email->setSubject($recipient->EmailSubject); $email->setTo($recipient->EmailAddress); // check to see if they are a dynamic sender. eg based on a email field a user selected if ($recipient->SendEmailFromField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField) { $email->setFrom($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected if ($recipient->SendEmailToField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField) { $email->setTo($submittedFormField->Value); } } if ($recipient->SendPlain) { $body = strip_tags($recipient->EmailBody) . "\n "; if (isset($emailData['Fields']) && !$recipient->HideFormData) { foreach ($emailData['Fields'] as $Field) { $body .= $Field->Title . ' - ' . $Field->Value . ' \\n'; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } $referrer = isset($data['Referrer']) ? '?referrer=' . urlencode($data['Referrer']) : ""; return Director::redirect($this->Link() . 'finished' . $referrer); }
/** * Save an file passed from a form post into this object. * DEPRECATED Please instanciate an Upload-object instead and pass the file * via {Upload->loadIntoFile()}. * * @param $tmpFile array Indexed array that PHP generated for every file it uploads. * @return Boolean|string Either success or error-message. */ function loadUploaded($tmpFile) { user_error('File::loadUploaded is deprecated, please use the Upload class directly.', E_USER_NOTICE); $upload = new Upload(); $upload->loadIntoFile($tmpFile, $this); return $upload->isError(); }
function handleswfupload() { set_time_limit(1200); // 20 minutes $data = $_POST; $owner = DataObject::get_by_id($this->urlParams['Class'], $this->urlParams['ID']); $fieldName = $this->urlParams['Field'] . 'ID'; // TODO We need to replace this with a way to get the type of a field $imageClass = $owner->has_one($this->urlParams['Field']); // If we can't find the relationship, assume its an Image. if (!$imageClass) { if (!is_subclass_of($imageClass, 'Image')) { $imageClass = 'Image'; } } // Assuming its a decendant of File $image = new $imageClass(); if (class_exists("Upload")) { $u = new Upload(); $u->loadIntoFile($_FILES['swfupload_file'], $image); } else { $image->loadUploaded($_FILES['swfupload_file']); } $owner->{$fieldName} = $image->ID; // store the owner id with the uploaded image $image->write(); $owner->write(); echo $owner->ID; }
/** * @param ISummit $summit * @param $speaker_id * @param $tmp_file * @return BetterImage */ public function uploadSpeakerPic(ISummit $summit, $speaker_id, $tmp_file) { $speaker_repository = $this->speaker_repository; return $this->tx_service->transaction(function () use($summit, $speaker_id, $tmp_file, $speaker_repository) { $speaker_id = intval($speaker_id); $speaker = $speaker_repository->getById($speaker_id); if (is_null($speaker)) { throw new NotFoundEntityException('PresentationSpeaker'); } $image = new BetterImage(); $upload = new Upload(); $validator = new Upload_Validator(); $validator->setAllowedExtensions(array('png', 'jpg', 'jpeg', 'gif')); $validator->setAllowedMaxFileSize(800 * 1024); // 300Kb $upload->setValidator($validator); if (!$upload->loadIntoFile($tmp_file, $image, 'profile-images')) { throw new EntityValidationException($upload->getErrors()); } $image->write(); return $image; }); }
/** * Process the form that is submitted through the site * * @param Array Data * @param Form Form * @return Redirection */ function process($data, $form) { // submitted form object $submittedForm = new SubmittedForm(); $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; $submittedForm->Recipient = $this->EmailTo; if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } // email values $values = array(); $recipientAddresses = array(); $sendCopy = false; $attachments = array(); $submittedFields = new DataObjectSet(); foreach ($this->Fields() as $field) { // don't show fields that shouldn't be shown if (!$field->showInReports()) { continue; } $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->Title; if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { // create the file from post data $upload = new Upload(); $file = new File(); $upload->loadIntoFile($_FILES[$field->Name], $file); // write file to form field $submittedField->UploadedFileID = $file->ID; // Attach the file if its less than 1MB, provide a link if its over. if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); // email users on submit. All have their own custom options. if ($this->EmailRecipients()) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); $email->populateTemplate($emailData); if ($attachments) { foreach ($attachments as $file) { // bug with double decorated fields, valid ones should have an ID. if ($file->ID != 0) { $email->attachFile($file->Filename, $file->Filename, $file->getFileType()); } } } foreach ($this->EmailRecipients() as $recipient) { $email->populateTemplate($recipient); $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($recipient->EmailBody); $email->setSubject($recipient->EmailSubject); $email->setTo($recipient->EmailAddress); // check to see if they are a dynamic sender. eg based on a email field a user selected if ($recipient->SendEmailFromField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField) { $email->setFrom($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected if ($recipient->SendEmailToField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField) { $email->setTo($submittedFormField->Value); } } if ($recipient->SendPlain) { $body = strip_tags($recipient->EmailBody) . "\n "; if (isset($emailData['Fields']) && !$recipient->HideFormData) { foreach ($emailData['Fields'] as $Field) { $body .= $Field->Title . ' - ' . $Field->Value . ' \\n'; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } return Director::redirect($this->Link() . 'finished?referrer=' . urlencode($data['Referrer'])); }
public function handleswfupload() { if (isset($_FILES['swfupload_file']) && !empty($_FILES['swfupload_file'])) { $do_class = $_POST['dataObjectClassName']; $file_class = $_POST['fileClassName']; $obj = new $do_class(); $idxfield = $_POST['fileFieldName'] . "ID"; $file = new $file_class(); $album = DataObject::get_by_id("ImageGalleryAlbum", $_POST['AlbumID']); $dest = substr_replace(str_replace('assets/', '', $album->Folder()->Filename), "", -1); if (class_exists("Upload")) { $u = new Upload(); $u->loadIntoFile($_FILES['swfupload_file'], $file, $dest); } else { $file->loadUploaded($_FILES['swfupload_file'], $dest); } $file->setField("ParentID", $album->FolderID); $file->write(); $obj->{$idxfield} = $file->ID; $obj->AlbumID = $album->ID; $ownerID = $_POST['parentIDName']; $obj->{$ownerID} = $_POST['controllerID']; $obj->write(); echo $obj->ID; } else { echo ' '; } }
/** * Process the form that is submitted through the site * * @param array $data * @param Form $form * * @return Redirection */ public function process($data, $form) { Session::set("FormInfo.{$form->FormName()}.data", $data); Session::clear("FormInfo.{$form->FormName()}.errors"); foreach ($this->Fields() as $field) { $messages[$field->Name] = $field->getErrorMessage()->HTML(); $formField = $field->getFormField(); if ($field->Required && $field->CustomRules()->Count() == 0) { if (isset($data[$field->Name])) { $formField->setValue($data[$field->Name]); } if (!isset($data[$field->Name]) || !$data[$field->Name] || !$formField->validate($form->getValidator())) { $form->addErrorMessage($field->Name, $field->getErrorMessage(), 'bad'); } } } if (Session::get("FormInfo.{$form->FormName()}.errors")) { Controller::curr()->redirectBack(); return; } $submittedForm = Object::create('SubmittedForm'); $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; // if saving is not disabled save now to generate the ID if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } $values = array(); $attachments = array(); $submittedFields = new ArrayList(); foreach ($this->Fields() as $field) { if (!$field->showInReports()) { continue; } $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->getField('Title'); // save the value from the data if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { $foldername = $field->getFormField()->getFolderName(); // create the file from post data $upload = new Upload(); $file = new File(); $file->ShowInSearch = 0; try { $upload->loadIntoFile($_FILES[$field->Name], $file, $foldername); } catch (ValidationException $e) { $validationResult = $e->getResult(); $form->addErrorMessage($field->Name, $validationResult->message(), 'bad'); Controller::curr()->redirectBack(); return; } // write file to form field $submittedField->UploadedFileID = $file->ID; // attach a file only if lower than 1MB if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } $submittedField->extend('onPopulationFromField', $field); if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); $this->extend('updateEmailData', $emailData, $attachments); // email users on submit. if ($recipients = $this->FilteredEmailRecipients($data, $form)) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); $mergeFields = $this->getMergeFieldsMap($emailData['Fields']); if ($attachments) { foreach ($attachments as $file) { if ($file->ID != 0) { $email->attachFile($file->Filename, $file->Filename, HTTP::get_mime_type($file->Filename)); } } } foreach ($recipients as $recipient) { $parsedBody = SSViewer::execute_string($recipient->getEmailBodyContent(), $mergeFields); if (!$recipient->SendPlain && $recipient->emailTemplateExists()) { $email->setTemplate($recipient->EmailTemplate); } $email->populateTemplate($recipient); $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($parsedBody); $email->setTo($recipient->EmailAddress); $email->setSubject($recipient->EmailSubject); if ($recipient->EmailReplyTo) { $email->setReplyTo($recipient->EmailReplyTo); } // check to see if they are a dynamic reply to. eg based on a email field a user selected if ($recipient->SendEmailFromField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField && is_string($submittedFormField->Value)) { $email->setReplyTo($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected if ($recipient->SendEmailToField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField && is_string($submittedFormField->Value)) { $email->setTo($submittedFormField->Value); } } // check to see if there is a dynamic subject if ($recipient->SendEmailSubjectField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name); if ($submittedFormField && trim($submittedFormField->Value)) { $email->setSubject($submittedFormField->Value); } } $this->extend('updateEmail', $email, $recipient, $emailData); if ($recipient->SendPlain) { $body = strip_tags($recipient->getEmailBodyContent()) . "\n"; if (isset($emailData['Fields']) && !$recipient->HideFormData) { foreach ($emailData['Fields'] as $Field) { $body .= $Field->Title . ': ' . $Field->Value . " \n"; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } $submittedForm->extend('updateAfterProcess'); Session::clear("FormInfo.{$form->FormName()}.errors"); Session::clear("FormInfo.{$form->FormName()}.data"); $referrer = isset($data['Referrer']) ? '?referrer=' . urlencode($data['Referrer']) : ""; // set a session variable from the security ID to stop people accessing // the finished method directly. if (!$this->DisableAuthenicatedFinishAction) { if (isset($data['SecurityID'])) { Session::set('FormProcessed', $data['SecurityID']); } else { // if the form has had tokens disabled we still need to set FormProcessed // to allow us to get through the finshed method if (!$this->Form()->getSecurityToken()->isEnabled()) { $randNum = rand(1, 1000); $randHash = md5($randNum); Session::set('FormProcessed', $randHash); Session::set('FormProcessedNum', $randNum); } } } if (!$this->DisableSaveSubmissions) { Session::set('userformssubmission' . $this->ID, $submittedForm->ID); } return $this->redirect($this->Link('finished') . $referrer . $this->config()->finished_anchor); }
/** * The main upload handler. Takes the $_FILES data from the request and stores a File * record {@see $defaults['file_class']}. Returns the ID of this new file to the * Javascript handler, for insertion into the parent form. * Note: This handler may require authentication, and that may not be possible * if the PHP setting "session_use_only_cookies" is on. * * @return int */ public function upload() { if (isset($_FILES["Filedata"]) && is_uploaded_file($_FILES["Filedata"]["tmp_name"])) { $upload_folder = $this->getUploadFolder(); if ($this->Backend()) { if (isset($_REQUEST['FolderID'])) { if ($folder = DataObject::get_by_id("Folder", Convert::raw2sql($_REQUEST['FolderID']))) { $upload_folder = self::relative_asset_dir($folder->Filename); } } } $ext = strtolower(end(explode('.', $_FILES['Filedata']['name']))); $class = in_array($ext, self::$image_extensions) ? $this->getSetting('image_class') : $this->getSetting('file_class'); $file = new $class(); $u = new Upload(); $u->loadIntoFile($_FILES['Filedata'], $file, $upload_folder); $file->write(); echo $file->ID; } else { echo ' '; // return something or SWFUpload won't fire uploadSuccess } }
/** * The main upload handler. Takes the $_FILES data from the request and stores a File * record {@see $defaults['file_class']}. Returns the ID of this new file to the * Javascript handler, for insertion into the parent form. * Note: This handler may require authentication, and that may not be possible * if the PHP setting "session_use_only_cookies" is on. * * @return int */ public function upload() { if (isset($_FILES["Filedata"]) && is_uploaded_file($_FILES["Filedata"]["tmp_name"])) { $upload_folder = $this->getUploadFolder(); if ($this->Backend()) { if (isset($_REQUEST['FolderID'])) { if ($folder = DataObject::get_by_id("Folder", Convert::raw2sql($_REQUEST['FolderID']))) { $upload_folder = self::relative_asset_dir($folder->Filename); } } } $ext = strtolower(end(explode('.', $_FILES['Filedata']['name']))); $class = in_array($ext, self::$image_extensions) ? $this->getSetting('image_class') : $this->getSetting('file_class'); $file = new $class(); // Perform check on allowed file extension, preventing upload of unallowed file types $u = new Upload(); $u->setValidator($validator = new Upload_Validator()); $validator->setAllowedExtensions(File::$allowed_extensions); if ($u->validate($_FILES['Filedata'])) { $u->loadIntoFile($_FILES['Filedata'], $file, $upload_folder); } else { return _t('Uploadify.FILETYPENOTALLOWED', 'File type not allowed!'); } $file->write(); if (method_exists($file, 'onAfterUpload')) { $file->onAfterUpload(); } echo $file->ID; } else { echo ' '; // return something or SWFUpload won't fire uploadSuccess } }
public function testReplaceFileWithLoadIntoFile() { // create tmp file $tmpFileName = 'UploadTest-testUpload.txt'; $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName; $tmpFileContent = ''; for ($i = 0; $i < 10000; $i++) { $tmpFileContent .= '0'; } file_put_contents($tmpFilePath, $tmpFileContent); // emulates the $_FILES array $tmpFile = array('name' => $tmpFileName, 'type' => 'text/plaintext', 'size' => filesize($tmpFilePath), 'tmp_name' => $tmpFilePath, 'extension' => 'txt', 'error' => UPLOAD_ERR_OK); // Make sure there are none here, otherwise they get renamed incorrectly for the test. $this->deleteTestUploadFiles("/UploadTest-testUpload.*/"); $v = new UploadTest_Validator(); // test upload into default folder $u = new Upload(); $u->setValidator($v); $u->load($tmpFile); $file = $u->getFile(); $this->assertEquals('UploadTest-testUpload.txt', $file->Name, 'File is uploaded without extension'); $this->assertFileExists(BASE_PATH . '/' . $file->getFilename(), 'File exists'); // replace=true $u = new Upload(); $u->setValidator($v); $u->setReplaceFile(true); $u->loadIntoFile($tmpFile, new File()); $file2 = $u->getFile(); $this->assertEquals('UploadTest-testUpload.txt', $file2->Name, 'File does not receive new name'); $this->assertFileExists(BASE_PATH . '/' . $file2->getFilename(), 'File exists'); $this->assertEquals($file->ID, $file2->ID, 'File database record is the same'); // replace=false $u = new Upload(); $u->setValidator($v); $u->setReplaceFile(false); $u->loadIntoFile($tmpFile, new File()); $file3 = $u->getFile(); $this->assertEquals('UploadTest-testUpload2.txt', $file3->Name, 'File does receive new name'); $this->assertFileExists(BASE_PATH . '/' . $file3->getFilename(), 'File exists'); $this->assertGreaterThan($file2->ID, $file3->ID, 'File database record is not the same'); $file->delete(); $file2->delete(); $file3->delete(); }
function upload() { if(isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) { $chunk = (isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0); $chunks = (isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0); $fileName = (isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''); echo(':'.$chunk.'/'.$chunks.':'); // Clean the fileName for security reasons $fileName = preg_replace('/[^\w\._]+/', '', $fileName); $uploadDir = $this->getUploadFolder(); $ext = strtolower(end(explode('.', $_FILES['file']['name']))); $class = in_array($ext, self::$image_extensions) ? $this->getSetting('image-class') : $this->getSetting('file-class'); if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } /* // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { */ if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { if ($chunks < 2) { $file = new $class(); $uploadObject = new Upload(); $uploadObject->loadIntoFile($_FILES['file'], $file, $uploadDir); // $file->write(); $id = $file->ID; } else { //die('ERROR: CHUNKING NOT YET SUPPORTED'); die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Chunking is not supported. Please remove chunk_size from the JS parameters."}, "id" : "id"}'); // Open temp file $out = fopen($uploadDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($_FILES['file']['tmp_name'], "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); fclose($in); fclose($out); @unlink($_FILES['file']['tmp_name']); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } /* } else { if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) { $file = new $class(); $uploadObject = new Upload(); $uploadObject->loadIntoFile($_FILES['file'], $file, $uploadDir); // $file->write(); $id = $file->ID; } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } */ // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); } }
public function handleswfupload() { if (isset($_FILES['swfupload_file']) && !empty($_FILES['swfupload_file'])) { $do_class = $_POST['dataObjectClassName']; $hasDataObject = $_POST['hasDataObject']; $idxfield = $_POST['fileFieldName'] . "ID"; $file_class = $_POST['fileClassName']; $file = new $file_class(); if (isset($_POST['UploadFolder'])) { $folder = DataObject::get_by_id("Folder", $_POST['UploadFolder']); $path = str_replace("assets/", "", $folder->Filename); if (substr($path, -1) == "/") { $path = substr($path, 0, -1); } } else { $path = str_replace("assets/", "", $_POST['OverrideUploadFolder']); if (substr($path, -1) == "/") { $path = substr($path, 0, -1); } } if (class_exists("Upload")) { $u = new Upload(); $u->loadIntoFile($_FILES['swfupload_file'], $file, $path); } else { $file->loadUploaded($_FILES['swfupload_file'], $path); } if (isset($_POST['UploadFolder'])) { $file->setField("ParentID", $folder->ID); } // Provide an "upgrade" to File subclasses if ($file->class == "File") { $ext = strtolower($file->Extension); if (in_array($ext, MP3::$allowed_file_types) && FileDataObjectManager::$upgrade_audio) { $file = $file->newClassInstance("MP3"); } else { if (in_array($ext, array('jpg', 'jpeg', 'gif', 'png')) && FileDataObjectManager::$upgrade_image) { $file = $file->newClassInstance("Image"); } else { if (in_array($ext, FLV::$allowed_file_types) && FileDataObjectManager::$upgrade_video) { $file = $file->newClassInstance("FLV"); } } } } $file->OwnerID = Member::currentUserID(); if ($hasDataObject) { $file->write(); $obj = new $do_class(); $obj->{$idxfield} = $file->ID; $ownerID = $_POST['parentIDName']; $obj->{$ownerID} = $_POST['controllerID']; $obj->write(); echo $obj->ID; } else { $ownerID = $_POST['parentIDName']; $file->{$ownerID} = $_POST['controllerID']; $file->write(); echo $file->ID; } } else { echo ' '; } }
/** * Process the form that is submitted through the site. Note that omnipay fields are NOT saved to the database. * This is intentional (so we don't save credit card details) but should be fixed in future, so we save all fields, * but only save the last 3 digits of the credit card (and not the CVV/exp date) * * @todo: save all fields to database except credit card fields * * @param array $data * @param Form $form * * @return Redirection */ public function process($data, $form) { Session::set("FormInfo.{$form->FormName()}.data", $data); Session::clear("FormInfo.{$form->FormName()}.errors"); foreach ($this->Fields() as $field) { $messages[$field->Name] = $field->getErrorMessage()->HTML(); $formField = $field->getFormField(); if ($field->Required && $field->CustomRules()->Count() == 0) { if (isset($data[$field->Name])) { $formField->setValue($data[$field->Name]); } if (!isset($data[$field->Name]) || !$data[$field->Name] || !$formField->validate($form->getValidator())) { $form->addErrorMessage($field->Name, $field->getErrorMessage(), 'bad'); } } } if (Session::get("FormInfo.{$form->FormName()}.errors")) { Controller::curr()->redirectBack(); return; } // if there are no errors, create the payment $submittedForm = Object::create('SubmittedPaymentForm'); $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; // if saving is not disabled save now to generate the ID if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } $attachments = array(); $submittedFields = new ArrayList(); foreach ($this->Fields() as $field) { if (!$field->showInReports()) { continue; } $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->getField('Title'); // save the value from the data if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { $foldername = $field->getFormField()->getFolderName(); // create the file from post data $upload = new Upload(); $file = new File(); $file->ShowInSearch = 0; try { $upload->loadIntoFile($_FILES[$field->Name], $file, $foldername); } catch (ValidationException $e) { $validationResult = $e->getResult(); $form->addErrorMessage($field->Name, $validationResult->message(), 'bad'); Controller::curr()->redirectBack(); return; } // write file to form field $submittedField->UploadedFileID = $file->ID; // attach a file only if lower than 1MB if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } $submittedField->extend('onPopulationFromField', $field); if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } /** Do the payment **/ // move this up here for our redirect link $referrer = isset($data['Referrer']) ? '?referrer=' . urlencode($data['Referrer']) : ""; // set amount $currency = $this->data()->PaymentCurrency; $paymentfieldname = $this->PaymentAmountField()->Name; $amount = $data[$paymentfieldname]; $postdata = $data; // request payment $payment = Payment::create()->init($this->data()->PaymentGateway, $amount, $currency); $payment->write(); $response = PurchaseService::create($payment)->setReturnUrl($this->Link('finished') . $referrer)->setCancelUrl($this->Link('finished') . $referrer)->purchase($postdata); // save payment to order $submittedForm->PaymentID = $payment->ID; $submittedForm->write(); $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); $this->extend('updateEmailData', $emailData, $attachments); $submittedForm->extend('updateAfterProcess'); Session::clear("FormInfo.{$form->FormName()}.errors"); Session::clear("FormInfo.{$form->FormName()}.data"); // set a session variable from the security ID to stop people accessing the finished method directly if (isset($data['SecurityID'])) { Session::set('FormProcessed', $data['SecurityID']); } else { // if the form has had tokens disabled we still need to set FormProcessed // to allow us to get through the finshed method if (!$this->Form()->getSecurityToken()->isEnabled()) { $randNum = rand(1, 1000); $randHash = md5($randNum); Session::set('FormProcessed', $randHash); Session::set('FormProcessedNum', $randNum); } } if (!$this->DisableSaveSubmissions) { Session::set('userformssubmission' . $this->ID, $submittedForm->ID); } return $response->redirect(); }
public function testFileVersioningWithAnExistingFile() { $upload = function ($tmpFileName) { // create tmp file $tmpFilePath = TEMP_FOLDER . '/' . $tmpFileName; $tmpFileContent = ''; for ($i = 0; $i < 10000; $i++) { $tmpFileContent .= '0'; } file_put_contents($tmpFilePath, $tmpFileContent); // emulates the $_FILES array $tmpFile = array('name' => $tmpFileName, 'type' => 'text/plaintext', 'size' => filesize($tmpFilePath), 'tmp_name' => $tmpFilePath, 'extension' => 'jpg', 'error' => UPLOAD_ERR_OK); $v = new UploadTest_Validator(); // test upload into default folder $u = new Upload(); $u->setReplaceFile(false); $u->setValidator($v); $u->loadIntoFile($tmpFile); return $u->getFile(); }; // test empty file version prefix Config::inst()->update('SilverStripe\\Filesystem\\Storage\\DefaultAssetNameGenerator', 'version_prefix', ''); $file1 = $upload('UploadTest-IMG001.jpg'); $this->assertEquals('UploadTest-IMG001.jpg', $file1->Name, 'File does not receive new name'); $file2 = $upload('UploadTest-IMG001.jpg'); $this->assertEquals('UploadTest-IMG002.jpg', $file2->Name, 'File does receive new name'); $file3 = $upload('UploadTest-IMG002.jpg'); $this->assertEquals('UploadTest-IMG003.jpg', $file3->Name, 'File does receive new name'); $file4 = $upload('UploadTest-IMG3.jpg'); $this->assertEquals('UploadTest-IMG3.jpg', $file4->Name, 'File does not receive new name'); $file1->delete(); $file2->delete(); $file3->delete(); $file4->delete(); // test '-v' file version prefix Config::inst()->update('SilverStripe\\Filesystem\\Storage\\DefaultAssetNameGenerator', 'version_prefix', '-v'); $file1 = $upload('UploadTest2-IMG001.jpg'); $this->assertEquals('UploadTest2-IMG001.jpg', $file1->Name, 'File does not receive new name'); $file2 = $upload('UploadTest2-IMG001.jpg'); $this->assertEquals('UploadTest2-IMG001-v2.jpg', $file2->Name, 'File does receive new name'); $file3 = $upload('UploadTest2-IMG001.jpg'); $this->assertEquals('UploadTest2-IMG001-v3.jpg', $file3->Name, 'File does receive new name'); $file4 = $upload('UploadTest2-IMG001-v3.jpg'); $this->assertEquals('UploadTest2-IMG001-v4.jpg', $file4->Name, 'File does receive new name'); }
/** * Do the dirty work of processing the form submission and saving it if necessary * * This has been overridden to be able to re-edit existing form submissions */ protected function processSubmission($data, $form) { $submittedForm = SubmittedForm::create(); $reEdit = false; if (isset($data['ResumeID'])) { $resumeSubmission = DataObject::get_by_id('SubmittedForm', (int) $data['ResumeID']); // make sure it was this user that submitted it if ($resumeSubmission->isReEditable()) { $submittedForm = $resumeSubmission; $reEdit = true; } } $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0; $submittedForm->ParentID = $this->ID; $submittedForm->Recipient = $this->EmailTo; if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } // email values $values = array(); $recipientAddresses = array(); $sendCopy = false; $attachments = array(); $submittedFields = ArrayList::create(); $titleField = $this->data()->SubmissionTitleField; foreach ($this->Fields() as $field) { // don't show fields that shouldn't be shown if (!$field->showInReports()) { continue; } $submittedField = null; if ($reEdit) { // get the field from the existing submission, otherwise return it // from the form field directly $submittedField = $submittedForm->getFormField($field->Name); } // we want to do things this way to ensure that we have a submittedField - sometimes a field won't // existing on a form re-edit (eg if the form changes) if (!$submittedField) { $submittedField = $field->getSubmittedFormField(); } $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->getField('Title'); if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } if ($titleField == $field->Name) { $submittedForm->SubmissionTitle = $submittedField->Value; } if (!empty($data[$field->Name])) { if (in_array("EditableFileField", $field->getClassAncestry())) { if (isset($_FILES[$field->Name])) { $foldername = $field->getFormField()->getFolderName(); // create the file from post data $upload = new Upload(); $file = new File(); $file->ShowInSearch = 0; try { $upload->loadIntoFile($_FILES[$field->Name], $file); } catch (ValidationException $e) { $validationResult = $e->getResult(); $form->addErrorMessage($field->Name, $validationResult->message(), 'bad'); Controller::curr()->redirectBack(); return; } // write file to form field $submittedField->UploadedFileID = $file->ID; // Attach the file if its less than 1MB, provide a link if its over. if ($file->getAbsoluteSize() < 1024 * 1024 * 1) { $attachments[] = $file; } } } } $submittedField->extend('onPopulationFromField', $field); if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields); $this->extend('updateEmailData', $emailData, $attachments); // email users on submit. if ($recipients = $this->FilteredEmailRecipients($data, $form)) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); if ($attachments) { foreach ($attachments as $file) { if ($file->ID != 0) { $email->attachFile($file->Filename, $file->Filename, HTTP::get_mime_type($file->Filename)); } } } foreach ($recipients as $recipient) { $email->populateTemplate($recipient); $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($recipient->EmailBody); $email->setTo($recipient->EmailAddress); $email->setSubject($recipient->EmailSubject); if ($recipient->EmailReplyTo) { $email->setReplyTo($recipient->EmailReplyTo); } // check to see if they are a dynamic reply to. eg based on a email field a user selected if ($recipient->SendEmailFromField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField && is_string($submittedFormField->Value)) { $email->setReplyTo($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected if ($recipient->SendEmailToField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField && is_string($submittedFormField->Value)) { $email->setTo($submittedFormField->Value); } } // check to see if there is a dynamic subject if ($recipient->SendEmailSubjectField()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name); if ($submittedFormField && trim($submittedFormField->Value)) { $email->setSubject($submittedFormField->Value); } } $this->extend('updateEmail', $email, $recipient, $emailData); if ($recipient->SendPlain) { $body = strip_tags($recipient->EmailBody) . "\n"; if (isset($emailData['Fields']) && !$recipient->HideFormData) { foreach ($emailData['Fields'] as $Field) { $body .= $Field->Title . ': ' . $Field->Value . " \n"; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } $submittedForm->extend('updateAfterProcess'); Session::clear("FormInfo.{$form->FormName()}.errors"); Session::clear("FormInfo.{$form->FormName()}.data"); return $submittedForm; }
/** * Process the form that is submitted through the site * * @param Array Data * @param Form Form * @return Redirection */ function process($data, $form) { // submitted form object $submittedForm = new SubmittedForm(); $submittedForm->SubmittedBy = Member::currentUser(); $submittedForm->ParentID = $this->ID; $submittedForm->Recipient = $this->EmailTo; $submittedForm->write(); // email values $values = array(); $recipientAddresses = array(); $sendCopy = false; $attachments = array(); $submittedFields = new DataObjectSet(); foreach($this->Fields() as $field) { // don't show fields that shouldn't be shown if(!$field->showInReports()) continue; $submittedField = new SubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->Title; if($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if(isset($data[$field->Name])) $submittedField->Value = $data[$field->Name]; } $submittedField->write(); $submittedFields->push($submittedField); if(!empty($data[$field->Name])){ /** * @todo this should be on the EditableFile class. Just need to sort out * attachments array */ if($field->ClassName == "EditableFileField"){ if(isset($_FILES[$field->Name])) { // create the file from post data $upload = new Upload(); $file = new File(); $upload->loadIntoFile($_FILES[$field->Name], $file); // write file to form field $submittedField->UploadedFileID = $file->ID; // Attach the file if its less than 1MB, provide a link if its over. if($file->getAbsoluteSize() < 1024*1024*1){ $attachments[] = $file; } // Always provide the link if present. if($file->ID) { $submittedField->Value = "<a href=\"". $file->getFilename() ."\" title=\"". $file->getFilename() . "\">". $file->Title . "</a>"; } else { $submittedField->Value = ""; } } } } // make sure we save $submittedField->write(); } $emailData = array( "Sender" => Member::currentUser(), "Fields" => $submittedFields, ); // email users on submit. All have their own custom options. if($this->EmailRecipients()) { $email = new UserDefinedForm_SubmittedFormEmail($submittedFields); $email->populateTemplate($emailData); if($attachments){ foreach($attachments as $file){ // bug with double decorated fields, valid ones should have an ID. if($file->ID != 0) { $email->attachFile($file->Filename,$file->Filename, $file->getFileType()); } } } foreach($this->EmailRecipients() as $recipient) { $email->populateTemplate($emailData); $email->setFrom($recipient->EmailFrom); $email->setBody($recipient->EmailBody); $email->setSubject($recipient->EmailSubject); $email->setTo($recipient->EmailAddress); // check to see if they are a dynamic sender. eg based on a email field // a user selected if($recipient->SendEmailFromField()) { $name = Convert::raw2sql($recipient->SendEmailFromField()->Name); if(defined('Database::USE_ANSI_SQL')) { $submittedFormField = DataObject::get_one("SubmittedFormField", "\"Name\" = '$name' AND \"ParentID\" = '$submittedForm->ID'"); } else { $submittedFormField = DataObject::get_one("SubmittedFormField", "Name = '$name' AND ParentID = '$submittedForm->ID'"); } if($submittedFormField) { $email->setFrom($submittedFormField->Value); } } // check to see if they are a dynamic reciever eg based on a dropdown field // a user selected if($recipient->SendEmailToField()) { $name = Convert::raw2sql($recipient->SendEmailToField()->Name); if(defined('Database::USE_ANSI_SQL')) { $submittedFormField = DataObject::get_one("SubmittedFormField", "\"Name\" = '$name' AND \"ParentID\" = '$submittedForm->ID'"); } else { $submittedFormField = DataObject::get_one("SubmittedFormField", "Name = '$name' AND ParentID = '$submittedForm->ID'"); } if($submittedFormField) { $email->setTo($submittedFormField->Value); } } if($recipient->SendPlain) { $body = strip_tags($recipient->EmailBody) . "\n "; if(isset($emailData['Fields'])) { foreach($emailData['Fields'] as $Field) { $body .= $Field->Title .' - '. $Field->Value .'\n'; } } $email->setBody($body); $email->sendPlain(); } else { $email->send(); } } } // Redirect to the finished method on this controller with the referrer data Director::redirect($this->Link() . 'finished?referrer=' . urlencode($data['Referrer'])); }
/** * Post a message to the forum. This method is called whenever you want to make a * new post or edit an existing post on the forum * * @param Array - Data * @param Form - Submitted Form */ function doPostMessageForm($data, $form) { $member = Member::currentUser(); $content = isset($data['Content']) ? $this->filterLanguage($data["Content"]) : ""; $title = isset($data['Title']) ? $this->filterLanguage($data["Title"]) : false; // If a thread id is passed append the post to the thread. Otherwise create // a new thread $thread = false; if (isset($data['ThreadID'])) { $thread = DataObject::get_by_id('ForumThread', $data['ThreadID']); } // If this is a simple edit the post then handle it here. Look up the correct post, // make sure we have edit rights to it then update the post $post = false; if (isset($data['ID'])) { $post = DataObject::get_by_id('Post', $data['ID']); if ($post && $post->isFirstPost()) { if ($title) { $thread->Title = $title; } } } // Check permissions $messageSet = array('default' => _t('Forum.LOGINTOPOST', 'You\'ll need to login before you can post to that forum. Please do so below.'), 'alreadyLoggedIn' => _t('Forum.NOPOSTPERMISSION', 'I\'m sorry, but you do not have permission post to this forum.'), 'logInAgain' => _t('Forum.LOGINTOPOSTAGAIN', 'You have been logged out of the forums. If you would like to log in again to post, enter a username and password below.')); // Creating new thread if (!$thread && !$this->canPost()) { Security::permissionFailure($this, $messageSet); return false; } // Replying to existing thread if ($thread && !$post && !$thread->canPost()) { Security::permissionFailure($this, $messageSet); return false; } // Editing existing post if ($thread && $post && !$post->canEdit()) { Security::permissionFailure($this, $messageSet); return false; } if (!$thread) { $thread = new ForumThread(); $thread->ForumID = $this->ID; if ($title) { $thread->Title = $title; } $starting_thread = true; } // from now on the user has the correct permissions. save the current thread settings $thread->write(); if (!$post || !$post->canEdit()) { $post = new Post(); $post->AuthorID = $member ? $member->ID : 0; $post->ThreadID = $thread->ID; } $post->ForumID = $thread->ForumID; $post->Content = $content; $post->write(); // Upload and Save all files attached to the field // Attachment will always be blank, If they had an image it will be at least in Attachment-0 if (!empty($data['Attachment'])) { $id = 0; // // @todo this only supports ajax uploads. Needs to change the key (to simply Attachment). // while (isset($data['Attachment-' . $id])) { $image = $data['Attachment-' . $id]; if ($image) { // check to see if a file of same exists $title = Convert::raw2sql($image['name']); $file = DataObject::get_one("Post_Attachment", "\"Title\" = '{$title}' AND \"PostID\" = '{$post->ID}'"); if (!$file) { $file = new Post_Attachment(); $file->PostID = $post->ID; $file->OwnerID = Member::currentUserID(); $upload = new Upload(); $upload->loadIntoFile($image, $file); $file->write(); } } $id++; } } // Add a topic subscription entry if required if (isset($data['TopicSubscription'])) { if (!ForumThread_Subscription::already_subscribed($thread->ID)) { // Create a new topic subscription for this member $obj = new ForumThread_Subscription(); $obj->ThreadID = $thread->ID; $obj->MemberID = Member::currentUserID(); $obj->write(); } } else { // See if the member wanted to remove themselves if (ForumThread_Subscription::already_subscribed($post->TopicID)) { DB::query("DELETE FROM \"ForumThread_Subscription\" WHERE \"ThreadID\" = '{$post->ThreadID}' AND \"MemberID\" = '{$member->ID}'"); } } // Send any notifications that need to be sent ForumThread_Subscription::notify($post); // Send any notifications to moderators of the forum if (Forum::$notify_moderators) { if (isset($starting_thread) && $starting_thread) { $this->notifyModerators($post, $thread, true); } else { $this->notifyModerators($post, $thread); } } return $this->redirect($post->Link()); }