Example #1
2
 public function __construct($imagePath, $user = null, $square = false)
 {
     if (!Filesystem::isValidPath($imagePath)) {
         return;
     }
     if (is_null($user)) {
         $this->view = Filesystem::getView();
         $this->user = \OCP\User::getUser();
     } else {
         $this->view = new View('/' . $user . '/files');
         $this->user = $user;
     }
     $this->useOriginal = (substr($imagePath, -4) === '.svg' or substr($imagePath, -5) === '.svgz');
     if ($this->useOriginal) {
         $this->path = $imagePath;
     } else {
         $galleryDir = \OC_User::getHome($this->user) . '/gallery/' . $this->user . '/';
         if (strrpos($imagePath, '.')) {
             $extension = substr($imagePath, strrpos($imagePath, '.') + 1);
             $image = substr($imagePath, 0, strrpos($imagePath, '.'));
         } else {
             $extension = '';
             $image = $imagePath;
         }
         if ($square) {
             $extension = 'square.' . $extension;
         }
         $this->path = $galleryDir . $image . '.' . $extension;
         if (!file_exists($this->path)) {
             $this->create($imagePath, $square);
         }
     }
 }
Example #2
2
 /**
  * get metadata info for a media file
  *
  * @param $path
  * @return array
  */
 public function extract($path)
 {
     if (ini_get('allow_url_fopen')) {
         $file = \OC\Files\Filesystem::getView()->getAbsolutePath($path);
         $data = @$this->getID3->analyze('oc://' . $file);
     } else {
         // Fallback to the local FS
         $file = \OC\Files\Filesystem::getLocalFile($path);
     }
     \getid3_lib::CopyTagsToComments($data);
     return $data;
 }
Example #3
0
 public static function determineIcon($file)
 {
     if ($file['type'] === 'dir') {
         $dir = $file['directory'];
         $absPath = \OC\Files\Filesystem::getView()->getAbsolutePath($dir . '/' . $file['name']);
         $mount = \OC\Files\Filesystem::getMountManager()->find($absPath);
         if (!is_null($mount)) {
             $sid = $mount->getStorageId();
             if (!is_null($sid)) {
                 $sid = explode(':', $sid);
                 if ($sid[0] === 'shared') {
                     return \OC_Helper::mimetypeIcon('dir-shared');
                 }
                 if ($sid[0] !== 'local' and $sid[0] !== 'home') {
                     return \OC_Helper::mimetypeIcon('dir-external');
                 }
             }
         }
         return \OC_Helper::mimetypeIcon('dir');
     }
     if ($file['isPreviewAvailable']) {
         $pathForPreview = $file['directory'] . '/' . $file['name'];
         return \OC_Helper::previewIcon($pathForPreview) . '&c=' . $file['etag'];
     }
     return \OC_Helper::mimetypeIcon($file['mimetype']);
 }
Example #4
0
 /**
  * Deletes the given file by moving it into the trashbin.
  *
  * @param string $path
  */
 public function unlink($path)
 {
     if (self::$disableTrash) {
         return $this->storage->unlink($path);
     }
     $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
     $result = true;
     if (!isset($this->deletedFiles[$normalized])) {
         $view = Filesystem::getView();
         $this->deletedFiles[$normalized] = $normalized;
         if ($filesPath = $view->getRelativePath($normalized)) {
             $filesPath = trim($filesPath, '/');
             $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath);
             // in cross-storage cases the file will be copied
             // but not deleted, so we delete it here
             if ($result) {
                 $this->storage->unlink($path);
             }
         } else {
             $result = $this->storage->unlink($path);
         }
         unset($this->deletedFiles[$normalized]);
     } else {
         if ($this->storage->file_exists($path)) {
             $result = $this->storage->unlink($path);
         }
     }
     return $result;
 }
Example #5
0
 public function generateFileToken($fileId, $version)
 {
     // Get the FS view of the current user.
     $view = \OC\Files\Filesystem::getView();
     // Get the virtual path (if the file is shared).
     $path = $view->getPath($fileId);
     if (!$view->is_file($path) || !$view->isUpdatable($path)) {
         throw new \Exception('Invalid fileId.');
     }
     // Figure out the real owner, if not us.
     $owner = $view->getOwner($path);
     // Create a view into the owner's FS.
     $view = new \OC\Files\View('/' . $owner . '/files');
     // Find the real path.
     $path = $view->getPath($fileId);
     if (!$view->is_file($path)) {
         throw new \Exception('Invalid fileId.');
     }
     $editor = \OC::$server->getUserSession()->getUser()->getUID();
     $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
     \OC::$server->getLogger()->debug('Issuing token for {editor} file {fileId}, version {version} owned by {owner}, path {path}: {token}', ['owner' => $owner, 'editor' => $editor, 'fileId' => $fileId, 'version' => $version, 'path' => $path, 'token' => $token]);
     $wopi = new \OCA\Richdocuments\Db\Wopi([$owner, $editor, $fileId, $version, $path, $token, time() + self::TOKEN_LIFETIME_SECONDS]);
     if (!$wopi->insert()) {
         throw new \Exception('Failed to add wopi token into database');
     }
     return $token;
 }
 /**
  * @param $parentUri
  * @return mixed
  */
 public function getFreeSpace($parentUri)
 {
     if (is_null($this->fileView)) {
         // initialize fileView
         $this->fileView = \OC\Files\Filesystem::getView();
     }
     $freeSpace = $this->fileView->free_space($parentUri);
     return $freeSpace;
 }
Example #7
0
 /**
  * get all storages for $dir
  *
  * @param string $dir
  * @return \OC\Files\Mount\MountPoint[]
  */
 protected function getMounts($dir)
 {
     //TODO: move to the node based fileapi once that's done
     \OC_Util::tearDownFS();
     \OC_Util::setupFS($this->user);
     $absolutePath = Filesystem::getView()->getAbsolutePath($dir);
     $mountManager = Filesystem::getMountManager();
     $mounts = $mountManager->findIn($absolutePath);
     $mounts[] = $mountManager->find($absolutePath);
     $mounts = array_reverse($mounts);
     //start with the mount of $dir
     return $mounts;
 }
Example #8
0
 /**
  * @return Directory
  */
 private function impl()
 {
     //
     // TODO: we need to mount filesystem of the give user
     //
     $user = \OC::$server->getUserSession()->getUser();
     if ($this->getName() !== $user->getUID()) {
         return new SimpleCollection($this->getName());
     }
     $view = \OC\Files\Filesystem::getView();
     $rootInfo = $view->getFileInfo('');
     $impl = new Directory($view, $rootInfo);
     return $impl;
 }
Example #9
0
 public static function unshareChildren($params)
 {
     $path = Filesystem::getView()->getAbsolutePath($params['path']);
     $view = new \OC\Files\View('/');
     // find share mount points within $path and unmount them
     $mountManager = \OC\Files\Filesystem::getMountManager();
     $mountedShares = $mountManager->findIn($path);
     foreach ($mountedShares as $mount) {
         if ($mount->getStorage()->instanceOfStorage('OCA\\Files_Sharing\\ISharedStorage')) {
             $mountPoint = $mount->getMountPoint();
             $view->unlink($mountPoint);
         }
     }
 }
Example #10
0
 public static function deleteHook($arguments)
 {
     // save delete file info
     $view = \OC\Files\Filesystem::getView();
     if (!is_null($view)) {
         $path = $arguments['path'];
         $info = $view->getFileInfo($path);
         if ($info) {
             self::$deleteFileInfo[$path] = $info;
         }
     }
     // save storage information
     self::$preStorageInfo = \OC_Helper::getStorageInfo('/');
 }
 public static function rename($args)
 {
     self::preDispatch();
     $fileId = intval(Helper::getArrayValueByKey($args, 'file_id', 0));
     $name = Helper::getArrayValueByKey($_POST, 'name');
     $view = \OC\Files\Filesystem::getView();
     $path = $view->getPath($fileId);
     if (isset($name) && $view->is_file($path) && $view->isUpdatable($path)) {
         $newPath = dirname($path) . '/' . $name;
         if ($view->rename($path, $newPath)) {
             \OCP\JSON::success();
             return;
         }
     }
     \OCP\JSON::error(array('message' => Config::getL10n()->t('You don\'t have permission to rename this document')));
 }
Example #12
0
 public function __construct($imagePath, $user = null, $square = false)
 {
     if (!Filesystem::isValidPath($imagePath)) {
         return;
     }
     if (is_null($user)) {
         $this->view = Filesystem::getView();
         $this->user = \OCP\USER::getUser();
     } else {
         $this->view = new View('/' . $user . '/files');
         $this->user = $user;
     }
     $galleryDir = \OC_User::getHome($this->user) . '/gallery/' . $this->user . '/';
     $this->path = $galleryDir . $imagePath . '.png';
     if (!file_exists($this->path)) {
         self::create($imagePath, $square);
     }
 }
Example #13
0
 /**
  * @param array $barriers of given quota barriers which are to be used to fire a quota change
  */
 public function __construct($barriers = null, $view = null)
 {
     if (is_null($barriers)) {
         $barriers = \OC_Config::getValue('webhook_barriers', array());
     }
     if (!is_array($barriers)) {
         \OC_Log::write('webhooks', "Invalid barriers given: {$barriers}", \OC_Log::ERROR);
         $barriers = array();
     }
     sort($barriers);
     $this->barriers = $barriers;
     $this->notifications = new Notifications();
     $this->subscriptions = new Subscriptions();
     if (is_null($view)) {
         $view = \OC\Files\Filesystem::getView();
     }
     $this->view = $view;
 }
Example #14
0
 public static function av_scan($path)
 {
     $path = $path[\OC\Files\Filesystem::signal_param_path];
     if ($path != '') {
         if (isset($_POST['dirToken'])) {
             //Public upload case
             $filesView = \OC\Files\Filesystem::getView();
         } else {
             $filesView = \OCP\Files::getStorage("files");
         }
         if (!is_object($filesView)) {
             \OCP\Util::writeLog('files_antivirus', 'Can\'t init filesystem view', \OCP\Util::WARN);
             return;
         }
         // check if path is a directory
         if ($filesView->is_dir($path)) {
             return;
         }
         // we should have a file to work with, and the file shouldn't
         // be empty
         $fileExists = $filesView->file_exists($path);
         if ($fileExists && $filesView->filesize($path) > 0) {
             $fileStatus = self::scanFile($filesView, $path);
             $result = $fileStatus->getNumericStatus();
             switch ($result) {
                 case Status::SCANRESULT_UNCHECKED:
                     //TODO: Show warning to the user: The file can not be checked
                     break;
                 case Status::SCANRESULT_INFECTED:
                     //remove file
                     $filesView->unlink($path);
                     Notification::sendMail($path);
                     $message = \OCP\Util::getL10N('files_antivirus')->t("Virus detected! Can't upload the file %s", array(basename($path)));
                     \OCP\JSON::error(array("data" => array("message" => $message)));
                     exit;
                     break;
                 case Status::SCANRESULT_CLEAN:
                     //do nothing
                     break;
             }
         }
     }
 }
Example #15
0
 /**
  * @NoAdminRequired
  */
 public function joinAsUser($fileId)
 {
     try {
         $view = \OC\Files\Filesystem::getView();
         $path = $view->getPath($fileId);
         if ($view->isUpdatable($path)) {
             $file = new File($fileId);
             $response = Db\Session::start($this->uid, $file);
         } else {
             $info = $view->getFileInfo($path);
             $response = array('permissions' => $info['permissions'], 'id' => $fileId);
         }
         $response = array_merge($response, array('status' => 'success'));
     } catch (\Exception $e) {
         $this->logger->warning('Starting a session failed. Reason: ' . $e->getMessage(), array('app' => $this->appName));
         $response = array('status' => 'error');
     }
     return $response;
 }
 public static function joinAsUser($args)
 {
     $uid = self::preDispatch();
     $fileId = Helper::getArrayValueByKey($args, 'file_id');
     try {
         $view = \OC\Files\Filesystem::getView();
         $path = $view->getPath($fileId);
         if ($view->isUpdatable($path)) {
             $file = new File($fileId);
             $session = Db\Session::start($uid, $file);
             \OCP\JSON::success($session);
         } else {
             $info = $view->getFileInfo($path);
             \OCP\JSON::success(array('permissions' => $info['permissions'], 'id' => $fileId));
         }
         exit;
     } catch (\Exception $e) {
         Helper::warnLog('Starting a session failed. Reason: ' . $e->getMessage());
         \OCP\JSON::error();
         exit;
     }
 }
Example #17
0
 /**
  * Run all commands pushed to the bus
  */
 protected function runCommands()
 {
     // get the user for which the fs is setup
     $view = Filesystem::getView();
     if ($view) {
         list(, $user) = explode('/', $view->getRoot());
     } else {
         $user = null;
     }
     \OC_Util::tearDownFS();
     // command cant reply on the fs being setup
     $this->commandBus->run();
     \OC_Util::tearDownFS();
     if ($user) {
         \OC_Util::setupFS($user);
     }
 }
Example #18
0
	private function emitPostHooks($exists, $path = null) {
		if (is_null($path)) {
			$path = $this->path;
		}
		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
		if (!$exists) {
			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
				\OC\Files\Filesystem::signal_param_path => $hookPath
			));
		} else {
			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
				\OC\Files\Filesystem::signal_param_path => $hookPath
			));
		}
		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
			\OC\Files\Filesystem::signal_param_path => $hookPath
		));
	}
Example #19
0
 /**
  * return the content of a file or return a zip file containing multiple files
  *
  * @param string $dir
  * @param string $files ; 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)
 {
     $view = \OC\Files\Filesystem::getView();
     $xsendfile = false;
     if (\OC::$server->getLockingProvider() instanceof NoopLockingProvider) {
         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)) {
         $get_type = self::ZIP_FILES;
         $basename = basename($dir);
         if ($basename) {
             $name = $basename . '.zip';
         } else {
             $name = 'download.zip';
         }
         $filename = $dir . '/' . $name;
     } else {
         $filename = $dir . '/' . $files;
         if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) {
             $get_type = self::ZIP_DIR;
             // downloading root ?
             if ($files === '') {
                 $name = 'download.zip';
             } else {
                 $name = $files . '.zip';
             }
         } else {
             $get_type = self::FILE;
             $name = $files;
         }
     }
     if ($get_type === self::FILE) {
         $zip = false;
         if ($xsendfile && \OC::$server->getEncryptionManager()->isEnabled()) {
             $xsendfile = false;
         }
     } else {
         $zip = new ZipStreamer(false);
     }
     OC_Util::obEnd();
     try {
         if ($get_type === self::FILE) {
             $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
         }
         if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
             self::sendHeaders($filename, $name, $zip);
         } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
             header("HTTP/1.0 404 Not Found");
             $tmpl = new OC_Template('', '404', 'guest');
             $tmpl->printPage();
             exit;
         } else {
             header("HTTP/1.0 403 Forbidden");
             die('403 Forbidden');
         }
         if ($only_header) {
             return;
         }
         if ($zip) {
             $executionTime = intval(ini_get('max_execution_time'));
             set_time_limit(0);
             if ($get_type === self::ZIP_FILES) {
                 foreach ($files as $file) {
                     $file = $dir . '/' . $file;
                     if (\OC\Files\Filesystem::is_file($file)) {
                         $fh = \OC\Files\Filesystem::fopen($file, 'r');
                         $zip->addFileFromStream($fh, basename($file));
                         fclose($fh);
                     } elseif (\OC\Files\Filesystem::is_dir($file)) {
                         self::zipAddDir($file, $zip);
                     }
                 }
             } elseif ($get_type === self::ZIP_DIR) {
                 $file = $dir . '/' . $files;
                 self::zipAddDir($file, $zip);
             }
             $zip->finalize();
             set_time_limit($executionTime);
         } else {
             if ($xsendfile) {
                 /** @var $storage \OC\Files\Storage\Storage */
                 list($storage) = $view->resolvePath($filename);
                 if ($storage->isLocal()) {
                     self::addSendfileHeader($filename);
                 } else {
                     \OC\Files\Filesystem::readfile($filename);
                 }
             } else {
                 \OC\Files\Filesystem::readfile($filename);
             }
         }
         if ($get_type === self::FILE) {
             $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
         }
     } catch (\OCP\Lock\LockedException $ex) {
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
     } catch (\Exception $ex) {
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
     }
 }
Example #20
0
 /**
  * get default share folder
  *
  * @param \OC\Files\View
  * @return string
  */
 public static function getShareFolder($view = null)
 {
     if ($view === null) {
         $view = Filesystem::getView();
     }
     $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
     $shareFolder = Filesystem::normalizePath($shareFolder);
     if (!$view->file_exists($shareFolder)) {
         $dir = '';
         $subdirs = explode('/', $shareFolder);
         foreach ($subdirs as $subdir) {
             $dir = $dir . '/' . $subdir;
             if (!$view->is_dir($dir)) {
                 $view->mkdir($dir);
             }
         }
     }
     return $shareFolder;
 }
Example #21
0
 /**
  * Adds a suffix to the name in case the file exists
  *
  * @param string $path
  * @param string $filename
  * @return string
  */
 public static function buildNotExistingFileName($path, $filename)
 {
     $view = \OC\Files\Filesystem::getView();
     return self::buildNotExistingFileNameForView($path, $filename, $view);
 }
Example #22
0
 /**
  * get the path relative to the default root for hook usage
  *
  * @param string $path
  * @return string
  */
 private function getHookPath($path)
 {
     if (!Filesystem::getView()) {
         return $path;
     }
     return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
 }
Example #23
0
 *
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
// no php execution timeout for webdav
set_time_limit(0);
// Turn off output buffering to prevent memory problems
\OC_Util::obEnd();
$serverFactory = new \OCA\DAV\Connector\Sabre\ServerFactory(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), \OC::$server->getUserSession(), \OC::$server->getMountManager(), \OC::$server->getTagManager(), \OC::$server->getRequest());
// Backends
$authBackend = new \OCA\DAV\Connector\Sabre\Auth(\OC::$server->getSession(), \OC::$server->getUserSession(), \OC::$server->getRequest(), 'principals/');
$requestUri = \OC::$server->getRequest()->getRequestUri();
$server = $serverFactory->createServer($baseuri, $requestUri, $authBackend, function () {
    // use the view for the logged in user
    return \OC\Files\Filesystem::getView();
});
// And off we go!
$server->exec();
Example #24
0
 /**
  * return the content of a file or return a zip file containing multiple files
  *
  * @param string $dir
  * @param string $files ; 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)) {
         $get_type = GET_TYPE::ZIP_FILES;
         $basename = basename($dir);
         if ($basename) {
             $name = $basename . '.zip';
         } else {
             $name = 'download.zip';
         }
         $filename = $dir . '/' . $name;
     } else {
         $filename = $dir . '/' . $files;
         if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) {
             $get_type = GET_TYPE::ZIP_DIR;
             // downloading root ?
             if ($files === '') {
                 $name = 'download.zip';
             } else {
                 $name = $files . '.zip';
             }
         } else {
             $get_type = GET_TYPE::FILE;
             $name = $files;
         }
     }
     if ($get_type === GET_TYPE::FILE) {
         $zip = false;
         if ($xsendfile && OC_App::isEnabled('files_encryption')) {
             $xsendfile = false;
         }
     } else {
         $zip = new ZipStreamer(false);
     }
     OC_Util::obEnd();
     if ($zip or \OC\Files\Filesystem::isReadable($filename)) {
         self::sendHeaders($filename, $name, $zip);
     } elseif (!\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) {
         $executionTime = intval(ini_get('max_execution_time'));
         set_time_limit(0);
         if ($get_type === GET_TYPE::ZIP_FILES) {
             foreach ($files as $file) {
                 $file = $dir . '/' . $file;
                 if (\OC\Files\Filesystem::is_file($file)) {
                     $fh = \OC\Files\Filesystem::fopen($file, 'r');
                     $zip->addFileFromStream($fh, basename($file));
                     fclose($fh);
                 } elseif (\OC\Files\Filesystem::is_dir($file)) {
                     self::zipAddDir($file, $zip);
                 }
             }
         } elseif ($get_type === GET_TYPE::ZIP_DIR) {
             $file = $dir . '/' . $files;
             self::zipAddDir($file, $zip);
         }
         $zip->finalize();
         set_time_limit($executionTime);
     } else {
         if ($xsendfile) {
             $view = \OC\Files\Filesystem::getView();
             /** @var $storage \OC\Files\Storage\Storage */
             list($storage) = $view->resolvePath($filename);
             if ($storage->isLocal()) {
                 self::addSendfileHeader($filename);
             } else {
                 \OC\Files\Filesystem::readfile($filename);
             }
         } else {
             \OC\Files\Filesystem::readfile($filename);
         }
     }
 }
Example #25
0
 private static function setAttributes($user_id, $saml_display_name, $saml_email, $saml_groups, $saml_quota)
 {
     /*$secure_cookie = \OC_Config::getValue("forcessl", false);
     		$expires = time() + \OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
     		setcookie("oc_display_name", $saml_display_name, $expires, \OC::$WEBROOT, '', $secure_cookie);
     		setcookie("oc_mail", $saml_email, $expires, \OC::$WEBROOT, '', $secure_cookie);
     		setcookie("oc_quota", $saml_quota, $expires, \OC::$WEBROOT, '', $secure_cookie);
     		setcookie("oc_groups", json_encode($saml_groups), $expires, \OC::$WEBROOT, '', $secure_cookie);*/
     self::setRedirectCookie();
     $_SESSION["oc_display_name"] = $saml_display_name;
     $_SESSION["oc_mail"] = $saml_email;
     $_SESSION["oc_groups"] = $saml_groups;
     $_SESSION["oc_quota"] = $saml_quota;
     if (OCP\App::isEnabled('files_sharding') && OCA\FilesSharding\Lib::isMaster()) {
         //\OC_Util::setupFS();
         // Let slaves know which folders are data folders
         $dataFolders = OCA\FilesSharding\Lib::dbGetDataFoldersList($user_id);
         $_SESSION["oc_data_folders"] = $dataFolders;
         // Have slaves use the same numeric ID for "storages".
         $view = \OC\Files\Filesystem::getView();
         $rootInfo = $view->getFileInfo('');
         $storageId = $rootInfo->getStorage()->getId();
         $numericStorageId = OC\Files\Cache\Storage::getNumericStorageId($storageId);
         $_SESSION["oc_storage_id"] = $storageId;
         $_SESSION["oc_numeric_storage_id"] = $numericStorageId;
     }
 }
Example #26
0
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
// Init owncloud
global $eventSource;
\OCP\JSON::checkLoggedIn();
\OCP\JSON::callCheck();
\OC::$server->getSession()->close();
// Get the params
$dir = isset($_REQUEST['dir']) ? '/' . trim((string) $_REQUEST['dir'], '/\\') : '';
$fileName = isset($_REQUEST['filename']) ? trim((string) $_REQUEST['filename'], '/\\') : '';
$l10n = \OC::$server->getL10N('files');
$result = array('success' => false, 'data' => NULL);
try {
    \OC\Files\Filesystem::getView()->verifyPath($dir, $fileName);
} catch (\OCP\Files\InvalidPathException $ex) {
    $result['data'] = ['message' => $ex->getMessage()];
    OCP\JSON::error($result);
    return;
}
if (!\OC\Files\Filesystem::file_exists($dir . '/')) {
    $result['data'] = array('message' => (string) $l10n->t('The target folder has been moved or deleted.'), 'code' => 'targetnotfound');
    OCP\JSON::error($result);
    exit;
}
$target = $dir . '/' . $fileName;
if (\OC\Files\Filesystem::file_exists($target)) {
    $result['data'] = array('message' => (string) $l10n->t('The name %s is already used in the folder %s. Please choose a different name.', array($fileName, $dir)));
    OCP\JSON::error($result);
    exit;
 public function file_assemble($path)
 {
     $absolutePath = \OC\Files\Filesystem::normalizePath(\OC\Files\Filesystem::getView()->getAbsolutePath($path));
     $data = '';
     // use file_put_contents as method because that best matches what this function does
     if (OC_FileProxy::runPreProxies('file_put_contents', $absolutePath, $data) && \OC\Files\Filesystem::isValidPath($path)) {
         $path = \OC\Files\Filesystem::getView()->getRelativePath($absolutePath);
         $exists = \OC\Files\Filesystem::file_exists($path);
         $run = true;
         if (!$exists) {
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         }
         OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(\OC\Files\Filesystem::signal_param_path => $path, \OC\Files\Filesystem::signal_param_run => &$run));
         if (!$run) {
             return false;
         }
         $target = \OC\Files\Filesystem::fopen($path, 'w');
         if ($target) {
             $count = $this->assemble($target);
             fclose($target);
             if (!$exists) {
                 OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(\OC\Files\Filesystem::signal_param_path => $path));
             }
             OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(\OC\Files\Filesystem::signal_param_path => $path));
             OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count);
             return $count > 0;
         } else {
             return false;
         }
     }
 }
Example #28
0
 /**
  * Test whether versions are created when overwriting as share recipient
  */
 public function testStoreVersionAsRecipient()
 {
     $this->loginAsUser(self::TEST_VERSIONS_USER);
     \OC\Files\Filesystem::mkdir('folder');
     \OC\Files\Filesystem::file_put_contents('folder/test.txt', 'test file');
     $fileInfo = \OC\Files\Filesystem::getFileInfo('folder');
     \OCP\Share::shareItem('folder', $fileInfo['fileid'], \OCP\Share::SHARE_TYPE_USER, self::TEST_VERSIONS_USER2, \OCP\Constants::PERMISSION_ALL);
     $this->loginAsUser(self::TEST_VERSIONS_USER2);
     $this->createAndCheckVersions(\OC\Files\Filesystem::getView(), 'folder/test.txt');
 }
Example #29
0
 /**
  * Updates the data
  *
  * The data argument is a readable stream resource.
  *
  * After a successful put operation, you may choose to return an ETag. The
  * etag must always be surrounded by double-quotes. These quotes must
  * appear in the actual string you're returning.
  *
  * Clients may use the ETag from a PUT request to later on make sure that
  * when they update the file, the contents haven't changed in the mean
  * time.
  *
  * If you don't plan to store the file byte-by-byte, and you return a
  * different object on a subsequent GET you are strongly recommended to not
  * return an ETag, and just return null.
  *
  * @param resource $data
  *
  * @throws Forbidden
  * @throws UnsupportedMediaType
  * @throws BadRequest
  * @throws Exception
  * @throws EntityTooLarge
  * @throws ServiceUnavailable
  * @throws FileLocked
  * @return string|null
  */
 public function put($data)
 {
     try {
         $exists = $this->fileView->file_exists($this->path);
         if ($this->info && $exists && !$this->info->isUpdateable()) {
             throw new Forbidden();
         }
     } catch (StorageNotAvailableException $e) {
         throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
     }
     // verify path of the target
     $this->verifyPath();
     // chunked handling
     if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
         try {
             return $this->createFileChunked($data);
         } catch (\Exception $e) {
             $this->convertToSabreException($e);
         }
     }
     list($partStorage) = $this->fileView->resolvePath($this->path);
     $needsPartFile = $this->needsPartFile($partStorage) && strlen($this->path) > 1;
     if ($needsPartFile) {
         // mark file as partial while uploading (ignored by the scanner)
         $partFilePath = $this->path . '.ocTransferId' . rand() . '.part';
     } else {
         // upload file directly as the final path
         $partFilePath = $this->path;
     }
     try {
         $this->fileView->lockFile($this->path, ILockingProvider::LOCK_SHARED);
     } catch (LockedException $e) {
         throw new FileLocked($e->getMessage(), $e->getCode(), $e);
     }
     // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
     /** @var \OC\Files\Storage\Storage $partStorage */
     list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
     /** @var \OC\Files\Storage\Storage $storage */
     list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
     try {
         $target = $partStorage->fopen($internalPartPath, 'wb');
         if ($target === false) {
             \OC_Log::write('webdav', '\\OC\\Files\\Filesystem::fopen() failed', \OC_Log::ERROR);
             // because we have no clue about the cause we can only throw back a 500/Internal Server Error
             throw new Exception('Could not write file contents');
         }
         list($count, ) = \OC_Helper::streamCopy($data, $target);
         fclose($target);
         // if content length is sent by client:
         // double check if the file was fully received
         // compare expected and actual size
         if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
             $expected = $_SERVER['CONTENT_LENGTH'];
             if ($count != $expected) {
                 throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
             }
         }
     } catch (\Exception $e) {
         $partStorage->unlink($internalPartPath);
         $this->convertToSabreException($e);
     }
     try {
         $view = \OC\Files\Filesystem::getView();
         $run = true;
         if ($view) {
             $hookPath = $view->getRelativePath($this->fileView->getAbsolutePath($this->path));
             if (!$exists) {
                 \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(\OC\Files\Filesystem::signal_param_path => $hookPath, \OC\Files\Filesystem::signal_param_run => &$run));
             } else {
                 \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(\OC\Files\Filesystem::signal_param_path => $hookPath, \OC\Files\Filesystem::signal_param_run => &$run));
             }
             \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(\OC\Files\Filesystem::signal_param_path => $hookPath, \OC\Files\Filesystem::signal_param_run => &$run));
         }
         try {
             $this->fileView->changeLock($this->path, ILockingProvider::LOCK_EXCLUSIVE);
         } catch (LockedException $e) {
             $partStorage->unlink($internalPartPath);
             throw new FileLocked($e->getMessage(), $e->getCode(), $e);
         }
         if ($needsPartFile) {
             // rename to correct path
             try {
                 if ($run) {
                     $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
                     $fileExists = $storage->file_exists($internalPath);
                 }
                 if (!$run || $renameOkay === false || $fileExists === false) {
                     \OC_Log::write('webdav', 'renaming part file to final file failed', \OC_Log::ERROR);
                     $partStorage->unlink($internalPartPath);
                     throw new Exception('Could not rename part file to final file');
                 }
             } catch (\Exception $e) {
                 $partStorage->unlink($internalPartPath);
                 $this->convertToSabreException($e);
             }
         }
         try {
             $this->fileView->changeLock($this->path, ILockingProvider::LOCK_SHARED);
         } catch (LockedException $e) {
             throw new FileLocked($e->getMessage(), $e->getCode(), $e);
         }
         // since we skipped the view we need to scan and emit the hooks ourselves
         $partStorage->getScanner()->scanFile($internalPath);
         if ($view) {
             $this->fileView->getUpdater()->propagate($hookPath);
             if (!$exists) {
                 \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(\OC\Files\Filesystem::signal_param_path => $hookPath));
             } else {
                 \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(\OC\Files\Filesystem::signal_param_path => $hookPath));
             }
             \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(\OC\Files\Filesystem::signal_param_path => $hookPath));
         }
         // allow sync clients to send the mtime along in a header
         $request = \OC::$server->getRequest();
         if (isset($request->server['HTTP_X_OC_MTIME'])) {
             if ($this->fileView->touch($this->path, $request->server['HTTP_X_OC_MTIME'])) {
                 header('X-OC-MTime: accepted');
             }
         }
         $this->refreshInfo();
         $this->fileView->unlockFile($this->path, ILockingProvider::LOCK_SHARED);
     } catch (StorageNotAvailableException $e) {
         throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
     }
     return '"' . $this->info->getEtag() . '"';
 }
Example #30
0
 /**
  * return the content of a file or return a zip file containing multiple files
  *
  * @param string $dir
  * @param string $files ; separated list of files to download
  * @param boolean $onlyHeader ; boolean to only send header of the request
  */
 public static function get($dir, $files, $onlyHeader = false)
 {
     $view = \OC\Files\Filesystem::getView();
     $getType = self::FILE;
     $filename = $dir;
     try {
         if (is_array($files) && count($files) === 1) {
             $files = $files[0];
         }
         if (!is_array($files)) {
             $filename = $dir . '/' . $files;
             if (!$view->is_dir($filename)) {
                 self::getSingleFile($view, $dir, $files, $onlyHeader);
                 return;
             }
         }
         $name = 'download';
         if (is_array($files)) {
             $getType = self::ZIP_FILES;
             $basename = basename($dir);
             if ($basename) {
                 $name = $basename;
             }
             $filename = $dir . '/' . $name;
         } else {
             $filename = $dir . '/' . $files;
             $getType = self::ZIP_DIR;
             // downloading root ?
             if ($files !== '') {
                 $name = $files;
             }
         }
         $streamer = new Streamer();
         OC_Util::obEnd();
         self::lockFiles($view, $dir, $files);
         $streamer->sendHeaders($name);
         $executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time'));
         set_time_limit(0);
         if ($getType === self::ZIP_FILES) {
             foreach ($files as $file) {
                 $file = $dir . '/' . $file;
                 if (\OC\Files\Filesystem::is_file($file)) {
                     $fileSize = \OC\Files\Filesystem::filesize($file);
                     $fh = \OC\Files\Filesystem::fopen($file, 'r');
                     $streamer->addFileFromStream($fh, basename($file), $fileSize);
                     fclose($fh);
                 } elseif (\OC\Files\Filesystem::is_dir($file)) {
                     $streamer->addDirRecursive($file);
                 }
             }
         } elseif ($getType === self::ZIP_DIR) {
             $file = $dir . '/' . $files;
             $streamer->addDirRecursive($file);
         }
         $streamer->finalize();
         set_time_limit($executionTime);
         self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
     } catch (\OCP\Lock\LockedException $ex) {
         self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
         OC::$server->getLogger()->logException($ex);
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
     } catch (\OCP\Files\ForbiddenException $ex) {
         self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
         OC::$server->getLogger()->logException($ex);
         $l = \OC::$server->getL10N('core');
         \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
     } catch (\Exception $ex) {
         self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
         OC::$server->getLogger()->logException($ex);
         $l = \OC::$server->getL10N('core');
         $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
         \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
     }
 }