/** * Send a download. * * @since 0.1.0 * * @param string $file An absolute file path. */ function satispress_send_file($file) { @session_write_close(); if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } if (get_magic_quotes_runtime()) { @set_magic_quotes_runtime(0); } @ini_set('zlib.output_compression', 'Off'); @set_time_limit(0); @ob_end_clean(); if (ob_get_level()) { @ob_end_clean(); // Zip corruption fix. } nocache_headers(); header('Robots: none'); header('Content-Type: application/force-download'); header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename="' . basename($file) . '";'); header('Content-Transfer-Encoding: binary'); if ($size = @filesize($file)) { header('Content-Length: ' . $size); } @readfile_chunked($file) or wp_die(__('File not found', 'satispress')); exit; }
function display_error() { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: no-cache'); header("Content-Type: image/gif"); readfile_chunked("./images/read_error48x48.gif"); exit; }
function get($task_id) { $filepath = $this->directory . '/' . $task_id . '.arff'; if (file_exists($filepath) == false) { $this->generate($task_id, $filepath); } header('Content-type: text/plain'); header('Content-Length: ' . filesize($filepath)); readfile_chunked($filepath); }
/** * This function does the action of forcing the browser to download the * specified file as well as feeds the bits of the file to the browser. * * @param string $filePath is the path to the file that we want to download. * @return int Error code if one exists. Return of 0 indicates no error. */ function download_file($filePath) { $allowed_ext = array('zip' => 'application/zip', 'pdf' => 'application/pdf', 'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'exe' => 'application/octet-stream', 'gif' => 'image/gif', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo'); $toReturn = 0; if ($filePath != "" && file_exists($filePath)) { $file_extension = strtolower(substr(strrchr($filePath, "."), 1)); // get mime type of the file. $ctype = ''; if (!array_key_exists($file_extension, $allowed_ext)) { // mime type is not set, get from server settings if (function_exists('mime_content_type')) { $ctype = mime_content_type($file_path); } else { if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); // return mime type $ctype = finfo_file($finfo, $file_path); finfo_close($finfo); } } if ($ctype == '') { $ctype = "application/force-download"; } } else { // get mime type defined by admin $ctype = $allowed_ext[$file_extension]; } $oldPath = getcwd(); // get current working directory $filePathArray = getPathArray($filePath); changeDirectory($filePathArray); $filename = getFilename($filePath); // Tell the browser the mime type of the file to be downloaded. header('Content-type: ' . $ctype); // Tell the browser what to call the file. header('Content-Disposition: attachment; filename="' . $filename . '"'); header("Content-Length: " . filesize($filename)); ob_clean(); flush(); $bytesSent = readfile_chunked($filename); $reverseFilePath = array(); for ($i = 0; $i < count($filePathArray); ++$i) { $reverseFilePath[] = ".."; } changeDirectory($reverseFilePath); // change back to the original directory $toReturn = 0; //exit; } else { $toReturn = 404; // file not found } return $toReturn; }
function download($id, $name = 'undefined') { $file = $this->File->getById($id); if ($this->_check_rights($file)) { if ($file === false || file_exists(DATA_PATH . $file->filepath) === false) { $this->_error404(); } else { $this->_header_download($file); readfile_chunked(DATA_PATH . $file->filepath); } } // else, an appropriate message is shown. }
function force_download($filename = '', $file = '') { if ($filename == '' or $file == '') { return FALSE; } // Try to determine if the filename includes a file extension. // We need it in order to set the MIME type if (FALSE === strpos($filename, '.')) { return FALSE; } // Grab the file extension $x = pathinfo($file); $extension = $x["extension"]; // Load the mime types @(include APPPATH . 'config/mimes' . EXT); // Set a default mime if we can't find it if (!isset($mimes[$extension])) { $mime = 'application/octet-stream'; } else { $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension]; } // Read the file size to pass to the // headers and also for our chunk method $size = filesize($file); // Generate the server headers if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE) { header('Content-Type: "' . $mime . '"'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header("Content-Transfer-Encoding: binary"); header('Pragma: public'); header("Content-Length: " . $size); } else { header('Content-Type: "' . $mime . '"'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header("Content-Transfer-Encoding: binary"); header('Expires: 0'); header('Pragma: no-cache'); header("Content-Length: " . $size); } readfile_chunked($file, $size); exit; }
if (!$group || !is_object($group)) { exit_error(_('Error'), _('Error creating group')); } else { if ($group->isError()) { exit_error(_('Error'), $group->getErrorMessage()); } } // Snapshot can be downloaded only if anon SCM is enabled or if the // logged in user belongs the group $permission = $group->enableAnonSCM(); if (session_loggedin()) { $perm =& $group->getPermission(session_get_user()); if ($perm && is_object($perm) && !$perm->isError() && $perm->isMember()) { $permission = true; } } if (!$permission) { exit_permission_denied(); } // Download file $group_name = $group->getUnixName(); $filename = $group_name . '-scm-latest.tar.gz'; if (file_exists($sys_scm_snapshots_path . '/' . $filename)) { Header('Content-disposition: filename="' . str_replace('"', '', $filename) . '"'); Header('Content-type: application/x-gzip'); $length = filesize($sys_scm_snapshots_path . '/' . $filename); Header('Content-length: ' . $length); readfile_chunked($sys_scm_snapshots_path . '/' . $filename); } else { session_redirect(util_make_url('/404.php')); }
/** * Download a file - hook into init function **/ function woocommerce_download_product() { if (isset($_GET['download_file']) && isset($_GET['order']) && isset($_GET['email'])) { global $wpdb; $download_file = (int) urldecode($_GET['download_file']); $order_key = urldecode($_GET['order']); $email = str_replace(' ', '+', urldecode($_GET['email'])); if (!is_email($email)) { wp_die(__('Invalid email address.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } $download_result = $wpdb->get_row($wpdb->prepare("\n\t\t\tSELECT order_id, downloads_remaining,user_id,download_count,access_expires\n\t\t\tFROM " . $wpdb->prefix . "woocommerce_downloadable_product_permissions\n\t\t\tWHERE user_email = %s\n\t\t\tAND order_key = %s\n\t\t\tAND product_id = %s\n\t\t;", $email, $order_key, $download_file)); if (!$download_result) { wp_die(__('Invalid download.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); exit; } $order_id = $download_result->order_id; $downloads_remaining = $download_result->downloads_remaining; $download_count = $download_result->download_count; $user_id = $download_result->user_id; $access_expires = $download_result->access_expires; if ($user_id && get_option('woocommerce_downloads_require_login') == 'yes') { if (!is_user_logged_in()) { wp_die(__('You must be logged in to download files.', 'woocommerce') . ' <a href="' . wp_login_url(get_permalink(woocommerce_get_page_id('myaccount'))) . '">' . __('Login →', 'woocommerce') . '</a>'); exit; } else { $current_user = wp_get_current_user(); if ($user_id != $current_user->ID) { wp_die(__('This is not your download link.', 'woocommerce')); exit; } } } if ($order_id) { $order = new WC_Order($order_id); if ($order->status != 'completed' && $order->status != 'processing' && $order->status != 'publish') { wp_die(__('Invalid order.', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); exit; } } if ($downloads_remaining == '0') { wp_die(__('Sorry, you have reached your download limit for this file', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); exit; } if ($access_expires > 0 && strtotime($access_expires) < current_time('timestamp')) { wp_die(__('Sorry, this download has expired', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); exit; } if ($downloads_remaining > 0) { $wpdb->update($wpdb->prefix . "woocommerce_downloadable_product_permissions", array('downloads_remaining' => $downloads_remaining - 1), array('user_email' => $email, 'order_key' => $order_key, 'product_id' => $download_file), array('%d'), array('%s', '%s', '%d')); } // Count the download $wpdb->update($wpdb->prefix . "woocommerce_downloadable_product_permissions", array('download_count' => $download_count + 1), array('user_email' => $email, 'order_key' => $order_key, 'product_id' => $download_file), array('%d'), array('%s', '%s', '%d')); // Get the downloads URL and try to replace the url with a path $file_path = apply_filters('woocommerce_file_download_path', get_post_meta($download_file, '_file_path', true), $download_file); if (!$file_path) { exit; } $file_download_method = apply_filters('woocommerce_file_download_method', get_option('woocommerce_file_download_method'), $download_file); if ($file_download_method == 'redirect') { header('Location: ' . $file_path); exit; } // Get URLS with https $site_url = site_url(); $network_url = network_admin_url(); if (is_ssl()) { $site_url = str_replace('https:', 'http:', $site_url); $network_url = str_replace('https:', 'http:', $network_url); } if (!is_multisite()) { $file_path = str_replace(trailingslashit($site_url), ABSPATH, $file_path); } else { $upload_dir = wp_upload_dir(); // Try to replace network url $file_path = str_replace(trailingslashit($network_url), ABSPATH, $file_path); // Now try to replace upload URL $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file_path); } // See if its local or remote if (strstr($file_path, 'http:') || strstr($file_path, 'https:') || strstr($file_path, 'ftp:')) { $remote_file = true; } else { $remote_file = false; $file_path = realpath($file_path); } // Download the file $file_extension = strtolower(substr(strrchr($file_path, "."), 1)); $ctype = "application/force-download"; foreach (get_allowed_mime_types() as $mime => $type) { $mimes = explode('|', $mime); if (in_array($file_extension, $mimes)) { $ctype = $type; break; } } if ($file_download_method == 'xsendfile') { if (getcwd()) { // Path fix - kudos to Jason Judge $file_path = trim(preg_replace('`^' . getcwd() . '`', '', $file_path), '/'); } header("Content-Disposition: attachment; filename=\"" . basename($file_path) . "\";"); if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { header("X-Sendfile: {$file_path}"); exit; } elseif (stristr(getenv('SERVER_SOFTWARE'), 'lighttpd')) { header("X-Lighttpd-Sendfile: {$file_path}"); exit; } elseif (stristr(getenv('SERVER_SOFTWARE'), 'nginx') || stristr(getenv('SERVER_SOFTWARE'), 'cherokee')) { header("X-Accel-Redirect: {$file_path}"); exit; } } /** * readfile_chunked * * Reads file in chunks so big downloads are possible without changing PHP.INI - http://codeigniter.com/wiki/Download_helper_for_large_files/ * * @access public * @param string file * @param boolean return bytes of file * @return void */ if (!function_exists('readfile_chunked')) { function readfile_chunked($file, $retbytes = TRUE) { $chunksize = 1 * (1024 * 1024); $buffer = ''; $cnt = 0; $handle = fopen($file, 'r'); if ($handle === FALSE) { return FALSE; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; ob_flush(); flush(); if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes and $status) { return $cnt; } return $status; } } @session_write_close(); if (function_exists('apache_setenv')) { @apache_setenv('no-gzip', 1); } @ini_set('zlib.output_compression', 'Off'); @set_time_limit(0); @set_magic_quotes_runtime(0); @ob_end_clean(); if (ob_get_level()) { @ob_end_clean(); } // Zip corruption fix header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Robots: none"); header("Content-Type: " . $ctype . ""); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=\"" . basename($file_path) . "\";"); header("Content-Transfer-Encoding: binary"); if ($size = @filesize($file_path)) { header("Content-Length: " . $size); } // Serve it if ($remote_file) { @readfile_chunked("{$file_path}") or header('Location: ' . $file_path); } else { @readfile_chunked("{$file_path}") or wp_die(__('File not found', 'woocommerce') . ' <a href="' . home_url() . '">' . __('Go to homepage →', 'woocommerce') . '</a>'); } exit; } }
header("Robots: none"); header("Content-Type: " . $ctype . ""); header("Content-Description: File Transfer"); header("Content-Transfer-Encoding: binary"); if (isset($header_filename) && !empty($header_filename)) { header("Content-Disposition: " . $header_filename . ";"); } else { if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { $iefilename = preg_replace('/\\./', '%2e', $filename, substr_count($filename, '.') - 1); header("Content-Disposition: attachment; filename=\"" . $iefilename . "\";"); } else { header("Content-Disposition: attachment; filename=\"" . $filename . "\";"); } } if (isset($filesize) && $filesize > 0) { @readfile_chunked($thefile, $filesize); } else { readfile($thefile); } exit; } elseif ($isURI && !ini_get('allow_url_fopen')) { // O dear, we cannot force the remote file without allow_url_fopen @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); wp_die(__('Forcing the download of externally hosted files is not supported by this server.', "wp-download_monitor"), __('Forcing the download of externally hosted files is not supported by this server.', "wp-download_monitor")); } // If we have not exited by now, the only thing left to do is die. // We cannot download something that is a local file system path on another system, and that's the only thing left it could be! @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); wp_die(__('Download path is invalid!', "wp-download_monitor"), __('Download path is invalid!', "wp-download_monitor")); } if (!strstr($thefile, 'http://') && !strstr($thefile, 'https://') && !strstr($thefile, 'ftp://')) {
readfile(GetSystemOption('temp_dir') . $backupname . ".zip "); unlink(GetSystemOption('temp_dir') . $backupname . ".zip "); exit; } else { # Now we send the output (POSIX)... $file = GetSystemOption('temp_dir') . $backupname . ".zip"; header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: private', false); header('Content-Description: File Transfer'); header('Content-Transfer-Encoding: binary'); header('Content-Type: application/force-download'); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename=' . $backupname . '.zip'); readfile_chunked($file); unlink(GetSystemOption('temp_dir') . $backupname . ".zip "); function readfile_chunked($filename) { $chunksize = 1 * (1024 * 1024); $buffer = ''; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); print $buffer; } return fclose($handle); }
public function testreadfile_chunked() { //execute the method and test if it returns expected values $expected = file_get_contents('config.php'); //retbytes parameter false ob_start(); $actual = readfile_chunked('config.php', false); $renderedContent = ob_get_contents(); ob_end_clean(); $this->assertTrue($actual); $this->assertSame($expected, $renderedContent); //retbytes parameter true/default ob_start(); $actual = readfile_chunked('config.php'); $renderedContent = ob_get_contents(); ob_end_clean(); $this->assertEquals($actual, strlen($renderedContent)); $this->assertSame($expected, $renderedContent); }
/** * Download a paper */ function download($requiredFile) { $type = "application/octet-stream"; $file = $this->filePath($requiredFile->id_phase, $requiredFile->file_code, $requiredFile->file_extension); header("Content-disposition: attachment; filename=" . $requiredFile->file_code . $this->id . "." . $requiredFile->file_extension); header("Content-Type: application/force-download"); header("Content-Transfer-Encoding: {$type}\n"); header("Content-Length: " . filesize($file)); header("Pragma: no-cache"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public"); header("Expires: 0"); readfile_chunked($file); }
function nzshpcrt_download_file() { global $wpdb, $user_level, $wp_rewrite; get_currentuserinfo(); function readfile_chunked($filename, $retbytes = true) { $chunksize = 1 * (1024 * 1024); // how many bytes per chunk $buffer = ''; $cnt = 0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; ob_flush(); flush(); if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes && $status) { return $cnt; // return num. bytes delivered like readfile() does. } return $status; } if (isset($_GET['downloadid'])) { // strip out anything that isnt 'a' to 'z' or '0' to '9' //ini_set('max_execution_time',10800); $downloadid = preg_replace("/[^a-z0-9]+/i", '', strtolower($_GET['downloadid'])); $download_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `uniqueid` = '" . $downloadid . "' AND `downloads` > '0' AND `active`='1' LIMIT 1", ARRAY_A); if ($download_data == null && is_numeric($downloadid)) { $download_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `id` = '" . $downloadid . "' AND `downloads` > '0' AND `active`='1' AND `uniqueid` IS NULL LIMIT 1", ARRAY_A); } if (get_option('wpsc_ip_lock_downloads') == 1 && $_SERVER['REMOTE_ADDR'] != null) { $ip_number = $_SERVER['REMOTE_ADDR']; if ($download_data['ip_number'] == '') { // if the IP number is not set, set it $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `ip_number` = '{$ip_number}' WHERE `id` = '{$download_data['id']}' LIMIT 1"); } else { if ($ip_number != $download_data['ip_number']) { // if the IP number is set but does not match, fail here. // return false; exit(WPSC_DOWNLOAD_INVALID); } } } //exit("<pre>".print_r($download_data,true)."</pre>"); if ($download_data != null) { if ($download_data['product_id'] > 0) { $product_file_id = $wpdb->get_var("SELECT `file` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $download_data['product_id'] . "' LIMIT 1"); $file_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id`='" . $product_file_id . "' LIMIT 1", ARRAY_A); } else { $old_file_data = $wpdb->get_row("SELECT `product_id` FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id`='" . $download_data['fileid'] . "' LIMIT 1", ARRAY_A); $product_file_id = $wpdb->get_var("SELECT `file` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $old_file_data['product_id'] . "' LIMIT 1"); $file_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id`='" . $product_file_id . "' LIMIT 1", ARRAY_A); } if ((int) $download_data['downloads'] >= 1) { $download_count = (int) $download_data['downloads'] - 1; } else { $download_count = 0; } $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `downloads` = '{$download_count}' WHERE `id` = '{$download_data['id']}' LIMIT 1"); $cart_contents = $wpdb->get_results('SELECT `' . WPSC_TABLE_CART_CONTENTS . '`.*,`' . WPSC_TABLE_PRODUCT_LIST . '`.`file` FROM `' . WPSC_TABLE_CART_CONTENTS . '` LEFT JOIN `' . WPSC_TABLE_PRODUCT_LIST . '` ON `' . WPSC_TABLE_CART_CONTENTS . '`.`prodid`= `' . WPSC_TABLE_PRODUCT_LIST . '`.`id` WHERE `purchaseid` =' . $download_data['purchid'], ARRAY_A); $dl = 0; foreach ($cart_contents as $cart_content) { if ($cart_content['file'] == 1) { $dl++; } } if (count($cart_contents) == $dl) { // exit('called'); $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '4' WHERE `id` = '" . $download_data['purchid'] . "' LIMIT 1"); } //exit('<pre>'.print_r($cart_contents,true).'</pre>'); if (is_file(WPSC_FILE_DIR . $file_data['idhash'])) { header('Content-Type: ' . $file_data['mimetype']); header('Content-Length: ' . filesize(WPSC_FILE_DIR . $file_data['idhash'])); header('Content-Transfer-Encoding: binary'); header('Content-Disposition: attachment; filename="' . stripslashes($file_data['filename']) . '"'); if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != '') { /* There is a bug in how IE handles downloads from servers using HTTPS, this is part of the fix, you may also need: session_cache_limiter('public'); session_cache_expire(30); At the start of your index.php file or before the session is started */ header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); } else { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); } $filename = WPSC_FILE_DIR . $file_data['idhash']; // destroy the session to allow the file to be downloaded on some buggy browsers and webservers session_destroy(); readfile_chunked($filename); exit; } } else { exit(WPSC_DOWNLOAD_INVALID); } } else { if ($_GET['admin_preview'] == "true" && is_numeric($_GET['product_id']) && current_user_can('edit_plugins')) { $product_id = $_GET['product_id']; $product_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A); if (is_numeric($product_data[0]['file']) && $product_data[0]['file'] > 0) { $file_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id`='" . $product_data[0]['file'] . "' LIMIT 1", ARRAY_A); $file_data = $file_data[0]; if (is_file(WPSC_FILE_DIR . $file_data['idhash'])) { header('Content-Type: ' . $file_data['mimetype']); header('Content-Length: ' . filesize(WPSC_FILE_DIR . $file_data['idhash'])); header('Content-Transfer-Encoding: binary'); if ($_GET['preview_track'] != 'true') { header('Content-Disposition: attachment; filename="' . $file_data['filename'] . '"'); } else { header('Content-Disposition: inline; filename="' . $file_data['filename'] . '"'); } if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != '') { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); } else { header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); } $filename = WPSC_FILE_DIR . $file_data['idhash']; session_destroy(); readfile_chunked($filename); exit; } } } } }
/** * Send file to download to the user * @global stdClass $CFG * @global stdClass $COURSE * @global stdClass $SESSION * @param string $path The path of the file * @param string $filename The file name * @param string $extension The file extension */ function send_file($path, $filename, $extension) { global $CFG, $COURSE, $SESSION; //print $path . " " . $filename . " " . $extension;exit(); $filesize = filesize($path); //IE compatibiltiy HACK! if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } //try to disable automatic sid rewrite in cookieless mode @ini_set("session.use_trans_sid", "false"); @header('Content-Disposition: inline; filename="' . $filename . '"'); $lifetime = $lifetime = 86400; @header('Cache-Control: max-age=' . $lifetime); @header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $lifetime) . ' GMT'); @header('Pragma: '); // Just send it out raw @header('Content-Length: ' . $filesize); @header('Content-Type: ' . $mimetype); while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite readfile_chunked($path); die; //no more chars to output!!! }
public function viewAsImage($max_size = 0) { $max_size = intval($max_size); if (!($dimensions = $this->getImageDimensions($max_size))) { log_message("file::viewAsImage({$this->id}) can not find file1 '{$filepath}'", LOG_MESSAGE_MISSING_FILES); return; } $filepath = $dimensions['filepath']; $new_width = $dimensions['new_width']; $new_height = $dimensions['new_height']; $width = $dimensions['width']; $height = $dimensions['height']; $filesize = filesize($filepath); /** * just provide the original file */ if (!$dimensions['downscale']) { header('Content-Length: ' . $filesize); header('Content-Type: ' . $this->mimetype); header("Content-Disposition: inline; filename={$this->org_filename}"); header("Cache-Control: public"); header('Last-Modified: ' . gmdate("D, j M Y G:i:s T", strToClientTime($this->modified))); if ($filesize > 1000000) { readfile_chunked($filepath); } else { readfile($filepath); } return; } /** * rescale with gd */ if (!function_exists('imagecreatetruecolor')) { log_message("file::viewAsImage({$this->id}) gd not installed", LOG_MESSAGE_MISSING_FILES); return; } ### check if cached file exists $md5 = md5(http_build_query(array('filepath' => $filepath, 'new_width' => $new_width, 'new_height' => $new_height))); $cached_filepath = confGet('DIR_IMAGE_CACHE') . "/" . $md5 . ".jpg"; if (file_exists($cached_filepath)) { header('Content-Length: ' . filesize($cached_filepath)); header('Content-Type: ' . $this->mimetype); header("Content-Disposition: inline; filename= {$this->org_filename}"); header("Cache-Control: public"); header('Last-Modified: ' . gmdate("D, j M Y G:i:s T", strToClientTime($this->modified))); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60 * 60 * 24 * 365) . " GMT"); readfile($cached_filepath); return; } $image_new = NULL; ### downscale if ($this->mimetype == 'image/jpeg' || $this->mimetype == 'image/jpg' || $this->mimetype == 'image/pjpeg') { $image = imagecreatefromjpeg($filepath); } else { if ($this->mimetype == 'image/png' || $this->mimetype == 'image/x-png') { $image = imagecreatefrompng($filepath); } else { if ($this->mimetype == 'image/gif') { $image = imagecreatefromgif($filepath); } else { return NULL; } } } ### Downscale image and stream content header('Content-Type: ' . 'image/jpeg'); header("Cache-Control: public"); ### Tell browser to cache forever, because the file will never change header("Last-Modified: " . gmdate('r', strToClientTime($this->modified))); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60 * 60 * 24 * 365) . " GMT"); $image_new = imagecreatetruecolor($new_width, $new_height) or die("Cannot Initialize new GD image stream"); if (imagecopyresampled($image_new, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height)) { imagejpeg($image_new); } else { imagejpeg($image); } ### write cached file if ($image_new) { imagejpeg($image_new, $cached_filepath); imagedestroy($image_new); } }
if ($mime_file == "inode/x-empty" || $mime_file == "") { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($navigation_dir) . '"'); } else { header('Content-Type: ' . $mime_file); } header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Accept-Ranges: bytes'); header('Pragma: public'); header('Content-Length: ' . filesize($navigation_dir)); ob_clean(); flush(); if ($options['general']['read_chunks'] == true) { readfile_chunked($navigation_dir); } else { readfile($navigation_dir); } } else { set_404_error(); } exit; } else { if (!file_exists($navigation_dir)) { set_404_error(); exit; } } // Declare vars used beyond this point. $file_list = array();
protected function deliver($bundleidentifier, $type) { $plist = @array_shift(glob($this->appDirectory.$bundleidentifier . '/*.plist')); $ipa = @array_shift(glob($this->appDirectory.$bundleidentifier . '/*.ipa')); $provisioningProfile = @array_shift(glob($this->appDirectory.$bundleidentifier . '/*.mobileprovision')); $note = @array_shift(glob($this->appDirectory.$bundleidentifier . '/*.html')); $image = @array_shift(glob($this->appDirectory.$bundleidentifier . '/*.png')); // did we get any user data? $udid = isset($_GET['udid']) ? $_GET['udid'] : null; $appversion = isset($_GET['version']) ? $_GET['version'] : ""; $osversion = isset($_GET['ios']) ? $_GET['ios'] : ""; $platform = isset($_GET['platform']) ? $_GET['platform'] : ""; if ($udid) { $thisdevice = $udid.";;".$platform.";;".$osversion.";;".$appversion.";;".date("m/d/Y H:i:s"); $content = ""; $filename = $this->appDirectory."stats/".$bundleidentifier; $content = @file_get_contents($filename); $lines = explode("\n", $content); $content = ""; $found = false; foreach ($lines as $i => $line) : if ($line == "") continue; $device = explode( ";;", $line); $newline = $line; if (count($device) > 0) { // is this the same device? if ($device[0] == $udid) { $newline = $thisdevice; $found = true; } } $content .= $newline."\n"; endforeach; if (!$found) { $content .= $thisdevice; } // write back the updated stats @file_put_contents($filename, $content); } // notes file is optional, other files are required if (!$plist || !$ipa) { $this->json = array(self::RETURN_RESULT => -1); return $this->sendJSONAndExit(); } if (!$type) { // check for available updates for the given bundleidentifier // and return a JSON string with the result values // parse the plist file $plistDocument = new DOMDocument(); $plistDocument->load($plist); $parsed_plist = parsePlist($plistDocument); // get the bundle_version which we treat as build number $latestversion = $parsed_plist['items'][0]['metadata']['bundle-version']; // add the latest release notes if available if ($note && file_exists($this->appDirectory . $note)) { $this->json[self::RETURN_NOTES] = nl2br_skip_html(file_get_contents($this->appDirectory . $note)); } $this->json[self::RETURN_TITLE] = $parsed_plist['items'][0]['metadata']['title']; if (array_key_exists('subtitle', $parsed_plist['items'][0]['metadata'])) $this->json[self::RETURN_SUBTITLE] = $parsed_plist['items'][0]['metadata']['subtitle']; $this->json[self::RETURN_RESULT] = $latestversion; return $this->sendJSONAndExit(); } else if ($type == self::TYPE_PROFILE) { // send latest profile for the given bundleidentifier header('Content-Disposition: attachment; filename=' . urlencode(basename($provisioningProfile))); header('Content-Type: application/octet-stream;'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.filesize($provisioningProfile).";\n"); readfile($provisioningProfile); } else if ($type == self::TYPE_APP) { $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http'; $port = $_SERVER["SERVER_PORT"]=='80'?'':':'.$_SERVER["SERVER_PORT"]; // send XML with url to app binary file $ipa_url = dirname($protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']) . '/index.php?type=' . self::TYPE_IPA . '&bundleidentifier=' . $bundleidentifier; $plist_content = file_get_contents($plist); $plist_content = str_replace('__URL__', $ipa_url, $plist_content); if ($image) { $image_url = dirname($protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']) . '/' . $bundleidentifier . '/' . basename($image); $imagedict = "<dict><key>kind</key><string>display-image</string><key>needs-shine</key><false/><key>url</key><string>".$image_url."</string></dict></array>"; $insertpos = strpos($plist_content, '</array>'); $plist_content = substr_replace($plist_content, $imagedict, $insertpos, 8); } header('content-type: application/xml'); echo $plist_content; } else if ($type == self::TYPE_IPA) { // send latest profile for the given bundleidentifier header('Content-Disposition: attachment; filename=' . urlencode(basename($ipa))); header('Content-Type: application/octet-stream;'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.filesize($ipa).";\n"); readfile_chunked($ipa); } exit(); }
<?php /* * This file is called by the offline Moodle SERVER and sends the existing * incremental or Full backup if no incremental is available to the client. * */ require '../config.php'; require_once "{$CFG->dirroot}/backup/backup_sch_incremental.php"; require_once "{$CFG->dirroot}/backup/incremental_backuplib.php"; require_once "{$CFG->dirroot}/backup/backuplib.php"; require_once "{$CFG->dirroot}/backup/lib.php"; require_once "{$CFG->dirroot}/lib/filelib.php"; $currenthash = required_param('hash'); // hash $action = required_param('action'); // what to do? $file = get_incremental($currenthash); if ($file) { if ($action == 'curldownload') { readfile_chunked($file->path . $file->name); } elseif ($action == 'download') { send_file($file->path, $file->name, 864, 0, true, true); } elseif ($action == 'check') { echo $file->name; } else { echo 'no action specified'; } } else { echo 'ERROR!!! No file returned'; }
/** * To be implemented by child classes * @param boolean $feedback * @param boolean $publish Whether to output directly, or send as a file * @return string */ function print_grades($feedback = false) { global $CFG; require_once $CFG->libdir . '/filelib.php'; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); /// Calculate file name $downloadfilename = clean_filename("{$this->course->shortname} {$strgrades}.xml"); make_upload_directory('temp/gradeexport', false); $tempfilename = $CFG->dataroot . '/temp/gradeexport/' . md5(sesskey() . microtime() . $downloadfilename); if (!($handle = fopen($tempfilename, 'w+b'))) { error("Could not create a temporary file into which to dump the XML data."); return false; } /// time stamp to ensure uniqueness of batch export fwrite($handle, '<results batch="xml_export_' . time() . '">' . "\n"); $export_buffer = array(); $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { $user = $userdata->user; if (empty($user->idnumber)) { //id number must exist continue; } // studentgrades[] index should match with corresponding $index foreach ($userdata->grades as $itemid => $grade) { $grade_item = $this->grade_items[$itemid]; $grade->grade_item =& $grade_item; $gradestr = $this->format_grade($grade); // no formating for now // MDL-11669, skip exported grades or bad grades (if setting says so) if ($export_tracking) { $status = $geub->track($grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { continue; } } fwrite($handle, "\t<result>\n"); if ($export_tracking) { fwrite($handle, "\t\t<state>{$status}</state>\n"); } // only need id number fwrite($handle, "\t\t<assignment>{$grade_item->idnumber}</assignment>\n"); // this column should be customizable to use either student id, idnumber, uesrname or email. fwrite($handle, "\t\t<student>{$user->idnumber}</student>\n"); fwrite($handle, "\t\t<score>{$gradestr}</score>\n"); if ($this->export_feedback) { $feedbackstr = $this->format_feedback($userdata->feedbacks[$itemid]); fwrite($handle, "\t\t<feedback>{$feedbackstr}</feedback>\n"); } fwrite($handle, "\t</result>\n"); } } fwrite($handle, "</results>"); fclose($handle); $gui->close(); $geub->close(); if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 @header('Cache-Control: max-age=10'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: '); } else { //normal http - prevent caching at all cost @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: no-cache'); } header("Content-type: text/xml; charset=UTF-8"); header("Content-Disposition: attachment; filename=\"{$downloadfilename}\""); readfile_chunked($tempfilename); @unlink($tempfilename); exit; }
$new_height = $word2_new_height; } $new_width = $word1_new_width + $word_seperator_pixel + $word2_new_width; $cropped_img = imagecreatetruecolor($new_width + 2 * $crop_spacer_pixel, $new_height); for ($x = 0; $x < $new_width + 2 * $crop_spacer_pixel; $x++) { for ($y = 0; $y < $new_height; $y++) { imagesetpixel($cropped_img, $x, $y, 16777215); } } imagecopyresampled($cropped_img, $temp, $crop_spacer_pixel, 0, $first_word_start, $word1_crop_top, $word1_new_width, $word1_new_height, $word1_new_width, $word1_new_height); imagecopyresampled($cropped_img, $temp, $word1_new_width + $word_seperator_pixel + $crop_spacer_pixel, 0, $second_word_start, $word2_crop_top, $word2_new_width, $word2_new_height, $word2_new_width, $word2_new_height); imagejpeg($cropped_img, 'cropped.jpg'); # output to ocr ************************************************************** # **************************************************************************** $tesseract_output = shell_exec($tesseract_commandline); $word_tess_text = str_replace("\n", "", str_replace("\r", "", readfile_chunked('tessoutput.txt'))); if (strlen($word_tess_text) < 2) { $word_tess_text = $shit; } if ($debug_mode) { echo "<img src=" . $input_image . "><br><img src=contrast.bmp><br><img src=debug.jpg><br>"; imagedestroy($debug); } else { @imagedestroy($temp); @imagedestroy($img); @unlink('resized.bmp'); @unlink('cropped1.jpg'); @unlink('cropped2.jpg'); @unlink('contrast.bmp'); @unlink('tessoutput.txt'); @unlink('debug.jpg');
function WA_DFP_DownloadFile($statusName, $folderPath, $fileName, $newFileName, $updateDB, $dbName, $connectionName, $tableName, $keyColumn, $recordID, $countColumn) { global $WA_DFP_DownloadStatus; if ($folderPath == "") { $folderPath = "./"; } if (strpos($fileName, "/") !== false) { $folderPath .= substr($fileName, 0, strrpos($fileName, "/") + 1); $fileName = substr($fileName, strrpos($fileName, "/") + 1); } $separator = WA_DFP_GetFileSeparator(); $folderPath = rootRelativeToFullFileURL($folderPath); if ($folderPath !== FALSE) { $path = $folderPath . $separator . $fileName; } else { $path = $fileName; } $path_parts = pathinfo($fileName); $path_parts = pathinfo($fileName); $WA_DFP_DownloadStatus[$statusName]["fileNotPresent"] = true; $WA_DFP_DownloadStatus[$statusName]["fileName"] = preg_replace('/\\.[^.]*$/', '', $fileName); $WA_DFP_DownloadStatus[$statusName]["fileFullName"] = $fileName; $WA_DFP_DownloadStatus[$statusName]["fileExtension"] = isset($path_parts['extension']) ? $path_parts['extension'] : ""; $WA_DFP_DownloadStatus[$statusName]["serverDirectory"] = realpath($folderPath); $WA_DFP_DownloadStatus[$statusName]["serverFilePath"] = $WA_DFP_DownloadStatus[$statusName]["serverDirectory"] . $separator . $WA_DFP_DownloadStatus[$statusName]["fileFullName"]; if (file_exists($path)) { if ($updateDB) { $query_cmd = "UPDATE " . $tableName . " SET " . $countColumn . "=" . $countColumn . "+1 WHERE " . $keyColumn . "=" . $recordID . ";"; mysql_select_db($dbName, $connectionName); $cmd = mysql_query($query_cmd, $connectionName) or die(mysql_error()); } $fileNameDefault = "[FileName]"; if ($newFileName != $fileNameDefault) { if ($path_parts["extension"] != "" && strpos($newFileName, ".") === FALSE) { $fileName = $fileName . "." . $path_parts["extension"]; } $fileName = preg_replace('/\\[FileName\\]/', preg_replace('/\\.[^.]*$/', '', $fileName), $newFileName); } else { $fileName = $fileName; } if (strpos($fileName, ".") === false && $WA_DFP_DownloadStatus[$statusName]["fileExtension"] != "") { $fileName .= "." . $WA_DFP_DownloadStatus[$statusName]["fileExtension"]; } $WA_DFP_DownloadStatus[$statusName]["statusCode"] = 1; header('Cache-Control:'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header("Content-length: " . filesize($path)); readfile_chunked("{$path}"); die; } else { $WA_DFP_DownloadStatus[$statusName]["statusCode"] = 0; $WA_DFP_DownloadStatus[$statusName]["errorMessage"] = "File: '" . $path . "' not found"; } }
function down_file($sha1, $key, $os, $arch, $id, $check = null) { $conf = configurations(); $con = new Mongo(); $db = $con->{$conf}['base']->{$conf}['project']; $file = $db->findOne(array('_id' => new MongoId($id))); if ($check) { return $file; } if ($file['files'][$key]['files'][$os][$arch]['sha1'] == $sha1 && is_file($file['files'][$key]['files'][$os][$arch]['path'])) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $file['files'][$key]['files'][$os][$arch]['filename']); header('Content-length: ' . $file['files'][$key]['files'][$os][$arch]['length']); header('Content-Transfer-Encoding: binary'); readfile_chunked($file['files'][$key]['files'][$os][$arch]['path']); } else { return user_page_display($_SESSION['db_data']['user'], $_SESSION['db_data']['lvl'], 'project', 'nofile'); } }
/** * See if there is a video rendering job that needs to be done * */ function GetVideoJob() { $ret = false; $videoDir = './video'; if (is_dir($videoDir)) { // lock the directory $lockFile = fopen($videoDir . '/lock.dat', 'a+b', false); if ($lockFile) { $ok = false; $count = 0; while (!$ok && $count < 500) { $count++; if (flock($lockFile, LOCK_EX)) { $ok = true; } else { usleep(10000); } } // look for the first zip file $dir = opendir($videoDir); if ($dir) { $testFile = null; while (!$testFile && ($file = readdir($dir))) { $path = $videoDir . "/{$file}"; if (is_file($path) && stripos($file, '.zip')) { $testFile = $path; } } if ($testFile) { header('Content-Type: application/zip'); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); readfile_chunked($testFile); $ret = true; // delete the test file unlink($testFile); } closedir($dir); } fclose($lockFile); } } return $ret; }
// , PATH_ASC_ROOT if (!modApiFunc("Shell", "isFileFromDirectoryOrSubdirectories", $application->getAppINI('PATH_ASC_ROOT'), $full_filename) || basename($file) == 'config.php') { exit(0); } $start = 0; $filesize = filesize($full_filename); if (isset($_SERVER['HTTP_RANGE'])) { // Support for partial transfers enabled and browser requested a partial transfer header("HTTP/1.1 206 Partial content\n"); $start = preg_replace(array("/( *|)bytes( *|)=( *|)/", "/( *|)\\-.*\$/"), array("", ""), $_SERVER['HTTP_RANGE']); if ($filesize < $start) { header("HTTP/1.1 411 Length Required\n"); echo "Trying to download past the end of the file. You have probably requested the wrong file. Please try again."; } $transfer_size = $filesize - $start; header("Accept-Ranges: bytes"); header("Content-Range: bytes " . $transfer_size . "-" . ($filesize - 1) . "/" . $filesize); header("Content-Length:" . $transfer_size . "\n"); } else { header("HTTP/1.1 200 OK\n"); header("Content-Length: " . filesize($full_filename)); } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=\"" . $local_filename . "\""); header("Content-Transfer-Encoding: binary"); readfile_chunked($full_filename, $start);
function Download($FileName) { global $ExploreDir, $CharsetOnFS; $FileName = cyr_convert($ExploreDir."/".$FileName,"u",$CharsetOnFS); $PathInfo = pathinfo($FileName); $Ext = isset($PathInfo["extension"]) ? $PathInfo["extension"] : ""; $BaseName = $PathInfo["basename"]; if($FileName == $ExploreDir."/" || !file_exists($FileName)) die(); $mimetype = mime_content_type($FileName); $pathinfo = pathinfo($FileName); $mimetype = isset($pathinfo["extension"]) && strtolower($pathinfo["extension"]) == "txt" ? "text/plain" : $mimetype; list($mimegen) = explode("/",$mimetype); header('Content-type: '.$mimetype); if($mimegen != "text" && $mimegen != "image") header('Content-Disposition: attachment; filename="'.cyr_convert($BaseName,$CharsetOnFS,"u").'"'); readfile_chunked($FileName); }
} $status = fclose($handle); if ($retbytes && $status) { return $cnt; // return num. bytes delivered like readfile() does. } return $status; } if (isset($_GET['path']) && startswith($_GET['path'], get_archive_link())) { // Prevent download to stop after PHP timeout set_time_limit(0); $filepath = $_GET['path']; $file_name = basename($filepath); // Prevent from corrupting files due to indesirable prints ob_end_clean(); // Getting file mimetype $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension $mime_type = finfo_file($finfo, $filepath); finfo_close($finfo); // Sending HTTP headers header("Content-Type: {$mime_type}"); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . $file_name . "\""); // Sending binary data readfile_chunked($filepath); delete_archive(); // generated file after download will be erased die(''); // Stopping flow }
header("Content-Range: bytes {$start}-{$end}/{$filesize}"); header("Content-Length: {$length}"); } elseif ($filesize) { header("Content-Length: {$filesize}"); } header("Expires: Mon, 12 Dec 2001 08:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); if ($_SERVER['HTTPS'] == "on") { header("Pragma: public"); header("Cache-Control: private"); } else { header("Pragma: no-cache"); header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 } header("Cache-Control: post-check=0, pre-check=0", false); header("Content-Type: {$content_type}"); header("Content-Disposition: {$content_disposition}; filename=\"{$file_name}\""); Metrics::increment('core.file_download'); if ($type != 5) { @readfile_chunked($path_file, $start, $end); if (in_array($type, array(0, 6)) && !$start) { TrackAccess($file_id, 'dokument'); } } else { echo $the_data; } //remove temporary file after zipping if (Request::int('zip') || $type == 4) { @unlink($path_file); }
/** * Handles the sending of file data to the user's browser, including support for * byteranges etc. * @param string $path Path of file on disk (including real filename), or actual content of file as string * @param string $filename Filename to send * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours) * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename */ function send_file($path, $filename, $lifetime = 'default', $filter = 0, $pathisstring = false, $forcedownload = false, $mimetype = '') { global $CFG, $COURSE, $SESSION; // MDL-11789, apply $CFG->filelifetime here if ($lifetime === 'default') { if (!empty($CFG->filelifetime)) { $lifetime = $CFG->filelifetime; } else { $lifetime = 86400; } } // Use given MIME type if specified, otherwise guess it using mimeinfo. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O // only Firefox saves all files locally before opening when content-disposition: attachment stated $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' : ($mimetype ? $mimetype : mimeinfo('type', $filename)); // If the file is a Flash file and that the user flash player is outdated return a flash upgrader MDL-20841 if (!empty($CFG->excludeoldflashclients) && $mimetype == 'application/x-shockwave-flash' && !empty($SESSION->flashversion)) { $userplayerversion = explode('.', $SESSION->flashversion); $requiredplayerversion = explode('.', $CFG->excludeoldflashclients); if ($userplayerversion[0] < $requiredplayerversion[0] || $userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] < $requiredplayerversion[1] || $userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] == $requiredplayerversion[1] && $userplayerversion[2] < $requiredplayerversion[2]) { $path = $CFG->dirroot . "/lib/flashdetect/flashupgrade.swf"; // Alternate content asking user to upgrade Flash $filename = "flashupgrade.swf"; $lifetime = 0; // Do not cache } } $lastmodified = $pathisstring ? time() : filemtime($path); $filesize = $pathisstring ? strlen($path) : filesize($path); /* - MDL-13949 //Adobe Acrobat Reader XSS prevention if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') { //please note that it prevents opening of pdfs in browser when http referer disabled //or file linked from another site; browser caching of pdfs is now disabled too if (!empty($_SERVER['HTTP_RANGE'])) { //already byteserving $lifetime = 1; // >0 needed for byteserving } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) { $mimetype = 'application/x-forcedownload'; $forcedownload = true; $lifetime = 0; } else { $lifetime = 1; // >0 needed for byteserving } } */ //IE compatibiltiy HACK! if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } //try to disable automatic sid rewrite in cookieless mode @ini_set("session.use_trans_sid", "false"); //do not put '@' before the next header to detect incorrect moodle configurations, //error should be better than "weird" empty lines for admins/users //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers? header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastmodified) . ' GMT'); // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup if (check_browser_version('MSIE')) { $filename = rawurlencode($filename); } if ($forcedownload) { @header('Content-Disposition: attachment; filename="' . $filename . '"'); } else { @header('Content-Disposition: inline; filename="' . $filename . '"'); } if ($lifetime > 0) { @header('Cache-Control: max-age=' . $lifetime); @header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $lifetime) . ' GMT'); @header('Pragma: '); if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') { @header('Accept-Ranges: bytes'); if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'], 'bytes=') !== FALSE) { // byteserving stuff - for acrobat reader and download accelerators // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php $ranges = false; if (preg_match_all('/(\\d*)-(\\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) { foreach ($ranges as $key => $value) { if ($ranges[$key][1] == '') { //suffix case $ranges[$key][1] = $filesize - $ranges[$key][2]; $ranges[$key][2] = $filesize - 1; } else { if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) { //fix range length $ranges[$key][2] = $filesize - 1; } } if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) { //invalid byte-range ==> ignore header $ranges = false; break; } //prepare multipart header $ranges[$key][0] = "\r\n--" . BYTESERVING_BOUNDARY . "\r\nContent-Type: {$mimetype}\r\n"; $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/{$filesize}\r\n\r\n"; } } else { $ranges = false; } if ($ranges) { byteserving_send_file($path, $mimetype, $ranges); } } } else { /// Do not byteserve (disabled, strings, text and html files). @header('Accept-Ranges: none'); } } else { // Do not cache files in proxies and browsers if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 @header('Cache-Control: max-age=10'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: '); } else { //normal http - prevent caching at all cost @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: no-cache'); } @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled } if (empty($filter)) { if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession' . $CFG->sessioncookie])) { //cookieless mode - rewrite links @header('Content-Type: text/html'); $path = $pathisstring ? $path : implode('', file($path)); $path = sid_ob_rewrite($path); $filesize = strlen($path); $pathisstring = true; } else { if ($mimetype == 'text/plain') { @header('Content-Type: Text/plain; charset=utf-8'); //add encoding } else { @header('Content-Type: ' . $mimetype); } } @header('Content-Length: ' . $filesize); while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite if ($pathisstring) { echo $path; } else { readfile_chunked($path); } } else { // Try to put the file through filters if ($mimetype == 'text/html') { $options = new object(); $options->noclean = true; $options->nocache = true; // temporary workaround for MDL-5136 $text = $pathisstring ? $path : implode('', file($path)); $text = file_modify_html_header($text); $output = format_text($text, FORMAT_HTML, $options, $COURSE->id); if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession' . $CFG->sessioncookie])) { //cookieless mode - rewrite links $output = sid_ob_rewrite($output); } @header('Content-Length: ' . strlen($output)); @header('Content-Type: text/html'); while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite echo $output; // only filter text if filter all files is selected } else { if ($mimetype == 'text/plain' and $filter == 1) { $options = new object(); $options->newlines = false; $options->noclean = true; $text = htmlentities($pathisstring ? $path : implode('', file($path))); $output = '<pre>' . format_text($text, FORMAT_MOODLE, $options, $COURSE->id) . '</pre>'; if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession' . $CFG->sessioncookie])) { //cookieless mode - rewrite links $output = sid_ob_rewrite($output); } @header('Content-Length: ' . strlen($output)); @header('Content-Type: text/html; charset=utf-8'); //add encoding while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite echo $output; } else { // Just send it out raw @header('Content-Length: ' . $filesize); @header('Content-Type: ' . $mimetype); while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite if ($pathisstring) { echo $path; } else { readfile_chunked($path); } } } } die; //no more chars to output!!! }
/** * See if there is a software update * */ function GetUpdate() { global $location; $ret = false; // see if the client sent a version number if ($_GET['ver']) { $fileBase = ''; if (isset($_GET['software']) && strlen($_GET['software'])) { $fileBase = trim($_GET['software']); } $updateDir = './work/update'; if (is_dir("{$updateDir}/{$location}")) { $updateDir = "{$updateDir}/{$location}"; } // see if we have any software updates if (is_file("{$updateDir}/{$fileBase}update.ini") && is_file("{$updateDir}/{$fileBase}update.zip")) { $update = parse_ini_file("{$updateDir}/{$fileBase}update.ini"); // Check for inequality allows both upgrade and quick downgrade if ($update['ver'] && intval($update['ver']) !== intval($_GET['ver'])) { header('Content-Type: application/zip'); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); readfile_chunked("{$updateDir}/{$fileBase}update.zip"); $ret = true; } } } return $ret; }
/** * Serves a file from dataroot. * * This function checks that the file is inside dataroot, but does not perform * any other checks. Authors using this function should make sure that their * scripts perform appropriate authentication. * * As an example: If the file is an artefact, you could ask for an artefact and * view ID, and check that the artefact is in the view and that the user can * view the view. * * @param string $path The file to send. Must include the dataroot path. * @param string $filename The name of the file as the browser should use to * serve it. * @param string $mimetype Mime type to be sent in header * @param array $options Any options to use when serving the file. Currently * lifetime = 0 for no cache * forcedownload - force application rather than inline * overridecontenttype - send this instead of the mimetype * there are none. */ function serve_file($path, $filename, $mimetype, $options = array()) { $dataroot = realpath(get_config('dataroot')); $path = realpath($path); $options = array_merge(array('lifetime' => 86400), $options); if (!get_config('insecuredataroot') && substr($path, 0, strlen($dataroot)) != $dataroot) { throw new AccessDeniedException(); } if (!file_exists($path)) { throw new NotFoundException(); } session_write_close(); // unlock session during fileserving $lastmodified = filemtime($path); $filesize = filesize($path); if ($mimetype == 'text/html' || $mimetype == 'text/xml' || $mimetype == 'application/xml' || $mimetype == 'application/xhtml+xml' || $mimetype == 'image/svg+xml') { if (isset($options['downloadurl']) && $filesize < 1024 * 1024) { display_cleaned_html(file_get_contents($path), $filename, $options); exit; } $options['forcedownload'] = true; $mimetype = 'application/octet-stream'; } if (!$mimetype) { $mimetype = 'application/forcedownload'; } if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // Try to disable automatic sid rewrite in cookieless mode @ini_set('session.use_trans_sid', 'false'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastmodified) . ' GMT'); // @todo possibly need addslashes on the filename, but I'm unsure on exactly // how the browsers will handle it. if ($mimetype == 'application/forcedownload' || isset($options['forcedownload'])) { header('Content-Disposition: attachment; filename="' . $filename . '"'); } else { header('Content-Disposition: inline; filename="' . $filename . '"'); } header('X-Content-Type-Options: nosniff'); if ($options['lifetime'] > 0 && !get_config('nocache')) { header('Cache-Control: max-age=' . $options['lifetime']); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $options['lifetime']) . ' GMT'); header('Pragma: '); if ($mimetype != 'text/plain' && $mimetype != 'text/html' && !isset($fileoutput)) { @header('Accept-Ranges: bytes'); if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'], 'bytes=') !== FALSE) { // Byteserving stuff - for Acrobat Reader and download accelerators // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php $ranges = false; if (preg_match_all('/(\\d*)-(\\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) { foreach ($ranges as $key => $value) { if ($ranges[$key][1] == '') { // Suffix case $ranges[$key][1] = $filesize - $ranges[$key][2]; $ranges[$key][2] = $filesize - 1; } else { if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) { // Fix range length $ranges[$key][2] = $filesize - 1; } } if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) { // Invalid byte-range ==> ignore header $ranges = false; break; } // Prepare multipart header $ranges[$key][0] = "\r\n--" . BYTESERVING_BOUNDARY . "\r\nContent-Type: {$mimetype}\r\n"; $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/{$filesize}\r\n\r\n"; } } else { $ranges = false; } if ($ranges) { byteserving_send_file($path, $mimetype, $ranges); } } } else { // Do not byteserve (disabled, strings, text and html files). header('Accept-Ranges: none'); } } else { // Do not cache files in proxies and browsers if (is_https() === true) { //https sites - watch out for IE! KB812935 and KB316431 header('Cache-Control: max-age=10'); header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); header('Pragma: '); } else { //normal http - prevent caching at all cost header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); header('Pragma: no-cache'); } header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled } if ($mimetype == 'text/plain') { // Add encoding header('Content-Type: Text/plain; charset=utf-8'); } else { if (isset($options['overridecontenttype'])) { header('Content-Type: ' . $options['overridecontenttype']); } else { header('Content-Type: ' . $mimetype); } } header('Content-Length: ' . $filesize); while (@ob_end_flush()) { } //flush the buffers - save memory and disable sid rewrite readfile_chunked($path); perf_to_log(); exit; }