/**
  * Output file to user.
  * Send file content to browser for download progressively.
  */
 public function index()
 {
     $file = $this->request->getVar('file');
     $fileAssetPath = substr($file, stripos($file, 'assets'));
     $fileObj = File::get()->filter(array('Filename' => Convert::raw2sql($fileAssetPath)))->first();
     if ($fileObj) {
         $rule = self::RULE_PUBLIC;
         foreach (self::config()->rules as $key => $value) {
             $regex = '$^assets/' . trim($key, '/') . '/$';
             if (preg_match($regex, $fileAssetPath)) {
                 $rule = $value;
             }
         }
         if (self::config()->cms_access_ignore_rules && Permission::check('CMS_ACCESS')) {
             $rule = self::RULE_PUBLIC;
         }
         if (self::config()->admin_ignore_rules && Permission::check('ADMIN')) {
             $rule = self::RULE_PUBLIC;
         }
         switch ($rule) {
             case self::RULE_PUBLIC:
                 // Then we do nothing...
                 break;
             case self::RULE_ADMIN:
                 if (!Permission::check('ADMIN')) {
                     return $this->sendHttpError($fileObj, $rule);
                 }
                 break;
             case self::RULE_LOGGED_IN:
                 if (!Member::currentUserID()) {
                     return $this->sendHttpError($fileObj, $rule);
                 }
                 break;
             case self::RULE_OWNER:
                 if ($fileObj->OwnerID != Member::currentUserID()) {
                     return $this->sendHttpError($fileObj, $rule);
                 }
                 break;
             default:
                 throw new Exception("Rule {$rule} is not defined");
         }
         $filePath = $fileObj->getFullPath();
         $mimeType = HTTP::get_mime_type($filePath);
         $name = $fileObj->Name;
         $this->audit($fileObj);
         header("Content-Type: {$mimeType}");
         header("Content-Disposition: attachment; filename=\"{$name}\"");
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         set_time_limit(0);
         $file = @fopen($filePath, "rb");
         while (!feof($file)) {
             print @fread($file, 1024 * 8);
             ob_flush();
             flush();
         }
         exit;
     }
     return $this->sendHttpError($fileObj, self::RULE_NOT_FOUND);
 }
 /**
  * Output file to the browser.
  * For performance reasons, we avoid SS_HTTPResponse and just output the contents instead.
  */
 public function sendFile($file)
 {
     $path = $file->getFullPath();
     if (SapphireTest::is_running_test()) {
         return file_get_contents($path);
     }
     header('Content-Description: File Transfer');
     // Quotes needed to retain spaces (http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download)
     header('Content-Disposition: inline; filename="' . basename($path) . '"');
     header('Content-Length: ' . $file->getAbsoluteSize());
     header('Content-Type: ' . HTTP::get_mime_type($file->getRelativePath()));
     header('Content-Transfer-Encoding: binary');
     // Fixes IE6,7,8 file downloads over HTTPS bug (http://support.microsoft.com/kb/812935)
     header('Pragma: ');
     if ($this->config()->min_download_bandwidth) {
         // Allow the download to last long enough to allow full download with min_download_bandwidth connection.
         increase_time_limit_to((int) (filesize($path) / ($this->config()->min_download_bandwidth * 1024)));
     } else {
         // Remove the timelimit.
         increase_time_limit_to(0);
     }
     // Clear PHP buffer, otherwise the script will try to allocate memory for entire file.
     while (ob_get_level() > 0) {
         ob_end_flush();
     }
     // Prevent blocking of the session file by PHP. Without this the user can't visit another page of the same
     // website during download (see http://konrness.com/php5/how-to-prevent-blocking-php-requests/)
     session_write_close();
     readfile($path);
     die;
 }
 /**
  * Output file to the browser.
  * For performance reasons, we avoid SS_HTTPResponse and just output the contents instead.
  */
 public function sendFile($file)
 {
     $reader = $file->reader();
     if (!$reader || !$reader->isReadable()) {
         return;
     }
     if (class_exists('SapphireTest', false) && SapphireTest::is_running_test()) {
         return $reader->read();
     }
     $type = HTTP::get_mime_type($file->Filename);
     $disposition = strpos($type, 'image') !== false ? 'inline' : 'attachment';
     header('Content-Description: File Transfer');
     // Quotes needed to retain spaces (http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download)
     header(sprintf('Content-Disposition: %s; filename="%s"', $disposition, basename($file->Filename)));
     header('Content-Length: ' . $file->FileSize);
     header('Content-Type: ' . $type);
     header('Content-Transfer-Encoding: binary');
     // Ensure we enforce no-cache headers consistently, so that files accesses aren't cached by CDN/edge networks
     header('Pragma: no-cache');
     header('Cache-Control: private, no-cache, no-store');
     increase_time_limit_to(0);
     // Clear PHP buffer, otherwise the script will try to allocate memory for entire file.
     while (ob_get_level() > 0) {
         ob_end_flush();
     }
     // Prevent blocking of the session file by PHP. Without this the user can't visit another page of the same
     // website during download (see http://konrness.com/php5/how-to-prevent-blocking-php-requests/)
     session_write_close();
     echo $reader->read();
     die;
 }
 /**
  * Output file to user.
  * Send file content to browser for download progressively.
  */
 public function index()
 {
     $file = $this->request->getVar('file');
     $fileAssetPath = substr($file, stripos($file, 'assets'));
     $fileObj = File::get()->filter(array('Filename' => $fileAssetPath))->first();
     if ($fileObj) {
         $filePath = $fileObj->getFullPath();
         $mimeType = HTTP::get_mime_type($filePath);
         $name = $fileObj->Name;
         header("Content-Type: {$mimeType}");
         header("Content-Disposition: attachment; filename=\"{$name}\"");
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         set_time_limit(0);
         $file = @fopen($filePath, "rb");
         while (!feof($file)) {
             print @fread($file, 1024 * 8);
             ob_flush();
             flush();
         }
         exit;
     } else {
         $this->httpError(404);
     }
 }
 /**
  * Handler to view a generated report file
  *
  * @param type $data
  * @param type $form
  */
 public function viewreport($request)
 {
     $item = 1;
     $allowed = array('html', 'pdf', 'csv');
     $ext = $request->getExtension();
     if (!in_array($ext, $allowed)) {
         return $this->httpError(404);
     }
     $reportID = (int) $request->param('ID');
     $fileID = (int) $request->param('OtherID');
     $report = AdvancedReport::get()->byID($reportID);
     if (!$report || !$report->canView()) {
         return $this->httpError(404);
     }
     $file = $report->{strtoupper($ext) . 'File'}();
     if (!$file || !strlen($file->Content)) {
         return $this->httpError(404);
     }
     $mimeType = HTTP::get_mime_type($file->Name);
     header("Content-Type: {$mimeType}; name=\"" . addslashes($file->Name) . "\"");
     header("Content-Disposition: attachment; filename=" . addslashes($file->Name));
     header("Content-Length: {$file->getSize()}");
     header("Pragma: ");
     session_write_close();
     ob_flush();
     flush();
     // Push the file while not EOF and connection exists
     echo base64_decode($file->Content);
     exit;
 }
 /**
  * Test that the the get_mime_type() works correctly
  * 
  */
 public function testGetMimeType()
 {
     $this->assertEquals('text/plain', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.csv'));
     $this->assertEquals('image/gif', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.gif'));
     $this->assertEquals('text/html', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.html'));
     $this->assertEquals('image/jpeg', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.jpg'));
     $this->assertEquals('image/png', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.png'));
     $this->assertEquals('image/vnd.adobe.photoshop', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.psd'));
     $this->assertEquals('audio/x-wav', HTTP::get_mime_type(FRAMEWORK_DIR . '/tests/control/files/file.wav'));
 }
 /**
  * Write content to haylix storage
  *
  * @param mixed $content 
  * @param string $name
  *				The name that is used to refer to this piece of content, 
  *				if needed
  */
 public function write($content = null, $fullname = '')
 {
     $this->getHaylix()->add_container($this->publicContainer);
     $this->getHaylix()->public_container($this->publicContainer);
     $reader = $this->getReaderWrapper($content);
     $name = basename($fullname);
     if (!$this->id) {
         if (!$name) {
             throw new Exception("Cannot write a file without a name");
         }
         $this->id = $this->nameToId($fullname);
     }
     $type = null;
     if (class_exists('HTTP')) {
         $type = HTTP::get_mime_type($name);
     }
     $result = $this->getHaylix()->upload_data($this->publicContainer, $reader->read(), $this->id, $type);
     if ($result < 0) {
         throw new Exception("Failed uploading to haylix");
     }
     // print_r($this->getHaylix()->info_container($this->publicContainer));
 }
 /**
  * Write content to storage
  *
  * @param mixed $content 
  * @param string $name
  *				The name that is used to refer to this piece of content, 
  *				if needed
  */
 public function write($content = null, $fullname = '')
 {
     $reader = $this->getReaderWrapper($content);
     $name = basename($fullname);
     if (!$this->id) {
         if (!$name) {
             throw new Exception("Cannot write a file without a name");
         }
         $this->id = $this->nameToId($fullname);
     }
     $type = null;
     if (class_exists('HTTP')) {
         $type = HTTP::get_mime_type($name);
     }
     $attrs = array('Bucket' => $this->bucket, 'Key' => $this->id, 'Body' => $reader->read(), 'ACL' => $this->defaultAcl);
     if ($type) {
         $attrs['ContentType'] = $type;
     }
     $result = $this->s3Service->putObject($attrs);
     if (!$result) {
         throw new Exception("Failed uploading to S3");
     }
     // print_r($this->getHaylix()->info_container($this->publicContainer));
 }
 /**
  * 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);
 }
示例#10
0
 /**
  * Construct an SS_HTTPResponse that will deliver a file to the client
  */
 static function send_file($fileData, $fileName, $mimeType = null)
 {
     if (!$mimeType) {
         $mimeType = HTTP::get_mime_type($fileName);
     }
     $response = new SS_HTTPResponse($fileData);
     $response->addHeader("Content-Type", "{$mimeType}; name=\"" . addslashes($fileName) . "\"");
     $response->addHeader("Content-disposition", "attachment; filename=" . addslashes($fileName));
     $response->addHeader("Content-Length", strlen($fileData));
     $response->addHeader("Pragma", "");
     // Necessary because IE has issues sending files over SSL
     if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") == true) {
         $response->addHeader('Cache-Control', 'max-age=3, must-revalidate');
         // Workaround for IE6 and 7
     }
     return $response;
 }
 /**
  * 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);
 }
 public function GetMimeType()
 {
     $res = false;
     if ($this->HTML5Video()) {
         $res = HTTP::get_mime_type($this->HTML5Video()->getFilename());
         if ($res == "video/x-flv") {
             $res = "video/flv";
         }
     }
     return $res;
 }
示例#13
0
/**
 * Encode the contents of a file for emailing, including headers
 * 
 * $file can be an array, in which case it expects these members:
 *   'filename'        - the filename of the file
 *   'contents'        - the raw binary contents of the file as a string
 *  and can optionally include these members:
 *   'mimetype'        - the mimetype of the file (calculated from filename if missing)
 *   'contentLocation' - the 'Content-Location' header value for the file
 *   
 * $file can also be a string, in which case it is assumed to be the filename
 * 
 * h5. contentLocation
 * 
 * Content Location is one of the two methods allowed for embedding images into an html email. It's also the simplest,
 * and best supported.
 * 
 * Assume we have an email with this in the body:
 * 
 *   <img src="http://example.com/image.gif" />
 * 
 * To display the image, an email viewer would have to download the image from the web every time it is displayed. Due
 * to privacy issues, most viewers will not display any images unless the user clicks 'Show images in this email'. Not
 * optimal.
 * 
 * However, we can also include a copy of this image as an attached file in the email. By giving it a contentLocation
 * of "http://example.com/image.gif" most email viewers will use this attached copy instead of downloading it. Better,
 * most viewers will show it without a 'Show images in this email' conformation.
 * 
 * Here is an example of passing this information through Email.php:
 * 
 *   $email = new Email();
 *   $email->attachments[] = array(
 *     'filename' => BASE_PATH . "/themes/mytheme/images/header.gif",
 *     'contents' => file_get_contents(BASE_PATH . "/themes/mytheme/images/header.gif"),
 *     'mimetype' => 'image/gif',
 *     'contentLocation' => Director::absoluteBaseURL() . "/themes/mytheme/images/header.gif"
 *   );
 * 
 */
function encodeFileForEmail($file, $destFileName = false, $disposition = NULL, $extraHeaders = "")
{
    if (!$file) {
        user_error("encodeFileForEmail: not passed a filename and/or data", E_USER_WARNING);
        return;
    }
    if (is_string($file)) {
        $file = array('filename' => $file);
        $fh = fopen($file['filename'], "rb");
        if ($fh) {
            while (!feof($fh)) {
                $file['contents'] .= fread($fh, 10000);
            }
            fclose($fh);
        }
    }
    // Build headers, including content type
    if (!$destFileName) {
        $base = basename($file['filename']);
    } else {
        $base = $destFileName;
    }
    $mimeType = $file['mimetype'] ? $file['mimetype'] : HTTP::get_mime_type($file['filename']);
    if (!$mimeType) {
        $mimeType = "application/unknown";
    }
    if (empty($disposition)) {
        $disposition = isset($file['contentLocation']) ? 'inline' : 'attachment';
    }
    // Encode for emailing
    if (substr($file['mimetype'], 0, 4) != 'text') {
        $encoding = "base64";
        $file['contents'] = chunk_split(base64_encode($file['contents']));
    } else {
        // This mime type is needed, otherwise some clients will show it as an inline attachment
        $mimeType = 'application/octet-stream';
        $encoding = "quoted-printable";
        $file['contents'] = QuotedPrintable_encode($file['contents']);
    }
    $headers = "Content-type: {$mimeType};\n\tname=\"{$base}\"\n" . "Content-Transfer-Encoding: {$encoding}\n" . "Content-Disposition: {$disposition};\n\tfilename=\"{$base}\"\n";
    if (isset($file['contentLocation'])) {
        $headers .= 'Content-Location: ' . $file['contentLocation'] . "\n";
    }
    $headers .= $extraHeaders . "\n";
    // Return completed packet
    return $headers . $file['contents'];
}
 /**
  * Add file upload support
  *
  * A typical SilverStripe attachement looks like this :
  *
  * array(
  * 'contents' => $data,
  * 'filename' => $filename,
  * 'mimetype' => $mimetype,
  * );
  *
  * @link https://support.sparkpost.com/customer/en/portal/articles/2214831-sending-attachments-in-sparkpost-and-sparkpost-elite
  * @param string|array $file The name of the file or a silverstripe array
  * @param string $destFileName
  * @param string $disposition
  * @param string $extraHeaders
  * @return array
  */
 public function encodeFileForEmail($file, $destFileName = false, $disposition = null, $extraHeaders = "")
 {
     if (!$file) {
         throw new Exception("encodeFileForEmail: not passed a filename and/or data");
     }
     if (is_string($file)) {
         $file = ['filename' => $file];
         $file['contents'] = file_get_contents($file['filename']);
     }
     if (empty($file['contents'])) {
         throw new Exception('A file should have some contents');
     }
     $name = $destFileName;
     if (!$destFileName) {
         $name = basename($file['filename']);
     }
     $mimeType = !empty($file['mimetype']) ? $file['mimetype'] : HTTP::get_mime_type($file['filename']);
     if (!$mimeType) {
         $mimeType = "application/unknown";
     }
     $content = $file['contents'];
     $content = base64_encode($content);
     // Return completed packet
     return ['type' => $mimeType, 'name' => $name, 'data' => $content];
 }
 /**
  * 
  * @param File $file
  * @return void
  */
 public function sendFileToBrowser($file)
 {
     $path = $file->getFullPath();
     if (SapphireTest::is_running_test()) {
         return file_get_contents($path);
     }
     $basename = basename($path);
     $length = $file->getAbsoluteSize();
     $type = HTTP::get_mime_type($file->getRelativePath());
     //handling time limitation
     if ($threshold = $this->config()->bandwidth_threshold) {
         increase_time_limit_to((int) ($length / $threshold));
     } else {
         increase_time_limit_to();
     }
     // send header
     header('Content-Description: File Transfer');
     /*
      * allow inline 'save as' popup, double quotation is present to prevent browser (eg. Firefox) from handling
      * wrongly a file with a name with whitespace, through a file in SilverStripe should not contain any whitespace
      * if the file is uploaded through SS interface
      * http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download
      */
     header('Content-Type: ' . $type);
     header('Content-Disposition: inline; filename=' . $basename);
     header('Content-Transfer-Encoding: binary');
     header('Content-Length: ' . $length);
     /**
      * issue fixes for IE6,7,8  when downloading a file over HTTPS (http://support.microsoft.com/kb/812935)
      * http://www.dotvoid.com/2009/10/problem-with-downloading-files-with-internet-explorer-over-https/
      */
     if (Director::is_https()) {
         header('Pragma: ');
     }
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     /**
      * unload the php session file
      * see http://konrness.com/php5/how-to-prevent-blocking-php-requests
      */
     session_write_close();
     // if output buffering is active, we clear it to prevent the script from trying to to allocate memory for entire file.
     while (ob_get_level() > 0) {
         ob_end_clean();
     }
     flush();
     readfile($path);
     exit(0);
 }
 /**
  * Add file upload support to mandrill
  *
  * A typical Silverstripe attachement looks like this :
  *
  * array(
  * 'contents' => $data,
  * 'filename' => $filename,
  * 'mimetype' => $mimetype,
  * );
  *
  * @param string|array $file The name of the file or a silverstripe array
  * @param string $destFileName
  * @param string $disposition
  * @param string $extraHeaders
  * @return array
  */
 function encodeFileForEmail($file, $destFileName = false, $disposition = NULL, $extraHeaders = "")
 {
     if (!$file) {
         user_error("encodeFileForEmail: not passed a filename and/or data", E_USER_WARNING);
         return;
     }
     if (is_string($file)) {
         $file = array('filename' => $file);
         $fh = fopen($file['filename'], "rb");
         if ($fh) {
             $file['contents'] = "";
             while (!feof($fh)) {
                 $file['contents'] .= fread($fh, 10000);
             }
             fclose($fh);
         }
     }
     if (!isset($file['contents'])) {
         throw new Exception('A file should have some contents');
     }
     $name = $destFileName;
     if (!$destFileName) {
         $name = basename($file['filename']);
     }
     $mimeType = !empty($file['mimetype']) ? $file['mimetype'] : HTTP::get_mime_type($file['filename']);
     if (!$mimeType) {
         $mimeType = "application/unknown";
     }
     $content = $file['contents'];
     $content = base64_encode($content);
     // Return completed packet
     return array('type' => $mimeType, 'name' => $name, 'content' => $content);
 }
 /**
  * Provides better fallbackfor {@link HTTP::getMimeType}
  * @param string $file File name or path
  * @return string|null Mime type of the passed in file, if known
  */
 protected function getMimeType($file)
 {
     return HTTP::get_mime_type($file);
 }
 /**
  * We need to offset the sending of emails so we can change the content based on the payment status
  *
  * @param $recipients
  * @param $attachments
  * @param $submittedFields
  * @param $payment
  */
 function SendEmailsToRecipients($recipients, $attachments, $submittedFields, $payment)
 {
     $email = new UserDefinedPaymentForm_SubmittedPaymentFormEmail($submittedFields);
     $email->PaymentID = $payment->ID;
     $receipt_number = "";
     if ($purchased_response = PurchasedResponse::get()->filter("PaymentID", $payment->ID)->first()) {
         $receipt_number = $purchased_response->Reference;
     }
     $emailData = array("Sender" => Member::currentUser(), "Fields" => $submittedFields, "Payment" => $payment, "ReceiptNumber" => $receipt_number);
     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();
         }
     }
 }
 /**
  * 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;
 }
示例#20
0
 /**
  * Construct an SS_HTTPResponse that will deliver a file to the client
  *
  * @static
  * @param $fileData
  * @param $fileName
  * @param null $mimeType
  * @return SS_HTTPResponse
  */
 public static function send_file($fileData, $fileName, $mimeType = null)
 {
     if (!$mimeType) {
         $mimeType = HTTP::get_mime_type($fileName);
     }
     $response = new SS_HTTPResponse($fileData);
     $response->addHeader("Content-Type", "{$mimeType}; name=\"" . addslashes($fileName) . "\"");
     // Note a IE-only fix that inspects this header in HTTP::add_cache_headers().
     $response->addHeader("Content-disposition", "attachment; filename=" . addslashes($fileName));
     $response->addHeader("Content-Length", strlen($fileData));
     return $response;
 }
示例#21
0
 /**
  * @param Mime\Message $message
  * @param $file
  * @param string|null $as
  */
 private function addAttachment(Mime\Message $message, $file, $as = null)
 {
     if (is_string($file)) {
         $file = array('filename' => $file, 'contents' => file_get_contents($file));
     }
     if (!isset($file['mimetype'])) {
         $file['mimetype'] = \HTTP::get_mime_type($file['filename']) ?: 'application/unknown';
     }
     $attachment = new Mime\Part($file['contents']);
     $attachment->type = $file['mimetype'];
     $attachment->filename = $as ?: basename($file['filename']);
     $attachment->disposition = Mime\Mime::DISPOSITION_ATTACHMENT;
     $message->addPart($attachment);
 }