public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { // TODO: use proc_open() and stream the source file ? $absPath = \OC_Helper::tmpFile(); $tmpPath = \OC_Helper::tmpFile(); $handle = $fileview->fopen($path, 'rb'); // we better use 5MB (1024 * 1024 * 5 = 5242880) instead of 1MB. // in some cases 1MB was no enough to generate thumbnail $firstmb = stream_get_contents($handle, 5242880); file_put_contents($absPath, $firstmb); if (self::$avconvBinary) { $cmd = self::$avconvBinary . ' -an -y -ss 5' . ' -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1 -vsync 1 ' . escapeshellarg($tmpPath) . ' > /dev/null 2>&1'; } else { $cmd = self::$ffmpegBinary . ' -y -ss 5' . ' -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1' . ' -s ' . escapeshellarg($maxX) . 'x' . escapeshellarg($maxY) . ' ' . escapeshellarg($tmpPath) . ' > /dev/null 2>&1'; } exec($cmd, $output, $returnCode); unlink($absPath); if ($returnCode === 0) { $image = new \OC_Image(); $image->loadFromFile($tmpPath); unlink($tmpPath); return $image->valid() ? $image : false; } return false; }
/** * @param \Doctrine\DBAL\Schema\Schema $targetSchema * @throws \OC\DB\MigrationException * * For sqlite we simple make a copy of the entire database, and test the migration on that */ public function checkMigrate(\Doctrine\DBAL\Schema\Schema $targetSchema) { $dbFile = $this->connection->getDatabase(); $tmpFile = \OC_Helper::tmpFile('.db'); copy($dbFile, $tmpFile); $connectionParams = array('path' => $tmpFile, 'driver' => 'pdo_sqlite'); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams); try { $this->applySchema($targetSchema, $conn); $conn->close(); unlink($tmpFile); } catch (DBALException $e) { $conn->close(); unlink($tmpFile); throw new MigrationException('', $e->getMessage()); } }
/** * @param int $maxX * @param int $maxY * @param string $absPath * @param int $second * @return bool|\OCP\IImage */ private function generateThumbNail($maxX, $maxY, $absPath, $second) { $tmpPath = \OC_Helper::tmpFile(); if (self::$avconvBinary) { $cmd = self::$avconvBinary . ' -an -y -ss ' . escapeshellarg($second) . ' -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1 -vsync 1 ' . escapeshellarg($tmpPath) . ' > /dev/null 2>&1'; } else { $cmd = self::$ffmpegBinary . ' -y -ss ' . escapeshellarg($second) . ' -i ' . escapeshellarg($absPath) . ' -f mjpeg -vframes 1' . ' -s ' . escapeshellarg($maxX) . 'x' . escapeshellarg($maxY) . ' ' . escapeshellarg($tmpPath) . ' > /dev/null 2>&1'; } exec($cmd, $output, $returnCode); if ($returnCode === 0) { $image = new \OC_Image(); $image->loadFromFile($tmpPath); unlink($tmpPath); return $image->valid() ? $image : false; } unlink($tmpPath); return false; }
/** * @param string $path * @return string */ protected function toTmpFile($path) { //no longer in the storage api, still useful here $source = $this->fopen($path, 'r'); if (!$source) { return false; } if ($pos = strrpos($path, '.')) { $extension = substr($path, $pos); } else { $extension = ''; } $tmpFile = \OC_Helper::tmpFile($extension); $target = fopen($tmpFile, 'w'); \OC_Helper::streamCopy($source, $target); fclose($target); return $tmpFile; }
public static function getPackage($url, $version) { self::$package = \OC_Helper::tmpFile(); if (!self::$package) { throw new \Exception('Unable to create a temporary file'); } try { if (file_put_contents(self::$package, self::fetch($url)) === false) { throw new \Exception("Error storing package content"); } if (preg_match('/\\.zip$/i', $url)) { rename(self::$package, self::$package . '.zip'); self::$package .= '.zip'; } elseif (preg_match('/(\\.tgz|\\.tar\\.gz)$/i', $url)) { rename(self::$package, self::$package . '.tgz'); self::$package .= '.tgz'; } elseif (preg_match('/\\.tar\\.bz2$/i', $url)) { rename(self::$package, self::$package . '.tar.bz2'); self::$package .= '.tar.bz2'; } else { throw new \Exception('Unable to extract package'); } $extractDir = self::getPackageDir($version); Helper::mkdir($extractDir, true); $archive = \OC_Archive::open(self::$package); if (!$archive || !$archive->extract($extractDir)) { throw new \Exception(self::$package . " extraction error"); } } catch (\Exception $e) { App::log('Retrieving ' . $url); self::cleanUp($version); throw $e; } Helper::removeIfExists(self::$package); // Prepare extracted data // to have '3rdparty', 'apps' and 'core' subdirectories $sources = Helper::getSources($version); $baseDir = $extractDir . '/' . self::PACKAGE_ROOT; @rename($baseDir . '/' . Helper::THIRDPARTY_DIRNAME, $sources[Helper::THIRDPARTY_DIRNAME]); @rename($baseDir . '/' . Helper::APP_DIRNAME, $sources[Helper::APP_DIRNAME]); @rename($baseDir, $sources[Helper::CORE_DIRNAME]); }
public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { require_once 'PHPExcel/Classes/PHPExcel.php'; require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php'; $absPath = $fileview->toTmpFile($path); $tmpPath = \OC_Helper::tmpFile(); $rendererName = \PHPExcel_Settings::PDF_RENDERER_DOMPDF; $rendererLibraryPath = \OC::$THIRDPARTYROOT . '/3rdparty/dompdf'; \PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibraryPath); $phpexcel = new \PHPExcel($absPath); $excel = \PHPExcel_IOFactory::createWriter($phpexcel, 'PDF'); $excel->save($tmpPath); $pdf = new \imagick($tmpPath . '[0]'); $pdf->setImageFormat('jpg'); unlink($absPath); unlink($tmpPath); $image = new \OC_Image(); $image->loadFromData($pdf); return $image->valid() ? $image : false; }
public function testUpdateApp() { $pathOfOldTestApp = __DIR__; $pathOfOldTestApp .= '/../data/'; $pathOfOldTestApp .= 'testapp.zip'; $oldTmp = OC_Helper::tmpFile('.zip'); OC_Helper::copyr($pathOfOldTestApp, $oldTmp); $oldData = array('path' => $oldTmp, 'source' => 'path'); $pathOfNewTestApp = __DIR__; $pathOfNewTestApp .= '/../data/'; $pathOfNewTestApp .= 'testapp2.zip'; $newTmp = OC_Helper::tmpFile('.zip'); OC_Helper::copyr($pathOfNewTestApp, $newTmp); $newData = array('path' => $newTmp, 'source' => 'path'); OC_Installer::installApp($oldData); $oldVersionNumber = OC_App::getAppVersion(self::$appid); OC_Installer::updateApp($newData); $newVersionNumber = OC_App::getAppVersion(self::$appid); $this->assertNotEquals($oldVersionNumber, $newVersionNumber); }
public static function getPackage($url, $version) { self::$package = \OC_Helper::tmpFile(); try { if (!copy($url, self::$package)) { throw new \Exception("Failed to download {$url} package"); } if (preg_match('/\\.zip$/i', $url)) { rename(self::$package, self::$package . '.zip'); self::$package .= '.zip'; } elseif (preg_match('/(\\.tgz|\\.tar\\.gz)$/i', $url)) { rename(self::$package, self::$package . '.tgz'); self::$package .= '.tgz'; } elseif (preg_match('/\\.tar\\.bz2$/i', $url)) { rename(self::$package, self::$package . '.tar.bz2'); self::$package .= '.tar.bz2'; } else { throw new \Exception('Unable to extract package'); } $extractDir = self::getPackageDir($version); Helper::mkdir($extractDir, true); $archive = \OC_Archive::open(self::$package); if ($archive) { $archive->extract($extractDir); } else { throw new \Exception(self::$package . " extraction error"); } } catch (\Exception $e) { self::cleanUp($version); throw $e; } Helper::removeIfExists(self::$package); // Prepare extracted data // to have '3rdparty', 'apps' and 'core' subdirectories $sources = Helper::getSources($version); $baseDir = $extractDir . '/' . self::PACKAGE_ROOT; @rename($baseDir . '/' . Helper::THIRDPARTY_DIRNAME, $sources[Helper::THIRDPARTY_DIRNAME]); @rename($baseDir . '/' . Helper::APP_DIRNAME, $sources[Helper::APP_DIRNAME]); @rename($baseDir, $sources[Helper::CORE_DIRNAME]); }
public static function getPackage($url, $version) { $path = \OC_Helper::tmpFile(); if (!copy($url, $path)) { \OC_Log::write(App::APP_ID, "Failed to download {$url} package to {$path}", \OC_Log::ERROR); return false; } //Mimetype bug workaround $mime = rtrim(\OC_Helper::getMimeType($path), ';'); if ($mime == 'application/zip') { rename($path, $path . '.zip'); $path .= '.zip'; } elseif ($mime == 'application/x-gzip') { rename($path, $path . '.tgz'); $path .= '.tgz'; } elseif ($mime == 'application/x-bzip2') { rename($path, $path . '.tar.bz2'); $path .= '.tar.bz2'; } else { \OC_Log::write(App::APP_ID, 'Archives of type ' . $mime . ' are not supported', \OC_Log::ERROR); return false; } $extractDir = self::getPackageDir($version); if (!mkdir($extractDir, 0777, true)) { \OC_Log::write(App::APP_ID, 'Unable to create temporary directory', \OC_Log::ERROR); return false; } $archive = \OC_Archive::open($path); if ($archive) { $archive->extract($extractDir); } else { \OC_Log::write(App::APP_ID, "Failed to open package {$path}", \OC_Log::ERROR); \OC_Helper::rmdirr($extractDir); @unlink($path); return false; } return $extractDir . DIRECTORY_SEPARATOR . self::PACKAGE_ROOT; }
public function fopen($path, $mode) { $path = $this->normalizePath($path); switch ($mode) { case 'r': case 'rb': $stat = $this->stat($path); if (is_array($stat)) { try { return $this->objectStore->readObject($this->getURN($stat['fileid'])); } catch (\Exception $ex) { \OCP\Util::writeLog('objectstore', 'Could not get object: ' . $ex->getMessage(), \OCP\Util::ERROR); return false; } } else { return false; } case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tmpFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } return false; }
/** * detect mimetype based on the content of a string * * @param string $data * @return string */ public function detectString($data) { if (function_exists('finfo_open') and function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); return finfo_buffer($finfo, $data); } else { $tmpFile = \OC_Helper::tmpFile(); $fh = fopen($tmpFile, 'wb'); fwrite($fh, $data, 8024); fclose($fh); $mime = $this->detect($tmpFile); unset($tmpFile); return $mime; } }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $file ; separated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { $xsendfile = false; if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { $xsendfile = true; } if (is_array($files) && count($files) == 1) { $files = $files[0]; } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); if ($xsendfile) { $filename = OC_Helper::tmpFileNoClean('.zip'); } else { $filename = OC_Helper::tmpFile('.zip'); } if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { exit("cannot open <{$filename}>\n"); } foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $tmpFile = \OC\Files\Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (\OC\Files\Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); $basename = basename($dir); if ($basename) { $name = $basename . '.zip'; } else { $name = 'owncloud.zip'; } set_time_limit($executionTime); } elseif (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); if ($xsendfile) { $filename = OC_Helper::tmpFileNoClean('.zip'); } else { $filename = OC_Helper::tmpFile('.zip'); } if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { exit("cannot open <{$filename}>\n"); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); $name = $files . '.zip'; set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; $name = $files; } OC_Util::obEnd(); if ($zip or \OC\Files\Filesystem::isReadable($filename)) { if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) { header('Content-Disposition: attachment; filename="' . rawurlencode($name) . '"'); } else { header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($name) . '; filename="' . rawurlencode($name) . '"'); } header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); self::addSendfileHeader($filename); } else { header('Content-Type: ' . \OC\Files\Filesystem::getMimeType($filename)); header("Content-Length: " . \OC\Files\Filesystem::filesize($filename)); list($storage) = \OC\Files\Filesystem::resolvePath($filename); if ($storage instanceof \OC\Files\Storage\Local) { self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename)); } } } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $name); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } if (!$xsendfile) { unlink($filename); } } else { \OC\Files\Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
public function fopen($path, $mode) { $path = $this->normalizePath($path); switch ($mode) { case 'r': case 'rb': $tmpFile = \OC_Helper::tmpFile(); self::$tmpFiles[$tmpFile] = $path; try { $object = $this->container->getObject($path); } catch (ClientErrorResponseException $e) { \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); return false; } catch (Exception\ObjectNotFoundException $e) { \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); return false; } try { $objectContent = $object->getContent(); $objectContent->rewind(); $stream = $objectContent->getStream(); file_put_contents($tmpFile, $stream); } catch (Exceptions\IOError $e) { \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); return false; } return fopen($tmpFile, 'r'); case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tmpFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } }
/** * @brief Installs an app * @param $data array with all information * @returns integer * * This function installs an app. All information needed are passed in the * associative array $data. * The following keys are required: * - source: string, can be "path" or "http" * * One of the following keys is required: * - path: path to the file containing the app * - href: link to the downloadable file containing the app * * The following keys are optional: * - pretend: boolean, if set true the system won't do anything * - noinstall: boolean, if true appinfo/install.php won't be loaded * - inactive: boolean, if set true the appconfig/app.sample.php won't be * renamed * * This function works as follows * -# fetching the file * -# unzipping it * -# check the code * -# installing the database at appinfo/database.xml * -# including appinfo/install.php * -# setting the installed version * * It is the task of oc_app_install to create the tables and do whatever is * needed to get the app working. */ public static function installApp($data = array()) { if (!isset($data['source'])) { OC_Log::write('core', 'No source specified when installing app', OC_Log::ERROR); return false; } //download the file if necesary if ($data['source'] == 'http') { $path = OC_Helper::tmpFile(); if (!isset($data['href'])) { OC_Log::write('core', 'No href specified when installing app from http', OC_Log::ERROR); return false; } copy($data['href'], $path); } else { if (!isset($data['path'])) { OC_Log::write('core', 'No path specified when installing app from local file', OC_Log::ERROR); return false; } $path = $data['path']; } //detect the archive type $mime = OC_Helper::getMimeType($path); if ($mime == 'application/zip') { rename($path, $path . '.zip'); $path .= '.zip'; } elseif ($mime == 'application/x-gzip') { rename($path, $path . '.tgz'); $path .= '.tgz'; } else { OC_Log::write('core', 'Archives of type ' . $mime . ' are not supported', OC_Log::ERROR); return false; } //extract the archive in a temporary folder $extractDir = OC_Helper::tmpFolder(); OC_Helper::rmdirr($extractDir); mkdir($extractDir); if ($archive = OC_Archive::open($path)) { $archive->extract($extractDir); } else { OC_Log::write('core', 'Failed to open archive when installing app', OC_Log::ERROR); OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } return false; } //load the info.xml file of the app if (!is_file($extractDir . '/appinfo/info.xml')) { //try to find it in a subdir $dh = opendir($extractDir); while ($folder = readdir($dh)) { if (substr($folder, 0, 1) != '.' and is_dir($extractDir . '/' . $folder)) { if (is_file($extractDir . '/' . $folder . '/appinfo/info.xml')) { $extractDir .= '/' . $folder; } } } } if (!is_file($extractDir . '/appinfo/info.xml')) { OC_Log::write('core', 'App does not provide an info.xml file', OC_Log::ERROR); OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } return false; } $info = OC_App::getAppInfo($extractDir . '/appinfo/info.xml', true); $basedir = OC::$APPSROOT . '/apps/' . $info['id']; // check the code for not allowed calls if (!OC_Installer::checkCode($info['id'], $extractDir)) { OC_Log::write('core', 'App can\'t be installed because of not allowed code in the App', OC_Log::ERROR); OC_Helper::rmdirr($extractDir); return false; } // check if the app is compatible with this version of ownCloud $version = OC_Util::getVersion(); if (!isset($info['require']) or $version[0] > $info['require']) { OC_Log::write('core', 'App can\'t be installed because it is not compatible with this version of ownCloud', OC_Log::ERROR); OC_Helper::rmdirr($extractDir); return false; } //check if an app with the same id is already installed if (self::isInstalled($info['id'])) { OC_Log::write('core', 'App already installed', OC_Log::WARN); OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } return false; } //check if the destination directory already exists if (is_dir($basedir)) { OC_Log::write('core', 'App directory already exists', OC_Log::WARN); OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } return false; } if (isset($data['pretent']) and $data['pretent'] == true) { return false; } //copy the app to the correct place if (@(!mkdir($basedir))) { OC_Log::write('core', 'Can\'t create app folder. Please fix permissions. (' . $basedir . ')', OC_Log::ERROR); OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } return false; } OC_Helper::copyr($extractDir, $basedir); //remove temporary files OC_Helper::rmdirr($extractDir); //install the database if (is_file($basedir . '/appinfo/database.xml')) { OC_DB::createDbFromStructure($basedir . '/appinfo/database.xml'); } //run appinfo/install.php if ((!isset($data['noinstall']) or $data['noinstall'] == false) and file_exists($basedir . '/appinfo/install.php')) { include $basedir . '/appinfo/install.php'; } //set the installed version OC_Appconfig::setValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'])); OC_Appconfig::setValue($info['id'], 'enabled', 'no'); //set remote/public handelers foreach ($info['remote'] as $name => $path) { OCP\CONFIG::setAppValue('core', 'remote_' . $name, '/apps/' . $info['id'] . '/' . $path); } foreach ($info['public'] as $name => $path) { OCP\CONFIG::setAppValue('core', 'public_' . $name, '/apps/' . $info['id'] . '/' . $path); } OC_App::setAppTypes($info['id']); return $info['id']; }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $file ; separated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { $xsendfile = false; if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { $xsendfile = true; } if (is_array($files) && count($files) == 1) { $files = $files[0]; } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { $l = OC_L10N::get('lib'); throw new Exception($l->t('cannot open "%s"', array($filename))); } foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $tmpFile = \OC\Files\Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (\OC\Files\Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); if ($xsendfile) { $filename = OC_Helper::moveToNoClean($filename); } $basename = basename($dir); if ($basename) { $name = $basename . '.zip'; } else { $name = 'download.zip'; } set_time_limit($executionTime); } elseif (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { $l = OC_L10N::get('lib'); throw new Exception($l->t('cannot open "%s"', array($filename))); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); if ($xsendfile) { $filename = OC_Helper::moveToNoClean($filename); } $name = $files . '.zip'; set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; $name = $files; if ($xsendfile && OC_App::isEnabled('files_encryption')) { $xsendfile = false; } } OC_Util::obEnd(); if ($zip or \OC\Files\Filesystem::isReadable($filename)) { OC_Response::setContentDispositionHeader($name, 'attachment'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); self::addSendfileHeader($filename); } else { $filesize = \OC\Files\Filesystem::filesize($filename); header('Content-Type: ' . \OC\Files\Filesystem::getMimeType($filename)); if ($filesize > -1) { header("Content-Length: " . $filesize); } if ($xsendfile) { list($storage) = \OC\Files\Filesystem::resolvePath(\OC\Files\Filesystem::getView()->getAbsolutePath($filename)); /** * @var \OC\Files\Storage\Storage $storage */ if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Local')) { self::addSendfileHeader(\OC\Files\Filesystem::getLocalFile($filename)); } } } } elseif ($zip or !\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $name); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } if (!$xsendfile) { unlink($filename); } } else { \OC\Files\Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
public function fopen($path, $mode) { $path = $this->root . $path; switch ($mode) { case 'r': case 'rb': $tmpFile = \OC_Helper::tmpFile(); try { $data = $this->dropbox->getFile($path); file_put_contents($tmpFile, $data); return fopen($tmpFile, 'r'); } catch (\Exception $exception) { \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR); return false; } case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tempFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } return false; }
public function fopen($path, $mode) { $path = $this->normalizePath($path); switch ($mode) { case 'r': case 'rb': $tmpFile = \OC_Helper::tmpFile(); self::$tmpFiles[$tmpFile] = $path; try { $result = $this->connection->getObject(array('Bucket' => $this->bucket, 'Key' => $this->cleanKey($path), 'SaveAs' => $tmpFile)); } catch (S3Exception $e) { \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); return false; } return fopen($tmpFile, 'r'); case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tmpFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } return false; }
public function fopen($path, $mode) { switch ($mode) { case 'r': case 'rb': $tmpFile = OC_Helper::tmpFile(); $handle = fopen($tmpFile, 'w'); $response = $this->s3->get_object($this->bucket, $path, array('fileDownload' => $handle)); if ($response->isOK()) { return fopen($tmpFile, 'r'); } break; case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = OC_Helper::tmpFile($ext); OC_CloseStreamWrapper::$callBacks[$tmpFile] = array($this, 'writeBack'); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tempFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } return false; }
public function fopen($path, $mode) { try { $absPath = $this->absPath($path); switch ($mode) { case 'r': case 'rb': if (!$this->file_exists($path)) { return false; } if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmp = \OC_Helper::tmpFile($ext); $this->getFile($absPath, $tmp); return fopen($tmp, $mode); case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $this->getFile($absPath, $tmpFile); } self::$tempFiles[$tmpFile] = $absPath; return fopen('close://' . $tmpFile, $mode); } } catch (\Exception $e) { } return false; }
public function testHooks() { if (\OC\Files\Filesystem::getView()) { $user = \OC_User::getUser(); } else { $user = self::TEST_FILESYSTEM_USER1; $backend = new \Test\Util\User\Dummy(); \OC_User::useBackend($backend); $backend->createUser($user, $user); $userObj = \OC::$server->getUserManager()->get($user); \OC::$server->getUserSession()->setUser($userObj); \OC\Files\Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); \OC\Files\Filesystem::mount('OC\\Files\\Storage\\Temporary', array(), '/'); $rootView = new \OC\Files\View(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); \OC\Files\Filesystem::mkdir('/bar'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo'); $tmpFile = \OC_Helper::tmpFile(); file_put_contents($tmpFile, 'foo'); $fh = fopen($tmpFile, 'r'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh); }
/** * create a temporary file with an unique filename * @param string postfix * @return string * * temporary files are automatically cleaned up after the script is finished */ public static function tmpFile($postfix = '') { return \OC_Helper::tmpFile($postfix); }
/** * return the content of a file or return a zip file containning multiply files * * @param dir $dir * @param file $file ; seperated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { if (strpos($files, ';')) { $files = explode(';', $files); } if (is_array($files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) { exit("cannot open <{$filename}>\n"); } foreach ($files as $file) { $file = $dir . '/' . $file; if (OC_Filesystem::is_file($file)) { $tmpFile = OC_Filesystem::toTmpFile($file); self::$tmpFiles[] = $tmpFile; $zip->addFile($tmpFile, basename($file)); } elseif (OC_Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } $zip->close(); set_time_limit($executionTime); } elseif (OC_Filesystem::is_dir($dir . '/' . $files)) { self::validateZipDownload($dir, $files); $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); $zip = new ZipArchive(); $filename = OC_Helper::tmpFile('.zip'); if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) { exit("cannot open <{$filename}>\n"); } $file = $dir . '/' . $files; self::zipAddDir($file, $zip); $zip->close(); set_time_limit($executionTime); } else { $zip = false; $filename = $dir . '/' . $files; } @ob_end_clean(); if ($zip or OC_Filesystem::is_readable($filename)) { header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); OC_Response::disableCaching(); if ($zip) { ini_set('zlib.output_compression', 'off'); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($filename)); } else { $fileData = OC_FileCache::get($filename); header('Content-Type: ' . $fileData['mimetype']); } } elseif ($zip or !OC_Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->assign('file', $filename); $tmpl->printPage(); } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { if (!$zip) { header("Content-Length: " . OC_Filesystem::filesize($filename)); } return; } if ($zip) { $handle = fopen($filename, 'r'); if ($handle) { $chunkSize = 8 * 1024; // 1 MB chunks while (!feof($handle)) { echo fread($handle, $chunkSize); flush(); } } unlink($filename); } else { OC_Filesystem::readfile($filename); } foreach (self::$tmpFiles as $tmpFile) { if (file_exists($tmpFile) and is_file($tmpFile)) { unlink($tmpFile); } } }
public function toTmpFile($path) { if (OC_Filesystem::isValidPath($path)) { $source = $this->fopen($path, 'r'); if ($source) { $extension = ''; $extOffset = strpos($path, '.'); if ($extOffset !== false) { $extension = substr($path, strrpos($path, '.')); } $tmpFile = OC_Helper::tmpFile($extension); file_put_contents($tmpFile, $source); return $tmpFile; } } }
/** * @param array $data * @return array * @throws Exception */ public static function downloadApp($data = array()) { $l = \OC::$server->getL10N('lib'); if (!isset($data['source'])) { throw new \Exception($l->t("No source specified when installing app")); } //download the file if necessary if ($data['source'] == 'http') { $pathInfo = pathinfo($data['href']); $path = OC_Helper::tmpFile('.' . $pathInfo['extension']); if (!isset($data['href'])) { throw new \Exception($l->t("No href specified when installing app from http")); } copy($data['href'], $path); } else { if (!isset($data['path'])) { throw new \Exception($l->t("No path specified when installing app from local file")); } $path = $data['path']; } //detect the archive type $mime = OC_Helper::getMimeType($path); if ($mime !== 'application/zip' && $mime !== 'application/x-gzip') { throw new \Exception($l->t("Archives of type %s are not supported", array($mime))); } //extract the archive in a temporary folder $extractDir = OC_Helper::tmpFolder(); OC_Helper::rmdirr($extractDir); mkdir($extractDir); if ($archive = OC_Archive::open($path)) { $archive->extract($extractDir); } else { OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } throw new \Exception($l->t("Failed to open archive when installing app")); } return array($extractDir, $path); }
/** * @param string $path * @return bool|string * @throws \OCP\Files\InvalidPathException */ public function toTmpFile($path) { $this->assertPathLength($path); if (Filesystem::isValidPath($path)) { $source = $this->fopen($path, 'r'); if ($source) { $extension = pathinfo($path, PATHINFO_EXTENSION); $tmpFile = \OC_Helper::tmpFile($extension); file_put_contents($tmpFile, $source); return $tmpFile; } else { return false; } } else { return false; } }
public function testHooks() { if (\OC\Files\Filesystem::getView()) { $user = \OC_User::getUser(); } else { $user = $this->getUniqueID(); \OC\Files\Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); \OC\Files\Filesystem::mount('OC\\Files\\Storage\\Temporary', array(), '/'); $rootView = new \OC\Files\View(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); \OC\Files\Filesystem::mkdir('/bar'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo'); $tmpFile = \OC_Helper::tmpFile(); file_put_contents($tmpFile, 'foo'); $fh = fopen($tmpFile, 'r'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh); }
/** * get the mimetype form a data string * @param string data * @return string */ static function getStringMimeType($data) { if (function_exists('finfo_open') and function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); return finfo_buffer($finfo, $data); } else { $tmpFile = OC_Helper::tmpFile(); $fh = fopen($tmpFile, 'wb'); fwrite($fh, $data, 8024); fclose($fh); $mime = self::getMimeType($tmpFile); unset($tmpFile); return $mime; } }
public function fopen($path, $mode) { $pos = strrpos($path, '.'); if ($pos !== false) { $ext = substr($path, $pos); } else { $ext = ''; } switch ($mode) { case 'r': case 'rb': $file = $this->getDriveFile($path); if ($file) { $exportLinks = $file->getExportLinks(); $mimetype = $this->getMimeType($path); $downloadUrl = null; if ($exportLinks && isset($exportLinks[$mimetype])) { $downloadUrl = $exportLinks[$mimetype]; } else { $downloadUrl = $file->getDownloadUrl(); } if (isset($downloadUrl)) { $request = new \Google_HttpRequest($downloadUrl, 'GET', null, null); $httpRequest = \Google_Client::$io->authenticatedRequest($request); if ($httpRequest->getResponseHttpCode() == 200) { $tmpFile = \OC_Helper::tmpFile($ext); $data = $httpRequest->getResponseBody(); file_put_contents($tmpFile, $data); return fopen($tmpFile, $mode); } } } return false; case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': $tmpFile = \OC_Helper::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $source = $this->fopen($path, 'rb'); file_put_contents($tmpFile, $source); } self::$tempFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } }
public function fopen($path, $mode) { switch ($mode) { case 'r': case 'rb': if ($entry = $this->getResource($path)) { $extension = $this->getExtension($entry); $downloadUri = $entry->getElementsByTagName('content')->item(0)->getAttribute('src'); // TODO Non-native documents don't need these additional parameters $downloadUri .= '&exportFormat=' . $extension . '&format=' . $extension; $tmpFile = $this->sendRequest($downloadUri, 'GET', null, null, true); return fopen($tmpFile, 'r'); } case 'w': case 'wb': case 'a': case 'ab': case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': if (strrpos($path, '.') !== false) { $ext = substr($path, strrpos($path, '.')); } else { $ext = ''; } $tmpFile = OC_Helper::tmpFile($ext); OC_CloseStreamWrapper::$callBacks[$tmpFile] = array($this, 'writeBack'); if ($this->file_exists($path)) { $source = $this->fopen($path, 'r'); file_put_contents($tmpFile, $source); } self::$tempFiles[$tmpFile] = $path; return fopen('close://' . $tmpFile, $mode); } return false; }
/** * @brief Installs an app * @param $data array with all information * @throws \Exception * @returns integer * * This function installs an app. All information needed are passed in the * associative array $data. * The following keys are required: * - source: string, can be "path" or "http" * * One of the following keys is required: * - path: path to the file containing the app * - href: link to the downloadable file containing the app * * The following keys are optional: * - pretend: boolean, if set true the system won't do anything * - noinstall: boolean, if true appinfo/install.php won't be loaded * - inactive: boolean, if set true the appconfig/app.sample.php won't be * renamed * * This function works as follows * -# fetching the file * -# unzipping it * -# check the code * -# installing the database at appinfo/database.xml * -# including appinfo/install.php * -# setting the installed version * * It is the task of oc_app_install to create the tables and do whatever is * needed to get the app working. */ public static function installApp($data = array()) { $l = \OC_L10N::get('lib'); if (!isset($data['source'])) { throw new \Exception($l->t("No source specified when installing app")); } //download the file if necessary if ($data['source'] == 'http') { $pathInfo = pathinfo($data['href']); $path = OC_Helper::tmpFile('.' . $pathInfo['extension']); if (!isset($data['href'])) { throw new \Exception($l->t("No href specified when installing app from http")); } copy($data['href'], $path); } else { if (!isset($data['path'])) { throw new \Exception($l->t("No path specified when installing app from local file")); } $path = $data['path']; } //detect the archive type $mime = OC_Helper::getMimeType($path); if ($mime !== 'application/zip' && $mime !== 'application/x-gzip') { throw new \Exception($l->t("Archives of type %s are not supported", array($mime))); } //extract the archive in a temporary folder $extractDir = OC_Helper::tmpFolder(); OC_Helper::rmdirr($extractDir); mkdir($extractDir); if ($archive = OC_Archive::open($path)) { $archive->extract($extractDir); } else { OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } throw new \Exception($l->t("Failed to open archive when installing app")); } //load the info.xml file of the app if (!is_file($extractDir . '/appinfo/info.xml')) { //try to find it in a subdir $dh = opendir($extractDir); if (is_resource($dh)) { while (($folder = readdir($dh)) !== false) { if ($folder[0] != '.' and is_dir($extractDir . '/' . $folder)) { if (is_file($extractDir . '/' . $folder . '/appinfo/info.xml')) { $extractDir .= '/' . $folder; } } } } } if (!is_file($extractDir . '/appinfo/info.xml')) { OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } throw new \Exception($l->t("App does not provide an info.xml file")); } $info = OC_App::getAppInfo($extractDir . '/appinfo/info.xml', true); // check the code for not allowed calls if (!OC_Installer::checkCode($info['id'], $extractDir)) { OC_Helper::rmdirr($extractDir); throw new \Exception($l->t("App can't be installed because of not allowed code in the App")); } // check if the app is compatible with this version of ownCloud if (!isset($info['require']) or !OC_App::isAppVersionCompatible(OC_Util::getVersion(), $info['require'])) { OC_Helper::rmdirr($extractDir); throw new \Exception($l->t("App can't be installed because it is not compatible with this version of ownCloud")); } // check if shipped tag is set which is only allowed for apps that are shipped with ownCloud if (isset($info['shipped']) and $info['shipped'] == 'true') { OC_Helper::rmdirr($extractDir); throw new \Exception($l->t("App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps")); } // check if the ocs version is the same as the version in info.xml/version $versionFile = $extractDir . '/appinfo/version'; if (is_file($versionFile)) { $version = trim(file_get_contents($versionFile)); } else { $version = trim($info['version']); } if ($version != trim($data['appdata']['version'])) { OC_Helper::rmdirr($extractDir); throw new \Exception($l->t("App can't be installed because the version in info.xml/version is not the same as the version reported from the app store")); } $basedir = OC_App::getInstallPath() . '/' . $info['id']; //check if the destination directory already exists if (is_dir($basedir)) { OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } throw new \Exception($l->t("App directory already exists")); } if (isset($data['pretent']) and $data['pretent'] == true) { return false; } //copy the app to the correct place if (@(!mkdir($basedir))) { OC_Helper::rmdirr($extractDir); if ($data['source'] == 'http') { unlink($path); } throw new \Exception($l->t("Can't create app folder. Please fix permissions. %s", array($basedir))); } OC_Helper::copyr($extractDir, $basedir); //remove temporary files OC_Helper::rmdirr($extractDir); //install the database if (is_file($basedir . '/appinfo/database.xml')) { if (OC_Appconfig::getValue($info['id'], 'installed_version') === null) { OC_DB::createDbFromStructure($basedir . '/appinfo/database.xml'); } else { OC_DB::updateDbFromStructure($basedir . '/appinfo/database.xml'); } } //run appinfo/install.php if ((!isset($data['noinstall']) or $data['noinstall'] == false) and file_exists($basedir . '/appinfo/install.php')) { include $basedir . '/appinfo/install.php'; } //set the installed version OC_Appconfig::setValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'])); OC_Appconfig::setValue($info['id'], 'enabled', 'no'); //set remote/public handelers foreach ($info['remote'] as $name => $path) { OCP\CONFIG::setAppValue('core', 'remote_' . $name, $info['id'] . '/' . $path); } foreach ($info['public'] as $name => $path) { OCP\CONFIG::setAppValue('core', 'public_' . $name, $info['id'] . '/' . $path); } OC_App::setAppTypes($info['id']); return $info['id']; }