/** * Outputs appropriate header for downloading a file * exits() after the call, so that no further output is given. * * @deprecated 2.3 Return a HTTPRequest::send_file() object instead */ static function sendFileToBrowser($fileData, $fileName, $mimeType = false) { user_error("HTTP::sendFileToBrowser() deprecated; return a HTTPRequest::send_file() object instead", E_USER_NOTICE); HTTPRequest::send_file($fileData, $fileName, $mimeType)->output(); exit(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 HTTPRequest::send_file($fileData, $fileName); }else{ user_error("No records found", E_USER_ERROR); } }
/** * 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); } }
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}/{$page->URLSegment}"; $contentfile = "{$tmpFolder}/{$page->URLSegment}/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 = HTTPRequest::send_file($archiveContent, "{$baseFolderName}.tar.gz", 'application/x-tar-gz'); echo $response->output(); }
/** * 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); } }
/** * 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(); } }