/** * @param File $f * @throws Exception */ public function put(File $f) { $fp = fopen($f->getFullPath(), 'r'); if (!$fp) { throw new Exception('Unable to open file: ' . $f->getFilename()); } $uploader = UploadBuilder::newInstance()->setClient($this->client)->setSource($f->getFullPath())->setBucket($this->containerName)->setKey($this->getRelativeLinkFor($f))->build(); try { $uploader->upload(); } catch (MultipartUploadException $e) { $uploader->abort(); } }
/** * @param File $f * @throws Exception */ public function put(File $f) { $fp = fopen($f->getFullPath(), 'r'); if (!$fp) { throw new Exception('Unable to open file: ' . $f->getFilename()); } $uploader = new MultipartUploader($this->client, $f->getFullPath(), array('bucket' => $this->containerName, 'key' => $this->getRelativeLinkFor($f))); try { $uploader->upload(); } catch (MultipartUploadException $e) { // warning: below exception gets silently swallowed! error_log('S3Bucket: failed to put file: ' . $e->getPrevious()->getMessage()); throw new Exception('S3Bucket: failed to put file: ' . $e->getPrevious()->getMessage(), 0, $e); } }
/** * @param \File $file * @param null|Key $key * @return bool|\File * @throws InvalidInput * @throws CryptoException */ public function decryptFile($file, $key = null) { $key = $this->getKey($key); $decryptedFilename = str_replace('.enc', '', $file->getFullPath()); try { File::decryptFile($file->getFullPath(), $decryptedFilename, $key); unlink($file->getFullPath()); $file->Filename = str_replace('.enc', '', $file->Filename); $file->Name = str_replace('.enc', '', $file->Name); $file->write(); return $file; } catch (Exception $e) { SS_Log::log(sprintf('Decryption exception while parsing "%s": %s', $file->Name, $e->getMessage()), SS_Log::ERR); return false; } }
/** * update the uploaded image with an optimized kraked file * @param File $file * @param Array $tmpFile * @TODO need to remake cropped images */ public function onAfterLoad($file, $tmpFile) { $siteConfig = SiteConfig::current_site_config(); if (!$siteConfig->DisableKraken && $file->appCategory() === 'image') { $krakenService = new KrakenService(); $data = $krakenService->optimizeImage($file->getFullPath()); //check if optimization was success if ($data['success']) { //attempt to download the kraked file $krakedFile = $krakenService->getOptimizedImage($data['kraked_url']); //update the uploaded file file_put_contents($file->getFullPath(), $krakedFile); $file->Kraked = true; $file->write(); } } }
/** * @param File $f * @throws Exception */ public function put(File $f) { $fp = fopen($f->getFullPath(), 'r'); if (!$fp) { throw new Exception("Unable to open file: " . $f->getFilename()); } $headers = array(); if (!empty($this->config[self::FORCE_DL])) { $headers['Content-Disposition'] = 'attachment; filename=' . ($f->hasMethod('getFriendlyName') ? $f->getFriendlyName() : $f->Name); } $this->getContainer()->uploadObject($this->getRelativeLinkFor($f), $fp, $headers); }
function rename($new_name) { if (strstr($new_name, "/") !== false) { throw new InvalidParameterException("Il nome contiene caratteri non ammessi ( / )!!"); } $this_dir = $this->getDirectory(); $target_path = $this_dir->getPath() . "/" . $new_name; $target_file = new File($target_path); if ($target_file->exists()) { return false; } return rename($this->__full_path, $target_file->getFullPath()); }
static function extract($f, $dir) { $reader = $f->openReader(); $binarydata = $reader->read(3); $data = unpack("a3", $binarydata); if ($data[1] !== self::FF_ARCHIVE_HEADER) { throw new InvalidDataException("Intestazione del file non valida : " . $data[1]); } $binarydata = $reader->read(2 + 2 + 2); $data = unpack("v3", $binarydata); if ($data[1] !== self::CURRENT_MAJOR || $data[2] !== self::CURRENT_MINOR || $data[3] !== self::CURRENT_REV) { throw new InvalidDataException("Versione del file non supportata!! : " . $data[1] . "-" . $data[2] . "-" . $data[3]); } $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $num_entries = $data[1]; $i = 0; while ($i < $num_entries) { $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $entry_type = $data[1]; $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $path_length = $data[1]; $binarydata = $reader->read($path_length); $data = unpack("a*", $binarydata); $path = $data[1]; if ($entry_type === self::ENTRY_TYPE_DIR) { $d = $dir->newSubdir($path); $d->touch(); } if ($entry_type === self::ENTRY_TYPE_FILE) { $binarydata = $reader->read(4); $data = unpack("V", $binarydata); $num_bytes = $data[1]; $compressed_file_data = $reader->read($num_bytes); $uncompressed_file_data = gzuncompress($compressed_file_data); $f = new File($dir->getPath() . $path); $writer = $f->openWriter(); $writer->write($uncompressed_file_data); $writer->close(); $sha1_checksum = $reader->read(20); if (strcmp($sha1_checksum, sha1_file($f->getFullPath(), true)) !== 0) { throw new InvalidDataException("La somma sha1 non corrisponde per il file : " . $f->getPath()); } } $i++; } $reader->close(); }
public static function expandArchive($zip_file, $target_folder) { $zip_archive = new ZipArchive(); if ($zip_file instanceof File) { $real_zip_file = $zip_file; } else { $real_zip_file = new File($zip_file); } if ($target_folder instanceof Dir) { $target_dir = $target_folder; } else { $target_dir = new Dir($target_folder); } $zip_archive->open($real_zip_file->getFullPath()); $zip_archive->extractTo($target_dir->getFullPath()); $zip_archive->close(); }
public function run(File $file) { $fpath = $file->getFullPath(); $fpathlen = strlen($fpath); $res = new Tool_Result(); $cmd = 'xmllint --noout ' . escapeshellarg($fpath) . ' 2>&1'; exec($cmd, $output, $retval); if ($retval == 0) { $res->annotations['general'][] = new Tool_Result_Line('XML is well-formed', 'ok'); return $res; } for ($i = 0; $i < count($output); $i += 3) { $line = $output[$i]; if (substr($line, 0, $fpathlen) != $fpath) { throw new Exception('xmllint does not behave as expected: ' . $line); } list($linenum, $msg) = explode(':', substr($line, $fpathlen + 1), 2); $res->annotations[$linenum][] = new Tool_Result_Line($msg, 'error'); } $res->annotations['general'][] = new Tool_Result_Line('XML is not well-formed', 'error'); return $res; }
public function run(File $file) { $fpath = $file->getFullPath(); $fpathlen = strlen($fpath); $res = new Tool_Result(); $cmd = 'php -l ' . escapeshellarg($fpath) . ' 2>&1'; exec($cmd, $output, $retval); if ($retval == 0) { $res->annotations['general'][] = new Tool_Result_Line('No syntax errors detected', 'ok'); return $res; } $regex = '#^(.+) in ' . preg_quote($fpath) . ' on line ([0-9]+)$#'; for ($i = 0; $i < count($output) - 1; $i++) { $line = $output[$i]; if (!preg_match($regex, trim($line), $matches)) { throw new Exception('"php -l" does not behave as expected: ' . $line); } $msg = $matches[1]; $linenum = $matches[2]; $res->annotations[$linenum][] = new Tool_Result_Line($msg, 'error'); } $res->annotations['general'][] = new Tool_Result_Line('PHP code has syntax errors', 'error'); return $res; }
/** * * Moves this element and all its content to the specified target directory. * * @param \Mbcraft\Piol\Dir|string $target_dir The target directory as string path or Dir instance. * @param string $new_name The optional new full name of the moved element. * @return boolean true if this operation was succesfull, false otherwise. * * @api */ public function moveTo($target_dir, $new_name = null) { $target = Dir::asDir($target_dir); if ($new_name != null) { $name = $new_name; } else { if ($this->isDir()) { $name = $this->getName(); } else { $name = $this->getFullName(); } } if ($this->isDir()) { $dest = new Dir($target->getPath() . DS . $name); } else { $dest = new File($target->getPath() . DS . $name); } $target->touch(); return rename($this->getFullPath(), $dest->getFullPath()); }
/** * * @param File $file * @return void */ public function sendFileToBrowser($file) { $path = $file->getFullPath(); if (SapphireTest::is_running_test()) { return file_get_contents($path); } $basename = basename($path); $length = $file->getAbsoluteSize(); $type = HTTP::get_mime_type($file->getRelativePath()); //handling time limitation if ($threshold = $this->config()->bandwidth_threshold) { increase_time_limit_to((int) ($length / $threshold)); } else { increase_time_limit_to(); } // send header header('Content-Description: File Transfer'); /* * allow inline 'save as' popup, double quotation is present to prevent browser (eg. Firefox) from handling * wrongly a file with a name with whitespace, through a file in SilverStripe should not contain any whitespace * if the file is uploaded through SS interface * http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download */ header('Content-Type: ' . $type); header('Content-Disposition: inline; filename=' . $basename); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . $length); /** * issue fixes for IE6,7,8 when downloading a file over HTTPS (http://support.microsoft.com/kb/812935) * http://www.dotvoid.com/2009/10/problem-with-downloading-files-with-internet-explorer-over-https/ */ if (Director::is_https()) { header('Pragma: '); } header('Expires: 0'); header('Cache-Control: must-revalidate'); /** * unload the php session file * see http://konrness.com/php5/how-to-prevent-blocking-php-requests */ session_write_close(); // if output buffering is active, we clear it to prevent the script from trying to to allocate memory for entire file. while (ob_get_level() > 0) { ob_end_clean(); } flush(); readfile($path); exit(0); }
/** * * COPIED CODE!!!!! * * This is copied from here: * https://github.com/silverstripe-labs/silverstripe-secureassets/blob/master/code/SecureFileController.php * * @param File $file */ protected function sendFile($file) { $path = $file->getFullPath(); if (SapphireTest::is_running_test()) { return file_get_contents($path); } header('Content-Description: File Transfer'); // Quotes needed to retain spaces (http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download) header('Content-Disposition: inline; filename="' . basename($path) . '"'); header('Content-Length: ' . $file->getAbsoluteSize()); header('Content-Type: ' . HTTP::get_mime_type($file->getRelativePath())); header('Content-Transfer-Encoding: binary'); // Fixes IE6,7,8 file downloads over HTTPS bug (http://support.microsoft.com/kb/812935) header('Pragma: '); if ($this->config()->min_download_bandwidth) { // Allow the download to last long enough to allow full download with min_download_bandwidth connection. increase_time_limit_to((int) (filesize($path) / ($this->config()->min_download_bandwidth * 1024))); } else { // Remove the timelimit. increase_time_limit_to(0); } // Clear PHP buffer, otherwise the script will try to allocate memory for entire file. while (ob_get_level() > 0) { ob_end_flush(); } // Prevent blocking of the session file by PHP. Without this the user can't visit another page of the same // website during download (see http://konrness.com/php5/how-to-prevent-blocking-php-requests/) session_write_close(); readfile($path); die; }
static function extract($f, $dir) { if ($f instanceof File) { $source_file = $f; } else { $source_file = new File($f); } if ($dir instanceof Dir) { $target_dir = $dir; } else { $target_dir = new Dir($dir); } $reader = $source_file->openReader(); $binarydata = $reader->read(3); $data = unpack("a3", $binarydata); if ($data[1] !== self::FF_ARCHIVE_HEADER) { throw new InvalidDataException("Intestazione del file non valida : " . $data[1]); } $binarydata = $reader->read(2 + 2 + 2); $data = unpack("v3", $binarydata); if ($data[1] !== self::CURRENT_MAJOR || $data[2] !== self::CURRENT_MINOR || $data[3] !== self::CURRENT_REV) { throw new InvalidDataException("Versione del file non supportata!! : " . $data[1] . "-" . $data[2] . "-" . $data[3]); } //properties $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $properties_length = $data[1]; if ($properties_length > 0) { $binarydata = $reader->read($properties_length); $data = unpack("a*", $binarydata); $properties = PropertiesUtils::readFromString($data[1], false); } else { $properties = array(); } //num entries $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $num_entries = $data[1]; $i = 0; while ($i < $num_entries) { //entry type $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $entry_type = $data[1]; //path length $binarydata = $reader->read(2); $data = unpack("v", $binarydata); $path_length = $data[1]; //path $binarydata = $reader->read($path_length); $data = unpack("a*", $binarydata); $path = $data[1]; if ($entry_type === self::ENTRY_TYPE_DIR) { $d = $target_dir->newSubdir($path); $d->touch(); } if ($entry_type === self::ENTRY_TYPE_FILE) { //compressed size $binarydata = $reader->read(4); $data = unpack("V", $binarydata); $num_bytes = $data[1]; //compressed data $compressed_file_data = $reader->read($num_bytes); $uncompressed_file_data = gzuncompress($compressed_file_data); $f = new File($target_dir->getPath() . $path); $writer = $f->openWriter(); $writer->write($uncompressed_file_data); $writer->close(); //sha1 sum $sha1_checksum = $reader->read(20); if (strcmp($sha1_checksum, sha1_file($f->getFullPath(), true)) !== 0) { throw new InvalidDataException("La somma sha1 non corrisponde per il file : " . $f->getPath()); } } $i++; } $reader->close(); return true; }
/** * Returns true if the local file is not available * @return bool */ public function isLocalMissing() { return !file_exists($this->owner->getFullPath()) || $this->containsPlaceholder(); }
/** * Sends the given file by whatever method is appropriate. Uses php's * header() instead of silverstripe's HTTPResponse class to prevent other * headers from being added and so we can just use readfile() instead of * pulling the whole file into a string for setBody(). * * @param File $file */ protected function sendFile(File $file) { // this is for optional compatibility with markguinn/silverstripe-cloudassets if ($file->hasExtension('CloudFileExtension') && $file->CloudStatus === 'Live') { header('Location: ' . $file->getAbsoluteURL()); exit; } // this is the normal way to send the files header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $file->Name . '"'); if (Config::inst()->get('Downloadable', 'use_xsendfile')) { header('X-Sendfile: ' . $file->getURL()); } else { header('Content-Length: ' . $file->getAbsoluteSize()); readfile($file->getFullPath()); } exit; }
public static function recycle(File $file, $verbose = true) { $recylcingFolder = Folder::find_or_make(Config::inst()->get("MetaTagCMSControlFiles", "recycling_bin_name")); if ($recylcingFolder) { if ($file) { if ($file->exists()) { if (file_exists($file->getFullPath())) { $valid = $file->validate(); if ($valid->valid()) { $record = new MetaTagCMSControlFileUse_RecyclingRecord(); $record->FileID = $file->ID; $record->FromFolderID = $file->ParentID; $record->write(); //doing it..... $file->ParentID = $recylcingFolder->ID; $file->write(); //IMPORTANT! return true; } } $record = new MetaTagCMSControlFileUse_RecyclingRecord(); $record->FileID = $file->ID; $record->FromFolderID = $file->ParentID; $record->write(); DB::query("UPDATE \"File\" SET \"ParentID\" = " . $recylcingFolder->ID . " WHERE \"File\".\"ID\" = " . $file->ID); return true; } } } return false; }
protected function getKey(File $file) { return md5($file->getFullPath()); }
function move_to($target_dir, $new_name = null) { if ($new_name != null) { $name = $new_name; } else { $name = $this->getName(); } if ($this->isDir()) { $dest = new Dir($target_dir->getPath() . "/" . $name); } else { $dest = new File($target_dir->getPath() . "/" . $name); } $target_dir->touch(); return rename($this->getFullPath(), $dest->getFullPath()); }
/** * We need to test that the _versions folder isn't completed wiped by * {@link VersionedFileExtension::onBeforeDelete()} when there is more than the file currently being deleted. */ public function testOnBeforeDelete() { // Create the second file $file2 = $this->folder->getFullPath() . 'test-file2.txt'; file_put_contents($file2, 'first-version'); $file2Obj = new File(); $file2Obj->ParentID = $this->folder->ID; $file2Obj->Filename = $this->folder->getFilename() . 'test-file2.txt'; $file2Obj->write(); // Create a second version of the second file file_put_contents($file2Obj->getFullPath(), 'second-version'); $file2Obj->createVersion(); // Delete the second file $file2Obj->delete(); // Ensure the _versions folder still exists $this->assertTrue(is_dir($this->folder->getFullPath())); $this->assertTrue(is_dir($this->folder->getFullPath() . '/_versions')); // Now delete the first file, and ensure the _versions folder no longer exists $this->file->delete(); $this->assertTrue(is_dir($this->folder->getFullPath())); $this->assertFalse(is_dir($this->folder->getFullPath() . '/_versions')); // Now create another file to ensure that the _versions folder can be successfully re-created $file3 = $this->folder->getFullPath() . 'test-file3.txt'; file_put_contents($file3, 'first-version'); $file3Obj = new File(); $file3Obj->ParentID = $this->folder->ID; $file3Obj->Filename = $this->folder->getFilename() . 'test-file3.txt'; $file3Obj->write(); $this->assertTrue(is_file($file3Obj->getFullPath())); $this->assertTrue(is_dir($this->folder->getFullPath() . '/_versions')); }
/** * * Renames this file. Rename does not allow moving the file. * * @param string $new_name the new file name. * @return boolean true if the operation was succesfull, false otherwise * @throws \Mbcraft\Piol\IOException if the name contains invalid characters. * * @api */ public function rename($new_name) { FileSystemUtils::checkValidFilename($new_name); $this_dir = $this->getParentDir(); $target_path = $this_dir->getPath() . DS . $new_name; $target_file = new File($target_path); if ($target_file->exists()) { return false; } return rename($this->__full_path, $target_file->getFullPath()); }
/** * Action to handle upload of a single file * * @param SS_HTTPRequest $request * @return string json */ public function upload(SS_HTTPRequest $request) { if (!$this->currentVersionFile) { return; } if ($this->isDisabled() || $this->isReadonly()) { return $this->httpError(403); } // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); if (!$token->checkRequest($request)) { return $this->httpError(400); } $name = $this->getName(); $tmpfile = $request->postVar($name); $record = $this->getRecord(); // Check if the file has been uploaded into the temporary storage. if (!$tmpfile) { $return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found')); } else { $return = array('name' => $tmpfile['name'], 'size' => $tmpfile['size'], 'type' => $tmpfile['type'], 'error' => $tmpfile['error']); } // Check for constraints on the record to which the file will be attached. if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) { $tooManyFiles = false; // Some relationships allow many files to be attached. if ($this->getConfig('allowedMaxFileNumber') && ($record->has_many($name) || $record->many_many($name))) { if (!$record->isInDB()) { $record->write(); } $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber'); // has_one only allows one file at any given time. } elseif ($record->has_one($name)) { $tooManyFiles = $record->{$name}() && $record->{$name}()->exists(); } // Report the constraint violation. if ($tooManyFiles) { if (!$this->getConfig('allowedMaxFileNumber')) { $this->setConfig('allowedMaxFileNumber', 1); } $return['error'] = _t('UploadField.MAXNUMBEROFFILES', 'Max number of {count} file(s) exceeded.', array('count' => $this->getConfig('allowedMaxFileNumber'))); } } // Process the uploaded file if (!$return['error']) { // Get the uploaded file into a new file object. try { $currentFilePath = $this->currentVersionFile->getFullPath(); if (file_exists($currentFilePath)) { unlink($this->currentVersionFile->getFullPath()); } // If $folderName == assets (by default), then this will try and create a file inside assets/assets // instead of creating it in the root. This check ensures that the newly uploaded files overwrites the // old file in the assets root directory. $folderName = $this->folderName; if ($folderName == basename(ASSETS_PATH)) { $folderName = "/"; } $this->upload->loadIntoFile(array_merge($tmpfile, array('name' => $this->currentVersionFile->Name)), $this->currentVersionFile, $folderName); } catch (Exception $e) { // we shouldn't get an error here, but just in case $return['error'] = $e->getMessage(); } if (!$return['error']) { if ($this->upload->isError()) { $return['error'] = implode(' ' . PHP_EOL, $this->upload->getErrors()); } else { $file = $this->upload->getFile(); $file->createVersion(); // Attach the file to the related record. if ($this->relationAutoSetting) { $this->attachFile($file); } // Collect all output data. $file = $this->customiseFile($file); $return = array_merge($return, array('id' => $file->ID, 'name' => $file->getTitle() . '.' . $file->getExtension(), 'url' => $file->getURL(), 'thumbnail_url' => $file->UploadFieldThumbnailURL, 'edit_url' => $file->UploadFieldEditLink, 'size' => $file->getAbsoluteSize(), 'buttons' => $file->UploadFieldFileButtons)); } } } $response = new SS_HTTPResponse(Convert::raw2json(array($return))); $response->addHeader('Content-Type', 'text/plain'); return $response; }
public function renderPath(File $file) { $upload = $file->getUpload(); return file_exists($file->getFullPath()) ? $this->renderTd($file->getDisplayFilename()) : $this->renderTd('<div class="reupload-conteiner"><span class="upload-name">' . $this->escape($file->getDisplayFilename()) . '</span><br />' . '<div class="reupload-conteiner-hide"><span class="error">' . ___('File was removed from disk or corrupted. Please re-upload it.') . '</span>' . '<div><span class="reupload" data-upload_id="' . $upload->pk() . '" id="reupload-' . $upload->pk() . '"></span></div></div></div>', false); }
public static function get_image_data($source_file) { if ($source_file instanceof File) { $f = $source_file; } else { $f = new File($source_file); } $data = getimagesize($f->getFullPath()); $result = array(); $result["width"] = $data[0]; $result["height"] = $data[1]; $result["mime_type"] = $data["mime"]; return $result; }
/** * @param File $f */ public function put(File $f) { $this->uploads[] = $f->Filename; $this->uploadContents[$f->Filename] = file_get_contents($f->getFullPath()); }
function testCreateNewFile() { $f_new = new File("/" . FRAMEWORK_CORE_PATH . "tests/io/test_dir/content_dir/new_file.txt"); $this->assertNotEqual("", $f_new->getFullPath()); $this->assertNotNull($f_new->getFullPath()); //$current_mtime = $f_new->getModificationTime(); $this->assertFalse($f_new->exists(), "Il file esiste!!"); $f_new->touch(); //$new_mtime = $f_new->getModificationTime(); //$this->assertNotEqual($current_mtime, $new_mtime); $this->assertTrue($f_new->exists(), "Il file non รจ stato creato!"); $f_new->delete(); $this->assertFalse($f_new->exists(), "Il file esiste!!"); }