コード例 #1
0
 /**
  * @return SS_HTTPRequest
  */
 public function backup()
 {
     $name = 'assets_' . SS_DateTime::now()->Format('Y-m-d') . '.zip';
     $tmpName = TEMP_FOLDER . '/' . $name;
     $zip = new ZipArchive();
     if (!$zip->open($tmpName, ZipArchive::OVERWRITE)) {
         user_error('Asset Export Extension: Unable to read/write temporary zip archive', E_USER_ERROR);
         return;
     }
     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(ASSETS_PATH, RecursiveDirectoryIterator::SKIP_DOTS));
     foreach ($files as $file) {
         $local = str_replace(ASSETS_PATH . '/', '', $file);
         $zip->addFile($file, $local);
     }
     if (!$zip->status == ZipArchive::ER_OK) {
         user_error('Asset Export Extension: ZipArchive returned an error other than OK', E_USER_ERROR);
         return;
     }
     $zip->close();
     if (ob_get_length()) {
         @ob_flush();
         @flush();
         @ob_end_flush();
     }
     @ob_start();
     $content = file_get_contents($tmpName);
     unlink($tmpName);
     return SS_HTTPRequest::send_file($content, $name);
 }
コード例 #2
0
 /**
  * Handle the export, for both the action button and the URL
  */
 public function handleExport($gridField, $request = null)
 {
     $now = Date("d-m-Y-H-i");
     $fileName = "export-{$now}.csv";
     if ($fileData = $this->generateExportFileData($gridField)) {
         return SS_HTTPRequest::send_file($fileData, $fileName, 'text/csv');
     }
 }
 /**
  * Handle the export, for both the action button and the URL
  */
 public function handleExport($gridField, $request = null)
 {
     $now = Date("d-m-Y-H-i");
     $modelClass = $gridField->getModelClass();
     $fileName = "export-{$modelClass}-{$now}.xlsx";
     if ($fileData = $this->generateExportFileData($gridField)) {
         return SS_HTTPRequest::send_file($fileData, $fileName, 'application/xslt+xml');
     }
 }
コード例 #4
0
 /**
  * Handle the export, for both the action button and the URL
  */
 public function handleExport($gridField, $request = null)
 {
     $now = date("d-m-Y-H-i");
     $title = str_replace(' ', '-', strtolower(singleton($gridField->getModelClass())->singular_name()));
     $fileName = "export-{$title}-{$now}.xls";
     if ($fileData = $this->generateExportFileData($gridField)) {
         return SS_HTTPRequest::send_file($fileData, $fileName, 'application/xls+xml');
     }
 }
 public function reportpreview($data, $form)
 {
     $data = $form->getData();
     $format = $data['PreviewFormat'];
     $result = $this->record->createReport($format);
     if ($result->content) {
         return $result->content;
     } else {
         return SS_HTTPRequest::send_file(file_get_contents($result->filename), "{$data['GeneratedReportTitle']}.{$format}");
     }
 }
コード例 #6
0
 public function handleAction(GridField $gridField, $actionName, $arguments, $data)
 {
     if (isset($arguments['FileID'])) {
         $response = Controller::curr()->getResponse();
         $file = File::get()->byID($arguments['FileID']);
         $path = $file->getFullPath();
         $filename = $file->getFileName();
         return SS_HTTPRequest::send_file(file_get_contents($path), $filename);
     }
     Controller::curr()->getResponse()->setStatusCode(200, 'No File');
 }
コード例 #7
0
 /**
  * Sends download request to registered members
  * 
  * @param	object	GET 'filename' request 
  * @return	object	HTTP request
  */
 public function download(SS_HTTPRequest $request)
 {
     $filename = $request->param('Filename');
     if (Member::currentUserID() && $request->isGET() && !empty($filename)) {
         $file = DB::query("SELECT Filename FROM File  WHERE Name = '" . Convert::raw2sql($filename) . "'")->value();
         if (!empty($file) && Director::fileExists($file)) {
             $file_contents = file_get_contents(Director::getAbsFile($file));
             return SS_HTTPRequest::send_file($file_contents, $filename);
         }
     }
     return Security::permissionFailure($this);
 }
 /**
  * Controller action for downloading a Clean File.
  * It responds to urls matching the following pattern:
  * 
  * /download/ClassName/ID
  * 
  * like:
  * 
  * /download/CleanFile/1
  * /download/CleanImage/1
  *
  * @param $request
  * @return SS_HTTPRequest
  */
 function download($request)
 {
     $classname = Convert::raw2sql($request->latestParam('ID'));
     $id = Convert::raw2sql($request->latestParam('OtherID'));
     if (is_numeric($id) && $classname != '' && $id != '') {
         if ($file = DataObject::get_by_id($classname, $id)) {
             if ($file->AttachmentID != 0 && isset($file->AttachmentID)) {
                 return SS_HTTPRequest::send_file(file_get_contents($file->Attachment()->getFullPath()), $file->Attachment()->Name);
             }
         }
     }
     return $this->owner->redirect($this->owner->Link());
 }
 public function ticketfile()
 {
     if (!$this->HasTicketFile() || $this->registration->Status != 'Valid') {
         $this->httpError(404);
     }
     $generator = $this->registration->Time()->Event()->TicketGenerator;
     $generator = new $generator();
     $path = $generator->generateTicketFileFor($this->registration);
     $path = Director::getAbsFile($path);
     $name = $generator->getTicketFilenameFor($this->registration);
     $mime = $generator->getTicketMimeTypeFor($this->registration);
     if (!$path || !file_exists($path)) {
         $this->httpError(404, 'The ticket file could not be generated.');
     }
     return SS_HTTPRequest::send_file(file_get_contents($path), $name, $mime);
 }
 function run($request)
 {
     //reset time limit
     set_time_limit(1200);
     //file data
     $now = Date("d-m-Y-H-i");
     $fileName = "export-{$now}.csv";
     //data object variables
     $orderStatusSubmissionLog = EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order");
     $fileData = "";
     $offset = 0;
     $count = 50;
     while ($orders = Order::get()->sort("\"Order\".\"ID\" ASC")->innerJoin("OrderStatusLog", "\"Order\".\"ID\" = \"OrderStatusLog\".\"OrderID\"")->innerJoin($orderStatusSubmissionLog, "\"{$orderStatusSubmissionLog}\".\"ID\" = \"OrderStatusLog\".\"ID\"")->leftJoin("Member", "\"Member\".\"ID\" = \"Order\".\"MemberID\"")->limit($count, $offset) && ($ordersCount = $orders->count())) {
         $offset = $offset + $count;
         foreach ($orders as $order) {
             if ($order->IsSubmitted()) {
                 $memberIsOK = false;
                 if (!$order->MemberID) {
                     $memberIsOK = true;
                 } elseif (!$order->Member()) {
                     $memberIsOK = true;
                 } elseif ($member = $order->Member()) {
                     $memberIsOK = true;
                     if ($member->IsShopAdmin()) {
                         $memberIsOK = false;
                     }
                 }
                 if ($memberIsOK) {
                     $items = OrderItem::get()->filter(array("OrderID" => $order->ID));
                     if ($items && $items->count()) {
                         $fileData .= $this->generateExportFileData($order->getOrderEmail(), $order->SubmissionLog()->Created, $items);
                     }
                 }
             }
         }
         unset($orders);
     }
     if ($fileData) {
         SS_HTTPRequest::send_file($fileData, $fileName, "text/csv");
     } else {
         user_error("No records found", E_USER_ERROR);
     }
 }
コード例 #11
0
 public function downloadExport($gridField, $request = null)
 {
     $id = $request->param('ID');
     $job = ExportQueue::get()->filter('Signature', $id)->first();
     if ((int) $job->MemberID !== (int) Member::currentUserID()) {
         return Security::permissionFailure();
     }
     $now = Date("d-m-Y-H-i");
     $servedName = "export-{$now}.csv";
     $path = $this->getExportPath($id);
     $content = file_get_contents($path);
     unlink($path);
     rmdir(dirname($path));
     $response = SS_HTTPRequest::send_file($content, $servedName, 'text/csv');
     $response->addHeader('Set-Cookie', 'downloaded_' . $id . '=true; Path=/');
     $job->AddAction('Downloaded');
     return $response;
 }
コード例 #12
0
 /**
  * Allows the user to download a file without right-clicking
  */
 function download()
 {
     if (isset($this->urlParams['ID'])) {
         $SQL_ID = Convert::raw2sql($this->urlParams['ID']);
         if (is_numeric($SQL_ID)) {
             $file = DataObject::get_by_id("Post_Attachment", $SQL_ID);
             $response = SS_HTTPRequest::send_file(file_get_contents($file->getFullPath()), $file->Name);
             $response->output();
         }
     }
     return Director::redirectBack();
 }
コード例 #13
0
ファイル: ManageHeatmaps.php プロジェクト: hemant-chakka/awss
 public function downloadHeatmap($request)
 {
     $imageId = $request->param('ID');
     $image = File::get()->byID($imageId);
     return SS_HTTPRequest::send_file(file_get_contents(Director::absoluteBaseURL() . $image->Filename), $image->Name);
 }
 public function exportastarball()
 {
     $template = $this->getCurrentDynamicTemplate();
     if (!$template) {
         FormResponse::status_message("No template selected, Please select template");
         FormResponse::load_form($this->getitem(), 'Form_EditForm');
         return FormResponse::respond();
     } else {
         $fileData = $template->exportAs("tar.gz");
         $fileName = $template->Name . ".tar.gz";
         return SS_HTTPRequest::send_file($fileData, $fileName, "application/x-tar");
     }
 }
コード例 #15
0
 public function export()
 {
     if (isset($_REQUEST['baseurl'])) {
         $base = $_REQUEST['baseurl'];
         if (substr($base, -1) != '/') {
             $base .= '/';
         }
         Config::inst()->update('Director', 'alternate_base_url', $base);
     } else {
         $base = Director::baseURL();
     }
     $folder = TEMP_FOLDER . '/static-export';
     $project = project();
     $exported = $this->doExport($base, $folder . '/' . $project, false);
     `cd {$folder}; tar -czhf {$project}-export.tar.gz {$project}`;
     $archiveContent = file_get_contents("{$folder}/{$project}-export.tar.gz");
     // return as download to the client
     $response = SS_HTTPRequest::send_file($archiveContent, "{$project}-export.tar.gz", 'application/x-tar-gz');
     echo $response->output();
 }
コード例 #16
0
 /**
  * Export each of the form submissions for this UserDefinedForm
  * instance into a CSV file.
  * 
  * In order to run this export function, the user must be
  * able to edit the page, so we check canEdit()
  *
  * @return HTTPResponse / bool
  */
 public function export()
 {
     $now = Date("Y-m-d_h.i.s");
     $fileName = "export-{$now}.csv";
     $separator = ",";
     // Get the UserDefinedForm to export data from the URL
     $SQL_ID = isset($_REQUEST['id']) ? Convert::raw2sql($_REQUEST['id']) : false;
     if ($SQL_ID) {
         $udf = DataObject::get_by_id("UserDefinedForm", $SQL_ID);
         if ($udf) {
             $submissions = $udf->Submissions();
             if ($submissions && $submissions->Count() > 0) {
                 // Get all the submission IDs (so we know what names/titles to get - helps for sites with many UDF's)
                 $inClause = array();
                 foreach ($submissions as $submission) {
                     $inClause[] = $submission->ID;
                 }
                 // Get the CSV header rows from the database
                 $tmp = DB::query("SELECT DISTINCT \"SubmittedFormField\".\"ID\", \"Name\", \"Title\"\n\t\t\t\t\t\tFROM \"SubmittedFormField\"\n\t\t\t\t\t\tLEFT JOIN \"SubmittedForm\" ON \"SubmittedForm\".\"ID\" = \"SubmittedFormField\".\"ParentID\"\n\t\t\t\t\t\tWHERE \"SubmittedFormField\".\"ParentID\" IN (" . implode(',', $inClause) . ")\n\t\t\t\t\t\tORDER BY \"SubmittedFormField\".\"ID\"");
                 // Sort the Names and Titles from the database query into separate keyed arrays
                 foreach ($tmp as $array) {
                     $csvHeaderNames[] = $array['Name'];
                     $csvHeaderTitle[] = $array['Title'];
                 }
                 // We need Headers to be unique, query is returning headers multiple times (number of submissions).
                 // TODO: Fix query
                 $csvHeaderNames = array_unique($csvHeaderNames);
                 $csvHeaderTitle = array_unique($csvHeaderTitle);
                 // For every submission...
                 $i = 0;
                 foreach ($submissions as $submission) {
                     // Get the rows for this submission (One row = one form field)
                     $dataRow = $submission->FieldValues();
                     $rows[$i] = array();
                     // For every row/field, get all the columns
                     foreach ($dataRow as $column) {
                         // If the Name of this field is in the $csvHeaderNames array, get an array of all the places it exists
                         if ($index = array_keys($csvHeaderNames, $column->Name)) {
                             if (is_array($index)) {
                                 // Set the final output array for each index that we want to insert this value into
                                 foreach ($index as $idx) {
                                     $rows[$i][$idx] = $column->Value;
                                 }
                                 $rows[$i]['Submitted'] = $submission->Created;
                             }
                         }
                     }
                     $i++;
                 }
                 // CSV header row
                 $csvData = '"' . implode('","', $csvHeaderTitle) . '"' . ',"Submitted"' . "\n";
                 // For every row of data (one form submission = one row)
                 foreach ($rows as $row) {
                     // Loop over all the names we can use
                     for ($i = 0; $i < count($csvHeaderNames); $i++) {
                         if (!isset($row[$i]) || !$row[$i]) {
                             $csvData .= '"",';
                         } else {
                             $csvData .= '"' . str_replace('"', '\\"', $row[$i]) . '",';
                         }
                     }
                     // Start a new row for each submission
                     $csvData .= '"' . $row['Submitted'] . '"' . "\n";
                 }
             } else {
                 user_error("No submissions to export.", E_USER_ERROR);
             }
             if (class_exists('SS_HTTPRequest')) {
                 SS_HTTPRequest::send_file($csvData, $fileName)->output();
             } else {
                 HTTPRequest::send_file($csvData, $fileName)->output();
             }
         } else {
             user_error("'{$SQL_ID}' is a valid type, but we can't find a UserDefinedForm in the database that matches the ID.", E_USER_ERROR);
         }
     } else {
         user_error("'{$SQL_ID}' is not a valid UserDefinedForm ID.", E_USER_ERROR);
     }
 }
コード例 #17
0
 /**
  * File found response
  *
  * @param $file File to send
  * @param $alternate_path string If supplied, return the file from this path instead, for
  * example, resampled images.
  */
 function fileFound(File $file, $alternate_path = null)
 {
     // File properties
     $file_name = $file->Name;
     $file_path = Director::getAbsFile($alternate_path ? $alternate_path : $file->FullPath);
     $file_size = filesize($file_path);
     // Testing mode - return an HTTPResponse
     if (self::$use_ss_sendfile) {
         if (ClassInfo::exists('SS_HTTPRequest')) {
             return SS_HTTPRequest::send_file(file_get_contents($file_path), $file_name);
         } else {
             return HTTPRequest::send_file(file_get_contents($file_path), $file_name);
         }
     }
     // Normal operation:
     $mimeType = HTTP::getMimeType($file_name);
     header("Content-Type: {$mimeType}; name=\"" . addslashes($file_name) . "\"");
     header("Content-Disposition: attachment; filename=" . addslashes($file_name));
     header("Cache-Control: max-age=1, private");
     header("Content-Length: {$file_size}");
     header("Pragma: ");
     if (self::$use_x_sendfile) {
         session_write_close();
         header('X-Sendfile: ' . $file_path);
         exit;
     } elseif ($filePointer = @fopen($file_path, 'rb')) {
         session_write_close();
         $this->flush();
         // Push the file while not EOF and connection exists
         while (!feof($filePointer) && !connection_aborted()) {
             print fread($filePointer, 1024 * self::$chunck_size_kb);
             $this->flush();
         }
         fclose($filePointer);
         exit;
     } else {
         // Edge case - either not found anymore or can't read
         return $this->fileNotFound();
     }
 }
コード例 #18
0
 public function downloadPDF()
 {
     // We only allow producing live pdf. There is no way to secure the draft files.
     Versioned::reading_stage('Live');
     $path = $this->owner->dataRecord->getPdfFilename();
     if (!file_exists($path)) {
         $this->generatePDF();
     }
     return SS_HTTPRequest::send_file(file_get_contents($path), basename($path), 'application/pdf');
 }
 function download($request)
 {
     $id = intval($request->param("ID"));
     if ($id) {
         $obj = DatabasebackupLog::get()->byID($id);
         return SS_HTTPRequest::send_file(file_get_contents($obj->FullLocation), basename($obj->FullLocation));
     }
     user_error("Could not action download", E_USER_WARNING);
 }
 /**
  * Overidden to exclude certain fields (IE Save) from the export. Additionally,
  * we need to trim the result set of fields that don't exist in the field anymore, even if there
  * are form submissions that have values for those non-existent fields.
  */
 public function export($fileName = null)
 {
     $separator = ",";
     // Get the UserDefinedForm to export data from the URL
     $SQL_ID = isset($_REQUEST['id']) ? Convert::raw2sql($_REQUEST['id']) : false;
     if ($SQL_ID) {
         $udf = DataObject::get_by_id("UserDefinedForm", $SQL_ID);
         if ($udf) {
             $fileName = str_replace(' ', '_', $udf->MenuTitle . '-' . date('Y-m-d_H.i.s') . '.csv');
             // we'll limit submissions to only those that are completed.
             $submissions = $udf->Submissions();
             //'"SubmissionStatus" = \'Complete\'');
             if ($submissions && $submissions->Count() > 0) {
                 // Get all the submission IDs (so we know what names/titles to get - helps for sites with many UDF's)
                 $inClause = array();
                 foreach ($submissions as $submission) {
                     $inClause[] = $submission->ID;
                 }
                 // Get the CSV header rows from the database
                 $tmp = DB::query("SELECT DISTINCT \"SubmittedFormField\".\"ID\", \"Name\", \"Title\"\n\t\t\t\t\t\tFROM \"SubmittedFormField\"\n\t\t\t\t\t\tLEFT JOIN \"SubmittedForm\" ON \"SubmittedForm\".\"ID\" = \"SubmittedFormField\".\"ParentID\"\n\t\t\t\t\t\tWHERE  \"SubmittedFormField\".\"ParentID\" IN (" . implode(',', $inClause) . ")\n\t\t\t\t\t\tORDER BY \"SubmittedFormField\".\"ID\"");
                 // Sort the Names and Titles from the database query into separate keyed arrays
                 $stored = array();
                 foreach ($tmp as $array) {
                     // only store if we haven't got this field already
                     // TODO Specific hack here to handle save fields in editable user forms
                     if (!isset($stored[$array['Name']]) && $array['Title'] != 'Save') {
                         $csvHeaderNames[] = $array['Name'];
                         $csvHeaderTitle[] = $array['Title'];
                         $stored[$array['Name']] = true;
                     }
                 }
                 // For every submission...
                 $i = 0;
                 foreach ($submissions as $submission) {
                     // Get the rows for this submission (One row = one form field)
                     $dataRow = $submission->Values();
                     $rows[$i] = array();
                     // For every row/field, get all the columns
                     foreach ($dataRow as $column) {
                         // If the Name of this field is in the $csvHeaderNames array, get an array of all the places it exists
                         if ($index = array_keys($csvHeaderNames, $column->Name)) {
                             if (is_array($index)) {
                                 // Set the final output array for each index that we want to insert this value into
                                 foreach ($index as $idx) {
                                     $rows[$i][$idx] = $column->Value;
                                 }
                                 $rows[$i]['SubmissionStatus'] = $submission->SubmissionStatus;
                                 $rows[$i]['Submitted'] = $submission->LastEdited;
                             }
                         }
                     }
                     $i++;
                 }
                 $csvHeaderTitle[] = "Status";
                 $csvHeaderTitle[] = "Submitted";
                 // CSV header row
                 $csvData = '"' . implode('","', $csvHeaderTitle) . '"' . "\n";
                 // For every row of data (one form submission = one row)
                 foreach ($rows as $row) {
                     // Loop over all the names we can use
                     for ($i = 0; $i < count($csvHeaderNames); $i++) {
                         if (!isset($row[$i]) || !$row[$i]) {
                             $csvData .= '"",';
                         } else {
                             $csvData .= '"' . str_replace('"', '\\"', $row[$i]) . '",';
                         }
                     }
                     // Start a new row for each submission
                     $csvData .= '"' . $row['SubmissionStatus'] . '",' . '"' . $row['Submitted'] . '"' . "\n";
                 }
             } else {
                 user_error("No submissions to export.", E_USER_ERROR);
             }
             if (class_exists('SS_HTTPRequest')) {
                 SS_HTTPRequest::send_file($csvData, $fileName)->output();
             } else {
                 HTTPRequest::send_file($csvData, $fileName)->output();
             }
         } else {
             user_error("'{$SQL_ID}' is a valid type, but we can't find a UserDefinedForm in the database that matches the ID.", E_USER_ERROR);
         }
     } else {
         user_error("'{$SQL_ID}' is not a valid UserDefinedForm ID.", E_USER_ERROR);
     }
 }
コード例 #21
0
 /**
  * Exports a given set of comma-separated IDs (from a previous search-query, stored in a HiddenField).
  * Uses {$csv_columns} if present, and falls back to {$result_columns}.
  * We move the most filedata generation code to the function {@link generateExportFileData()} so that a child class
  * could reuse the filedata generation code while overwrite export function.
  * 
  * @todo Make relation-syntax available (at the moment you'll have to use custom sql) 
  */
 function export()
 {
     $now = Date("d-m-Y-H-i");
     $fileName = "export-{$now}.csv";
     // No pagination for export
     $oldShowPagination = $this->showPagination;
     $this->showPagination = false;
     $result = $this->renderWith(array($this->template . '_printable', 'TableListField_printable'));
     $this->showPagination = $oldShowPagination;
     if ($fileData = $this->generateExportFileData($numColumns, $numRows)) {
         return SS_HTTPRequest::send_file($fileData, $fileName);
     } else {
         user_error("No records found", E_USER_ERROR);
     }
 }
コード例 #22
0
 function export()
 {
     // specify custom baseurl for publishing to other webroot
     if (isset($_REQUEST['baseurl'])) {
         $base = $_REQUEST['baseurl'];
         if (substr($base, -1) != '/') {
             $base .= '/';
         }
         Director::setBaseURL($base);
     }
     // setup temporary folders
     $tmpBaseFolder = TEMP_FOLDER . '/static-export';
     $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site";
     if (!file_exists($tmpFolder)) {
         Filesystem::makeFolder($tmpFolder);
     }
     $baseFolderName = basename($tmpFolder);
     // symlink /assets
     $f1 = ASSETS_PATH;
     $f2 = Director::baseFolder() . '/' . project();
     `cd {$tmpFolder}; ln -s {$f1}; ln -s {$f2}`;
     // iterate through all instances of SiteTree
     $pages = DataObject::get("SiteTree");
     foreach ($pages as $page) {
         $subfolder = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/');
         $contentfile = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/') . '/index.html';
         // Make the folder
         if (!file_exists($subfolder)) {
             Filesystem::makeFolder($subfolder);
         }
         // Run the page
         Requirements::clear();
         $link = Director::makeRelative($page->Link());
         $response = Director::test($link);
         // Write to file
         if ($fh = fopen($contentfile, 'w')) {
             fwrite($fh, $response->getBody());
             fclose($fh);
         }
     }
     // copy homepage (URLSegment: "home") to webroot
     copy("{$tmpFolder}/home/index.html", "{$tmpFolder}/index.html");
     // archive all generated files
     `cd {$tmpBaseFolder}; tar -czhf {$baseFolderName}.tar.gz {$baseFolderName}`;
     $archiveContent = file_get_contents("{$tmpBaseFolder}/{$baseFolderName}.tar.gz");
     // remove temporary files and folder
     Filesystem::removeFolder($tmpBaseFolder);
     // return as download to the client
     $response = SS_HTTPRequest::send_file($archiveContent, "{$baseFolderName}.tar.gz", 'application/x-tar-gz');
     echo $response->output();
 }
コード例 #23
0
 /**
  * Export each of the form submissions for this UserDefinedForm
  * instance into a CSV file.
  * 
  * In order to run this export function, the user must be
  * able to edit the page, so we check canEdit()
  *
  * @return HTTPResponse / bool
  */
 public function export($id = false)
 {
     if ($id && is_int($id)) {
         $SQL_ID = $id;
     } else {
         if (isset($_REQUEST['id'])) {
             $SQL_ID = Convert::raw2sql($_REQUEST['id']);
         } else {
             user_error("No UserDefinedForm Defined.", E_USER_ERROR);
             return false;
         }
     }
     $now = Date("Y-m-d_h.i.s");
     $fileName = "export-{$now}.csv";
     $separator = ",";
     $udf = DataObject::get_by_id("UserDefinedForm", $SQL_ID);
     if ($udf) {
         $submissions = $udf->Submissions("", "\"ID\"");
         // Collect unique columns for use in the CSV.
         // Do it separately as we need a fixed number of columns for the file.
         // Include all fields that have ever existed in this form.
         // Preserve the ordering: the most recent form setup should be dominant.
         $inClause = array();
         foreach ($submissions as $submission) {
             $inClause[] = $submission->ID;
         }
         $csvHeaders = DB::query("SELECT \"Name\" , \"Title\" FROM \"SubmittedFormField\" \n\t\t\t\t\t\t\t\t\t LEFT JOIN \"SubmittedForm\" ON \"SubmittedForm\".\"ID\" = \"SubmittedFormField\".\"ParentID\"\n\t\t\t\t\t\t\t\t\t WHERE \"SubmittedFormField\".\"ParentID\" IN (" . implode(',', $inClause) . ") \n\t\t\t\t\t\t\t\t\t ORDER BY \"SubmittedFormField\".\"ParentID\" DESC, \"SubmittedFormField\".\"ID\"\n\t\t\t\t\t\t\t\t\t");
         if ($csvHeaders) {
             $csvHeaders = $csvHeaders->map();
         }
         if ($submissions && $submissions->exists()) {
             $data = array();
             // Create CSV rows out of submissions. Fields on those submissions will become columns.
             foreach ($submissions as $submission) {
                 $fields = $submission->Values();
                 $row = array();
                 foreach ($fields as $field) {
                     $row[$field->Name] = $field->Value;
                 }
                 $row['Submitted'] = $submission->Created;
                 $data[] = $row;
             }
             // Create the CSV header line first:
             $csvData = '"' . implode('","', $csvHeaders) . '"' . ',"Submitted"' . "\n";
             // Now put the collected data under relevant columns
             foreach ($data as $row) {
                 $csvRowItems = array();
                 foreach ($csvHeaders as $columnName => $columnTitle) {
                     if (!isset($row[$columnName])) {
                         $csvRowItems[] = "";
                     } else {
                         $csvRowItems[] = str_replace('"', '""', $row[$columnName]);
                     }
                 }
                 $csvRowItems[] = $row['Submitted'];
                 // Encode the row by hand (fputcsv fails to encode newlines properly)
                 if (count($csvRowItems)) {
                     $csvData .= "\"" . implode($csvRowItems, "\",\"") . "\"\n";
                 }
             }
         } else {
             user_error("No submissions to export.", E_USER_ERROR);
         }
         if (SapphireTest::is_running_test()) {
             return $csvData;
         } else {
             SS_HTTPRequest::send_file($csvData, $fileName, 'text/csv')->output();
             exit;
         }
     } else {
         user_error("'{$SQL_ID}' is a valid type, but we can't find a UserDefinedForm in the database that matches the ID.", E_USER_ERROR);
     }
 }
コード例 #24
0
 /**
  * Exports a given set of comma-separated IDs (from a previous search-query, stored in a HiddenField).
  * Uses {$csv_columns} if present, and falls back to {$result_columns}.
  * We move the most filedata generation code to the function {@link generateExportFileData()} so that a child class
  * could reuse the filedata generation code while overwrite export function.
  * 
  * @todo Make relation-syntax available (at the moment you'll have to use custom sql) 
  */
 function export()
 {
     $now = Date("d-m-Y-H-i");
     $fileName = "export-{$now}.csv";
     if ($fileData = $this->generateExportFileData($numColumns, $numRows)) {
         return SS_HTTPRequest::send_file($fileData, $fileName);
     } else {
         user_error("No records found", E_USER_ERROR);
     }
 }
 /**
  * @return SS_HTTPRequest
  */
 public function export()
 {
     // get folder
     $folder = $this->owner->currentPage();
     $fn = $folder->exists() && $folder->getFilename() ? str_replace(ASSETS_DIR, '', $folder->getFilename()) : '';
     $path = realpath(ASSETS_PATH . $fn);
     // init zip
     $fn = preg_replace('/-+/', '-', 'assets-' . preg_replace('/[^a-zA-Z0-9]+/', '-', $fn) . '-' . SS_DateTime::now()->Format('Y-m-d') . '.zip');
     $tmpName = TEMP_FOLDER . '/' . $fn;
     $zip = new ZipArchive();
     // create zip file for writing
     if ($zip->open($tmpName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
         user_error('Asset Export Extension: Unable to read/write temporary zip archive', E_USER_ERROR);
         return;
     }
     // get whitelisted files
     $files = $this->getDirContents($path);
     // build zip
     foreach ($files as $file) {
         $local = trim(str_replace($path, '', $file), '/');
         $zip->addFile($file, $local);
     }
     // check the status
     if (!$zip->status == ZipArchive::ER_OK) {
         user_error('Asset Export Extension: ZipArchive returned an error other than OK', E_USER_ERROR);
         return;
     }
     $zip->close();
     if (ob_get_length()) {
         @ob_flush();
         @flush();
         @ob_end_flush();
     }
     @ob_start();
     $content = file_get_contents($tmpName);
     unlink($tmpName);
     return SS_HTTPRequest::send_file($content, $fn);
 }