/** * delete a SubAdmin * @param string $uid uid of the SubAdmin * @param string $gid gid of the group * @return boolean */ public static function deleteSubAdmin($uid, $gid) { $stmt = OC_DB::prepare('DELETE FROM `*PREFIX*group_admin` WHERE `gid` = ? AND `uid` = ?'); $result = $stmt->execute(array($gid, $uid)); OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", array("gid" => $gid)); return true; }
/** * delete a SubAdmin * @param IUser $user the user that is the SubAdmin * @param IGroup $group the group * @return bool */ public function deleteSubAdmin(IUser $user, IGroup $group) { $qb = $this->dbConn->getQueryBuilder(); $qb->delete('group_admin')->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))->execute(); $this->emit('\\OC\\SubAdmin', 'postDeleteSubAdmin', [$user, $group]); \OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]); return true; }
/** * @brief Can be set up * @param string $user * @return boolean * @description configure the initial filesystem based on the configuration */ public static function setupFS($user = '') { //setting up the filesystem twice can only lead to trouble if (self::$fsSetup) { return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // load all filesystem apps before, so no setup-hook gets lost if (!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) { OC_App::loadApps(array('filesystem')); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $configDataDirectory = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage \OC\Files\Filesystem::initMounts(); if (!self::$rootMounted) { \OC\Files\Filesystem::mount('\\OC\\Files\\Storage\\Local', array('datadir' => $configDataDirectory), '/'); self::$rootMounted = true; } //if we aren't logged in, there is no use to set up the filesystem if ($user != "") { \OC\Files\Filesystem::addStorageWrapper(function ($mountPoint, $storage) { // set up quota for home storages, even for other users // which can happen when using sharing if ($storage instanceof \OC\Files\Storage\Home) { $user = $storage->getUser()->getUID(); $quota = OC_Util::getUserQuota($user); if ($quota !== \OC\Files\SPACE_UNLIMITED) { return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota)); } } return $storage; }); $userDir = '/' . $user . '/files'; $userRoot = OC_User::getHome($user); $userDirectory = $userRoot . '/files'; if (!is_dir($userDirectory)) { mkdir($userDirectory, 0755, true); OC_Util::copySkeleton($userDirectory); } //jail the user into his "home" directory \OC\Files\Filesystem::init($user, $userDir); $fileOperationProxy = new OC_FileProxy_FileOperations(); OC_FileProxy::register($fileOperationProxy); OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir)); } return true; }
public static function setupFS($user = '') { // configure the initial filesystem based on the configuration if (self::$fsSetup) { //setting up the filesystem twice can only lead to trouble return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $CONFIG_DATADIRECTORY = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage if (!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY), '/'); self::$rootMounted = true; } if ($user != "") { //if we aren't logged in, there is no use to set up the filesystem $user_dir = '/' . $user . '/files'; $user_root = OC_User::getHome($user); $userdirectory = $user_root . '/files'; if (!is_dir($userdirectory)) { mkdir($userdirectory, 0755, true); } //jail the user into his "home" directory OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user); OC_Filesystem::init($user_dir); $quotaProxy = new OC_FileProxy_Quota(); OC_FileProxy::register($quotaProxy); // Load personal mount config if (is_file($user_root . '/mount.php')) { $mountConfig = (include $user_root . '/mount.php'); if (isset($mountConfig['user'][$user])) { foreach ($mountConfig['user'][$user] as $mountPoint => $options) { OC_Filesystem::mount($options['class'], $options['options'], $mountPoint); } } $mtime = filemtime($user_root . '/mount.php'); $previousMTime = OC_Preferences::getValue($user, 'files', 'mountconfigmtime', 0); if ($mtime > $previousMTime) { //mount config has changed, filecache needs to be updated OC_FileCache::triggerUpdate($user); OC_Preferences::setValue($user, 'files', 'mountconfigmtime', $mtime); } } OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir)); } }
/** * get the filesystem info from the cache * @param string path * @param string root (optional) * @return array * * returns an associative array with the following keys: * - size * - mtime * - ctime * - mimetype * - encrypted * - versioned */ public static function get($path, $root = false) { if (OC_FileCache_Update::hasUpdated($path, $root)) { if ($root === false) { //filesystem hooks are only valid for the default root OC_Hook::emit('OC_Filesystem', 'post_write', array('path' => $path)); } else { OC_FileCache_Update::update($path, $root); } } return OC_FileCache_Cached::get($path, $root); }
/** * scan all music for the current user * * @return int the number of songs found */ public function scanCollection() { $music = $this->getMusic(); \OC_Hook::emit('media', 'song_count', array('count' => count($music))); $songs = 0; foreach ($music as $file) { $this->scanFile($file); $songs++; \OC_Hook::emit('media', 'song_scanned', array('path' => $file, 'count' => $songs)); } return $songs; }
/** * upgrade all child elements of an item * * @param int $id * @param bool $mode */ function upgradeChilds($id, $mode = Scanner::SCAN_RECURSIVE) { $children = $this->legacy->getChildren($id); foreach ($children as $child) { $childData = $this->getNewData($child); \OC_Hook::emit('\\OC\\Files\\Cache\\Upgrade', 'migrate_path', $child['path']); if ($childData) { $this->insert($childData); if ($mode == Scanner::SCAN_RECURSIVE) { $this->upgradeChilds($child['id']); } } } }
public static function setupFS($user = '') { // configure the initial filesystem based on the configuration if (self::$fsSetup) { //setting up the filesystem twice can only lead to trouble return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // load all filesystem apps before, so no setup-hook gets lost if (!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) { OC_App::loadApps(array('filesystem')); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $CONFIG_DATADIRECTORY = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage if (!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY), '/'); self::$rootMounted = true; } if ($user != "") { //if we aren't logged in, there is no use to set up the filesystem $user_dir = '/' . $user . '/files'; $user_root = OC_User::getHome($user); $userdirectory = $user_root . '/files'; if (!is_dir($userdirectory)) { mkdir($userdirectory, 0755, true); } //jail the user into his "home" directory OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user); OC_Filesystem::init($user_dir, $user); $quotaProxy = new OC_FileProxy_Quota(); $fileOperationProxy = new OC_FileProxy_FileOperations(); OC_FileProxy::register($quotaProxy); OC_FileProxy::register($fileOperationProxy); // Load personal mount config self::loadUserMountPoints($user); OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir)); } }
/** * send server-to-server share to remote server * * @param string $token * @param string $shareWith * @param string $name * @param int $remote_id * @param string $owner * @return bool */ public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) { list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith); if ($user && $remote) { $url = $remote; $local = $this->addressHandler->generateRemoteURL(); $fields = array('shareWith' => $user, 'token' => $token, 'name' => $name, 'remoteId' => $remote_id, 'owner' => $owner, 'remote' => $local); $url = $this->addressHandler->removeProtocolFromUrl($url); $result = $this->tryHttpPostToShareEndpoint($url, '', $fields); $status = json_decode($result['result'], true); if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) { \OC_Hook::emit('OCP\\Share', 'federated_share_added', ['server' => $remote]); return true; } } return false; }
/** * Find the mount for $path * * @param string $path * @return MountPoint */ public function find($path) { \OC_Util::setupFS(); $path = $this->formatPath($path); if (isset($this->mounts[$path])) { return $this->mounts[$path]; } \OC_Hook::emit('OC_Filesystem', 'get_mountpoint', array('path' => $path)); $foundMountPoint = ''; $mountPoints = array_keys($this->mounts); foreach ($mountPoints as $mountpoint) { if (strpos($path, $mountpoint) === 0 and strlen($mountpoint) > strlen($foundMountPoint)) { $foundMountPoint = $mountpoint; } } if (isset($this->mounts[$foundMountPoint])) { return $this->mounts[$foundMountPoint]; } else { return null; } }
public function testBlacklist() { OC_Hook::clear('OC_Filesystem'); OC::registerFilesystemHooks(); $run = true; OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array(OC_Filesystem::signal_param_path => '/test/.htaccess', OC_Filesystem::signal_param_run => &$run)); $this->assertFalse($run); if (OC_Filesystem::getView()) { $user = OC_User::getUser(); } else { $user = uniqid(); OC_Filesystem::init('/' . $user . '/files'); } OC_Filesystem::mount('OC_Filestorage_Temporary', array(), '/'); $rootView = new OC_FilesystemView(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); $this->assertFalse($rootView->file_put_contents('/.htaccess', 'foo')); $this->assertFalse(OC_Filesystem::file_put_contents('/.htaccess', 'foo')); $fh = fopen(__FILE__, 'r'); $this->assertFalse(OC_Filesystem::file_put_contents('/.htaccess', $fh)); }
/** * send server-to-server share to remote server * * @param string $token * @param string $shareWith * @param string $name * @param int $remote_id * @param string $owner * @return bool */ private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) { list($user, $remote) = Helper::splitUserRemote($shareWith); if ($user && $remote) { $url = $remote . self::BASE_PATH_TO_SHARE_API . '?format=' . self::RESPONSE_FORMAT; $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/'); $fields = array('shareWith' => $user, 'token' => $token, 'name' => $name, 'remoteId' => $remote_id, 'owner' => $owner, 'remote' => $local); $url = self::removeProtocolFromUrl($url); $result = self::tryHttpPost($url, $fields); $status = json_decode($result['result'], true); if ($result['success'] && $status['ocs']['meta']['statuscode'] === 100) { \OC_Hook::emit('OCP\\Share', 'federated_share_added', ['server' => $remote]); return true; } } return false; }
/** * Can be set up * * @param string $user * @return boolean * @description configure the initial filesystem based on the configuration */ public static function setupFS($user = '') { //setting up the filesystem twice can only lead to trouble if (self::$fsSetup) { return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // load all filesystem apps before, so no setup-hook gets lost OC_App::loadApps(array('filesystem')); // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } //check if we are using an object storage $objectStore = OC_Config::getValue('objectstore'); if (isset($objectStore)) { self::initObjectStoreRootFS($objectStore); } else { self::initLocalStorageRootFS(); } if ($user != '' && !OCP\User::userExists($user)) { return false; } //if we aren't logged in, there is no use to set up the filesystem if ($user != "") { \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) { // set up quota for home storages, even for other users // which can happen when using sharing /** * @var \OC\Files\Storage\Storage $storage */ if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') || $storage->instanceOfStorage('\\OC\\Files\\ObjectStore\\HomeObjectStoreStorage')) { if (is_object($storage->getUser())) { $user = $storage->getUser()->getUID(); $quota = OC_Util::getUserQuota($user); if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files')); } } } return $storage; }); // copy skeleton for local storage only if (!isset($objectStore)) { $userRoot = OC_User::getHome($user); $userDirectory = $userRoot . '/files'; if (!is_dir($userDirectory)) { mkdir($userDirectory, 0755, true); OC_Util::copySkeleton($userDirectory); } } $userDir = '/' . $user . '/files'; //jail the user into his "home" directory \OC\Files\Filesystem::init($user, $userDir); $fileOperationProxy = new OC_FileProxy_FileOperations(); OC_FileProxy::register($fileOperationProxy); OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir)); } return true; }
/** * walk over any folders that are not fully scanned yet and scan them */ public function backgroundScan() { $lastPath = null; while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { try { $this->scan($path, self::SCAN_RECURSIVE, self::REUSE_ETAG); \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); if ($this->cacheActive) { $this->cache->correctFolderSize($path); } } catch (\OCP\Files\StorageInvalidException $e) { // skip unavailable storages } catch (\OCP\Files\StorageNotAvailableException $e) { // skip unavailable storages } catch (\OCP\Files\ForbiddenException $e) { // skip forbidden storages } catch (\OCP\Lock\LockedException $e) { // skip unavailable storages } // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() // to make this possible $lastPath = $path; } }
/** * Put shared item into the database * @param string $itemType Item type * @param string $itemSource Item source * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK * @param string $shareWith User or group the item is being shared with * @param string $uidOwner User that is the owner of shared item * @param int $permissions CRUDS permissions * @param boolean|array $parentFolder Parent folder target (optional) * @param string $token (optional) * @param string $itemSourceName name of the source item (optional) * @param \DateTime $expirationDate (optional) * @throws \Exception * @return boolean Returns true on success or false on failure */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) { $queriesToExecute = array(); $suggestedItemTarget = null; $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate); if (!empty($result)) { $parent = $result['parent']; $itemSource = $result['itemSource']; $fileSource = $result['fileSource']; $suggestedItemTarget = $result['suggestedItemTarget']; $suggestedFileTarget = $result['suggestedFileTarget']; $filePath = $result['filePath']; $expirationDate = $result['expirationDate']; } $isGroupShare = false; if ($shareType == self::SHARE_TYPE_GROUP) { $isGroupShare = true; $users = \OC_Group::usersInGroup($shareWith['group']); // remove current user from list if (in_array(\OCP\User::getUser(), $users)) { unset($users[array_search(\OCP\User::getUser(), $users)]); } $groupItemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget); $groupFileTarget = $filePath; // add group share to table and remember the id as parent $queriesToExecute['groupShare'] = array('itemType' => $itemType, 'itemSource' => $itemSource, 'itemTarget' => $groupItemTarget, 'shareType' => $shareType, 'shareWith' => $shareWith['group'], 'uidOwner' => $uidOwner, 'permissions' => $permissions, 'shareTime' => time(), 'fileSource' => $fileSource, 'fileTarget' => $filePath, 'token' => $token, 'parent' => $parent, 'expiration' => $expirationDate); } else { $users = array($shareWith); $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget); } $run = true; $error = ''; $preHookData = array('itemType' => $itemType, 'itemSource' => $itemSource, 'shareType' => $shareType, 'uidOwner' => $uidOwner, 'permissions' => $permissions, 'fileSource' => $fileSource, 'expiration' => $expirationDate, 'token' => $token, 'run' => &$run, 'error' => &$error); $preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget; $preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith; \OC_Hook::emit('OCP\\Share', 'pre_shared', $preHookData); if ($run === false) { throw new \Exception($error); } foreach ($users as $user) { $sourceId = $itemType === 'file' || $itemType === 'folder' ? $fileSource : $itemSource; $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user); $shareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType; if ($sourceExists) { $fileTarget = $sourceExists['file_target']; $itemTarget = $sourceExists['item_target']; // for group shares we don't need a additional entry if the target is the same if ($isGroupShare && $groupItemTarget === $itemTarget) { continue; } } elseif (!$sourceExists && !$isGroupShare) { $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $user, $uidOwner, $suggestedItemTarget, $parent); if (isset($fileSource)) { if ($parentFolder) { if ($parentFolder === true) { $fileTarget = Helper::generateTarget('file', $filePath, $shareType, $user, $uidOwner, $suggestedFileTarget, $parent); if ($fileTarget != $groupFileTarget) { $parentFolders[$user]['folder'] = $fileTarget; } } else { if (isset($parentFolder[$user])) { $fileTarget = $parentFolder[$user]['folder'] . $itemSource; $parent = $parentFolder[$user]['id']; } } } else { $fileTarget = Helper::generateTarget('file', $filePath, $shareType, $user, $uidOwner, $suggestedFileTarget, $parent); } } else { $fileTarget = null; } } else { // group share which doesn't exists until now, check if we need a unique target for this user $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user, $uidOwner, $suggestedItemTarget, $parent); // do we also need a file target if (isset($fileSource)) { $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user, $uidOwner, $suggestedFileTarget, $parent); } else { $fileTarget = null; } if ($itemTarget === $groupItemTarget && (isset($fileSource) && $fileTarget === $groupItemTarget)) { continue; } } $queriesToExecute[] = array('itemType' => $itemType, 'itemSource' => $itemSource, 'itemTarget' => $itemTarget, 'shareType' => $shareType, 'shareWith' => $user, 'uidOwner' => $uidOwner, 'permissions' => $permissions, 'shareTime' => time(), 'fileSource' => $fileSource, 'fileTarget' => $fileTarget, 'token' => $token, 'parent' => $parent, 'expiration' => $expirationDate); } if ($isGroupShare) { self::insertShare($queriesToExecute['groupShare']); // Save this id, any extra rows for this group share will need to reference it $parent = \OC_DB::insertid('*PREFIX*share'); unset($queriesToExecute['groupShare']); } foreach ($queriesToExecute as $shareQuery) { $shareQuery['parent'] = $parent; self::insertShare($shareQuery); } $postHookData = array('itemType' => $itemType, 'itemSource' => $itemSource, 'parent' => $parent, 'shareType' => $shareType, 'uidOwner' => $uidOwner, 'permissions' => $permissions, 'fileSource' => $fileSource, 'id' => $parent, 'token' => $token, 'expirationDate' => $expirationDate); $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith; $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget; $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget; \OC_Hook::emit('OCP\\Share', 'post_shared', $postHookData); return true; }
/** * @param mixed $app * @return bool * @throws Exception if app is not compatible with this version of ownCloud * @throws Exception if no app-name was specified */ public static function installApp($app) { $l = \OC::$server->getL10N('core'); $config = \OC::$server->getConfig(); $appData = OC_OCSClient::getApplication($app); // check if app is a shipped app or not. OCS apps have an integer as id, shipped apps use a string if (!is_numeric($app)) { $shippedVersion = self::getAppVersion($app); if ($appData && version_compare($shippedVersion, $appData['version'], '<')) { $app = self::downloadApp($app); } else { $app = OC_Installer::installShippedApp($app); } } else { // Maybe the app is already installed - compare the version in this // case and use the local already installed one. // FIXME: This is a horrible hack. I feel sad. The god of code cleanness may forgive me. $internalAppId = self::getInternalAppIdByOcs($app); if ($internalAppId !== false) { if ($appData && version_compare(\OC_App::getAppVersion($internalAppId), $appData['version'], '<')) { $app = self::downloadApp($app); } else { self::enable($internalAppId); $app = $internalAppId; } } else { $app = self::downloadApp($app); } } if ($app !== false) { // check if the app is compatible with this version of ownCloud $info = self::getAppInfo($app); $version = OC_Util::getVersion(); if (!self::isAppCompatible($version, $info)) { throw new \Exception($l->t('App \\"%s\\" can\'t be installed because it is not compatible with this version of ownCloud.', array($info['name']))); } // check for required dependencies $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l); $missing = $dependencyAnalyzer->analyze($app); if (!empty($missing)) { $missingMsg = join(PHP_EOL, $missing); throw new \Exception($l->t('App \\"%s\\" cannot be installed because the following dependencies are not fulfilled: %s', array($info['name'], $missingMsg))); } $config->setAppValue($app, 'enabled', 'yes'); if (isset($appData['id'])) { $config->setAppValue($app, 'ocsid', $appData['id']); } \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app)); } else { throw new \Exception($l->t("No app name specified")); } return $app; }
/** * Try to login a user, assuming authentication * has already happened (e.g. via Single Sign On). * * Log in a user and regenerate a new session. * * @param \OCP\Authentication\IApacheBackend $backend * @return bool */ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid)); if ($uid) { if (self::getUser() !== $uid) { self::setUserId($uid); self::setDisplayName($uid); self::getUserSession()->setLoginName($uid); OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => '')); } return true; } return false; }
/** * Emits a signal. To get data from the slot use references! * @param string $signalclass class name of emitter * @param string $signalname name of signal * @param array $params default: array() array with additional data * @return bool true if slots exists or false if not * * TODO: write example * @since 4.0.0 */ public static function emitHook($signalclass, $signalname, $params = array()) { return \OC_Hook::emit($signalclass, $signalname, $params); }
public function file_assemble($path) { $absolutePath = OC_Filesystem::normalizePath(OC_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_Filesystem::isValidPath($path)) { $path = OC_Filesystem::getView()->getRelativePath($absolutePath); $exists = OC_Filesystem::file_exists($path); $run = true; if (!$exists) { OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_create, array(OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); } OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array(OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); if (!$run) { return false; } $target = OC_Filesystem::fopen($path, 'w'); if ($target) { $count = $this->assemble($target); fclose($target); if (!$exists) { OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_create, array(OC_Filesystem::signal_param_path => $path)); } OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array(OC_Filesystem::signal_param_path => $path)); OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count); return $count > 0; } else { return false; } } }
function __construct() { $this->registerService('ContactsManager', function ($c) { return new ContactsManager(); }); $this->registerService('Request', function ($c) { if (isset($c['urlParams'])) { $urlParams = $c['urlParams']; } else { $urlParams = array(); } if (\OC::$server->getSession()->exists('requesttoken')) { $requestToken = \OC::$server->getSession()->get('requesttoken'); } else { $requestToken = false; } if (defined('PHPUNIT_RUN') && PHPUNIT_RUN && in_array('fakeinput', stream_get_wrappers())) { $stream = 'fakeinput://data'; } else { $stream = 'php://input'; } return new Request(array('get' => $_GET, 'post' => $_POST, 'files' => $_FILES, 'server' => $_SERVER, 'env' => $_ENV, 'cookies' => $_COOKIE, 'method' => isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null, 'urlParams' => $urlParams, 'requesttoken' => $requestToken), $stream); }); $this->registerService('PreviewManager', function ($c) { return new PreviewManager(); }); $this->registerService('TagManager', function ($c) { $user = \OC_User::getUser(); return new TagManager($user); }); $this->registerService('RootFolder', function ($c) { // TODO: get user and user manager from container as well $user = \OC_User::getUser(); /** @var $c SimpleContainer */ $userManager = $c->query('UserManager'); $user = $userManager->get($user); $manager = \OC\Files\Filesystem::getMountManager(); $view = new View(); return new Root($manager, $view, $user); }); $this->registerService('UserManager', function ($c) { /** * @var SimpleContainer $c * @var \OC\AllConfig $config */ $config = $c->query('AllConfig'); return new \OC\User\Manager($config); }); $this->registerService('GroupManager', function ($c) { /** * @var SimpleContainer $c * @var \OC\User\Manager $userManager */ $userManager = $c->query('UserManager'); return new \OC\Group\Manager($userManager); }); $this->registerService('UserSession', function ($c) { /** * @var SimpleContainer $c * @var \OC\User\Manager $manager */ $manager = $c->query('UserManager'); $userSession = new \OC\User\Session($manager, new \OC\Session\Memory('')); $userSession->listen('\\OC\\User', 'preCreateUser', function ($uid, $password) { \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password)); }); $userSession->listen('\\OC\\User', 'postCreateUser', function ($user, $password) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password)); }); $userSession->listen('\\OC\\User', 'preDelete', function ($user) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID())); }); $userSession->listen('\\OC\\User', 'postDelete', function ($user) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID())); }); $userSession->listen('\\OC\\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); }); $userSession->listen('\\OC\\User', 'postSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); }); $userSession->listen('\\OC\\User', 'preLogin', function ($uid, $password) { \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password)); }); $userSession->listen('\\OC\\User', 'postLogin', function ($user, $password) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password)); }); $userSession->listen('\\OC\\User', 'logout', function () { \OC_Hook::emit('OC_User', 'logout', array()); }); return $userSession; }); $this->registerService('NavigationManager', function ($c) { return new \OC\NavigationManager(); }); $this->registerService('AllConfig', function ($c) { return new \OC\AllConfig(); }); $this->registerService('AppConfig', function ($c) { return new \OC\AppConfig(\OC_DB::getConnection()); }); $this->registerService('L10NFactory', function ($c) { return new \OC\L10N\Factory(); }); $this->registerService('URLGenerator', function ($c) { /** @var $c SimpleContainer */ $config = $c->query('AllConfig'); return new \OC\URLGenerator($config); }); $this->registerService('AppHelper', function ($c) { return new \OC\AppHelper(); }); $this->registerService('UserCache', function ($c) { return new UserCache(); }); $this->registerService('MemCacheFactory', function ($c) { $instanceId = \OC_Util::getInstanceId(); return new \OC\Memcache\Factory($instanceId); }); $this->registerService('ActivityManager', function ($c) { return new ActivityManager(); }); $this->registerService('AvatarManager', function ($c) { return new AvatarManager(); }); $this->registerService('Logger', function ($c) { /** @var $c SimpleContainer */ $logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud'); $logger = 'OC_Log_' . ucfirst($logClass); call_user_func(array($logger, 'init')); return new Log($logger); }); $this->registerService('JobList', function ($c) { /** * @var Server $c */ $config = $c->getConfig(); return new \OC\BackgroundJob\JobList($c->getDatabaseConnection(), $config); }); $this->registerService('Router', function ($c) { /** * @var Server $c */ $cacheFactory = $c->getMemCacheFactory(); if ($cacheFactory->isAvailable()) { $router = new \OC\Route\CachingRouter($cacheFactory->create('route')); } else { $router = new \OC\Route\Router(); } return $router; }); $this->registerService('Search', function ($c) { return new Search(); }); $this->registerService('SecureRandom', function ($c) { return new SecureRandom(); }); $this->registerService('Crypto', function ($c) { return new Crypto(\OC::$server->getConfig(), \OC::$server->getSecureRandom()); }); $this->registerService('Db', function ($c) { return new Db(); }); }
/** * @param string[] $hooks * @param string $path * @param bool $post * @return bool */ private function runHooks($hooks, $path, $post = false) { $path = $this->getHookPath($path); $prefix = $post ? 'post_' : ''; $run = true; if ($this->shouldEmitHooks($path)) { foreach ($hooks as $hook) { if ($hook != 'read') { \OC_Hook::emit(Filesystem::CLASSNAME, $prefix . $hook, array(Filesystem::signal_param_run => &$run, Filesystem::signal_param_path => $path)); } elseif (!$post) { \OC_Hook::emit(Filesystem::CLASSNAME, $prefix . $hook, array(Filesystem::signal_param_path => $path)); } } } return $run; }
/** * @param string $webRoot */ public function __construct($webRoot) { parent::__construct(); $this->webRoot = $webRoot; $this->registerService('ContactsManager', function ($c) { return new ContactsManager(); }); $this->registerService('PreviewManager', function (Server $c) { return new PreviewManager($c->getConfig()); }); $this->registerService('EncryptionManager', function (Server $c) { $view = new View(); $util = new Encryption\Util($view, $c->getUserManager(), $c->getGroupManager(), $c->getConfig()); return new Encryption\Manager($c->getConfig(), $c->getLogger(), $c->getL10N('core'), new View(), $util); }); $this->registerService('EncryptionFileHelper', function (Server $c) { $util = new Encryption\Util(new View(), $c->getUserManager(), $c->getGroupManager(), $c->getConfig()); return new Encryption\File($util); }); $this->registerService('EncryptionKeyStorage', function (Server $c) { $view = new View(); $util = new Encryption\Util($view, $c->getUserManager(), $c->getGroupManager(), $c->getConfig()); return new Encryption\Keys\Storage($view, $util); }); $this->registerService('TagMapper', function (Server $c) { return new TagMapper($c->getDatabaseConnection()); }); $this->registerService('TagManager', function (Server $c) { $tagMapper = $c->query('TagMapper'); return new TagManager($tagMapper, $c->getUserSession()); }); $this->registerService('SystemTagManager', function (Server $c) { return new SystemTag\SystemTagManager($c->getDatabaseConnection()); }); $this->registerService('SystemTagObjectMapper', function (Server $c) { return new SystemTag\SystemTagObjectMapper($c->getDatabaseConnection(), $c->getSystemTagManager()); }); $this->registerService('RootFolder', function (Server $c) { // TODO: get user and user manager from container as well $user = \OC_User::getUser(); /** @var $c SimpleContainer */ $userManager = $c->query('UserManager'); $user = $userManager->get($user); $manager = \OC\Files\Filesystem::getMountManager(); $view = new View(); $root = new Root($manager, $view, $user); $connector = new HookConnector($root, $view); $connector->viewToNode(); return $root; }); $this->registerService('UserManager', function (Server $c) { $config = $c->getConfig(); return new \OC\User\Manager($config); }); $this->registerService('GroupManager', function (Server $c) { $groupManager = new \OC\Group\Manager($this->getUserManager()); $groupManager->listen('\\OC\\Group', 'preCreate', function ($gid) { \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid)); }); $groupManager->listen('\\OC\\Group', 'postCreate', function (\OC\Group\Group $gid) { \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID())); }); $groupManager->listen('\\OC\\Group', 'preDelete', function (\OC\Group\Group $group) { \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID())); }); $groupManager->listen('\\OC\\Group', 'postDelete', function (\OC\Group\Group $group) { \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID())); }); $groupManager->listen('\\OC\\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) { \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID())); }); $groupManager->listen('\\OC\\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) { \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID())); //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID())); }); return $groupManager; }); $this->registerService('UserSession', function (Server $c) { $manager = $c->getUserManager(); $session = new \OC\Session\Memory(''); $userSession = new \OC\User\Session($manager, $session); $userSession->listen('\\OC\\User', 'preCreateUser', function ($uid, $password) { \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password)); }); $userSession->listen('\\OC\\User', 'postCreateUser', function ($user, $password) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password)); }); $userSession->listen('\\OC\\User', 'preDelete', function ($user) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID())); }); $userSession->listen('\\OC\\User', 'postDelete', function ($user) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID())); }); $userSession->listen('\\OC\\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); }); $userSession->listen('\\OC\\User', 'postSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword)); }); $userSession->listen('\\OC\\User', 'preLogin', function ($uid, $password) { \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password)); }); $userSession->listen('\\OC\\User', 'postLogin', function ($user, $password) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password)); }); $userSession->listen('\\OC\\User', 'logout', function () { \OC_Hook::emit('OC_User', 'logout', array()); }); return $userSession; }); $this->registerService('NavigationManager', function ($c) { return new \OC\NavigationManager(); }); $this->registerService('AllConfig', function (Server $c) { return new \OC\AllConfig($c->getSystemConfig()); }); $this->registerService('SystemConfig', function ($c) { return new \OC\SystemConfig(); }); $this->registerService('AppConfig', function ($c) { return new \OC\AppConfig(\OC_DB::getConnection()); }); $this->registerService('L10NFactory', function ($c) { return new \OC\L10N\Factory(); }); $this->registerService('URLGenerator', function (Server $c) { $config = $c->getConfig(); $cacheFactory = $c->getMemCacheFactory(); return new \OC\URLGenerator($config, $cacheFactory); }); $this->registerService('AppHelper', function ($c) { return new \OC\AppHelper(); }); $this->registerService('UserCache', function ($c) { return new Cache\File(); }); $this->registerService('MemCacheFactory', function (Server $c) { $config = $c->getConfig(); if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) { $v = \OC_App::getAppVersions(); $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php')); $version = implode(',', $v); $instanceId = \OC_Util::getInstanceId(); $path = \OC::$SERVERROOT; $prefix = md5($instanceId . '-' . $version . '-' . $path); return new \OC\Memcache\Factory($prefix, $c->getLogger(), $config->getSystemValue('memcache.local', null), $config->getSystemValue('memcache.distributed', null), $config->getSystemValue('memcache.locking', null)); } return new \OC\Memcache\Factory('', $c->getLogger(), '\\OC\\Memcache\\ArrayCache', '\\OC\\Memcache\\ArrayCache', '\\OC\\Memcache\\ArrayCache'); }); $this->registerService('ActivityManager', function (Server $c) { return new ActivityManager($c->getRequest(), $c->getUserSession(), $c->getConfig()); }); $this->registerService('AvatarManager', function (Server $c) { return new AvatarManager($c->getUserManager(), $c->getRootFolder(), $c->getL10N('lib')); }); $this->registerService('Logger', function (Server $c) { $logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud'); $logger = 'OC_Log_' . ucfirst($logClass); call_user_func(array($logger, 'init')); return new Log($logger); }); $this->registerService('JobList', function (Server $c) { $config = $c->getConfig(); return new \OC\BackgroundJob\JobList($c->getDatabaseConnection(), $config); }); $this->registerService('Router', function (Server $c) { $cacheFactory = $c->getMemCacheFactory(); $logger = $c->getLogger(); if ($cacheFactory->isAvailable()) { $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger); } else { $router = new \OC\Route\Router($logger); } return $router; }); $this->registerService('Search', function ($c) { return new Search(); }); $this->registerService('SecureRandom', function ($c) { return new SecureRandom(); }); $this->registerService('Crypto', function (Server $c) { return new Crypto($c->getConfig(), $c->getSecureRandom()); }); $this->registerService('Hasher', function (Server $c) { return new Hasher($c->getConfig()); }); $this->registerService('DatabaseConnection', function (Server $c) { $factory = new \OC\DB\ConnectionFactory(); $systemConfig = $c->getSystemConfig(); $type = $systemConfig->getValue('dbtype', 'sqlite'); if (!$factory->isValidType($type)) { throw new \OC\DatabaseException('Invalid database type'); } $connectionParams = $factory->createConnectionParams($systemConfig); $connection = $factory->getConnection($type, $connectionParams); $connection->getConfiguration()->setSQLLogger($c->getQueryLogger()); return $connection; }); $this->registerService('Db', function (Server $c) { return new Db($c->getDatabaseConnection()); }); $this->registerService('HTTPHelper', function (Server $c) { $config = $c->getConfig(); return new HTTPHelper($config, $c->getHTTPClientService()); }); $this->registerService('HttpClientService', function (Server $c) { $user = \OC_User::getUser(); $uid = $user ? $user : null; return new ClientService($c->getConfig(), new \OC\Security\CertificateManager($uid, new View(), $c->getConfig())); }); $this->registerService('EventLogger', function (Server $c) { if ($c->getSystemConfig()->getValue('debug', false)) { return new EventLogger(); } else { return new NullEventLogger(); } }); $this->registerService('QueryLogger', function (Server $c) { if ($c->getSystemConfig()->getValue('debug', false)) { return new QueryLogger(); } else { return new NullQueryLogger(); } }); $this->registerService('TempManager', function (Server $c) { return new TempManager($c->getLogger(), $c->getConfig()); }); $this->registerService('AppManager', function (Server $c) { return new \OC\App\AppManager($c->getUserSession(), $c->getAppConfig(), $c->getGroupManager(), $c->getMemCacheFactory()); }); $this->registerService('DateTimeZone', function (Server $c) { return new DateTimeZone($c->getConfig(), $c->getSession()); }); $this->registerService('DateTimeFormatter', function (Server $c) { $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null); return new DateTimeFormatter($c->getDateTimeZone()->getTimeZone(), $c->getL10N('lib', $language)); }); $this->registerService('MountConfigManager', function () { $loader = \OC\Files\Filesystem::getLoader(); return new \OC\Files\Config\MountProviderCollection($loader); }); $this->registerService('IniWrapper', function ($c) { return new IniGetWrapper(); }); $this->registerService('AsyncCommandBus', function (Server $c) { $jobList = $c->getJobList(); return new AsyncBus($jobList); }); $this->registerService('TrustedDomainHelper', function ($c) { return new TrustedDomainHelper($this->getConfig()); }); $this->registerService('IntegrityCodeChecker', function (Server $c) { // IConfig and IAppManager requires a working database. This code // might however be called when ownCloud is not yet setup. if (\OC::$server->getSystemConfig()->getValue('installed', false)) { $config = $c->getConfig(); $appManager = $c->getAppManager(); } else { $config = null; $appManager = null; } return new Checker(new EnvironmentHelper(), new FileAccessHelper(), new AppLocator(), $config, $c->getMemCacheFactory(), $appManager); }); $this->registerService('Request', function ($c) { if (isset($this['urlParams'])) { $urlParams = $this['urlParams']; } else { $urlParams = []; } if ($this->getSession()->exists('requesttoken')) { $requestToken = $this->getSession()->get('requesttoken'); } else { $requestToken = false; } if (defined('PHPUNIT_RUN') && PHPUNIT_RUN && in_array('fakeinput', stream_get_wrappers())) { $stream = 'fakeinput://data'; } else { $stream = 'php://input'; } return new Request(['get' => $_GET, 'post' => $_POST, 'files' => $_FILES, 'server' => $_SERVER, 'env' => $_ENV, 'cookies' => $_COOKIE, 'method' => isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null, 'urlParams' => $urlParams, 'requesttoken' => $requestToken], $this->getSecureRandom(), $this->getConfig(), $stream); }); $this->registerService('Mailer', function (Server $c) { return new Mailer($c->getConfig(), $c->getLogger(), new \OC_Defaults()); }); $this->registerService('OcsClient', function (Server $c) { return new OCSClient($this->getHTTPClientService(), $this->getConfig(), $this->getLogger()); }); $this->registerService('LockingProvider', function (Server $c) { if ($c->getConfig()->getSystemValue('filelocking.enabled', true) or defined('PHPUNIT_RUN') && PHPUNIT_RUN) { /** @var \OC\Memcache\Factory $memcacheFactory */ $memcacheFactory = $c->getMemCacheFactory(); $memcache = $memcacheFactory->createLocking('lock'); if (!$memcache instanceof \OC\Memcache\NullCache) { return new MemcacheLockingProvider($memcache); } return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory()); } return new NoopLockingProvider(); }); $this->registerService('MountManager', function () { return new \OC\Files\Mount\Manager(); }); $this->registerService('MimeTypeDetector', function (Server $c) { return new \OC\Files\Type\Detection($c->getURLGenerator(), \OC::$SERVERROOT . '/config/', \OC::$SERVERROOT . '/resources/config/'); }); $this->registerService('MimeTypeLoader', function (Server $c) { return new \OC\Files\Type\Loader($c->getDatabaseConnection()); }); $this->registerService('NotificationManager', function () { return new Manager(); }); $this->registerService('CapabilitiesManager', function (Server $c) { $manager = new \OC\CapabilitiesManager(); $manager->registerCapability(function () use($c) { return new \OC\OCS\CoreCapabilities($c->getConfig()); }); return $manager; }); $this->registerService('CommentsManager', function (Server $c) { $config = $c->getConfig(); $factoryClass = $config->getSystemValue('comments.managerFactory', '\\OC\\Comments\\ManagerFactory'); /** @var \OCP\Comments\ICommentsManagerFactory $factory */ $factory = new $factoryClass(); return $factory->getManager(); }); $this->registerService('EventDispatcher', function () { return new EventDispatcher(); }); $this->registerService('CryptoWrapper', function (Server $c) { // FIXME: Instantiiated here due to cyclic dependency $request = new Request(['get' => $_GET, 'post' => $_POST, 'files' => $_FILES, 'server' => $_SERVER, 'env' => $_ENV, 'cookies' => $_COOKIE, 'method' => isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null], new SecureRandom(), $c->getConfig()); return new CryptoWrapper($c->getConfig(), $c->getCrypto(), $c->getSecureRandom(), $request); }); }
/** * scan a single file and store it in the cache * * @param string $file * @param int $reuseExisting * @param bool $parentExistsInCache * @return array with metadata of the scanned file */ public function scanFile($file, $reuseExisting = 0, $parentExistsInCache = false) { if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { $this->emit('\\OC\\Files\\Cache\\Scanner', 'scanFile', array($file, $this->storageId)); \OC_Hook::emit('\\OC\\Files\\Cache\\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); $data = $this->getData($file); if ($data) { if ($file and !$parentExistsInCache) { $parent = dirname($file); if ($parent === '.' or $parent === '/') { $parent = ''; } if (!$this->cache->inCache($parent)) { $this->scanFile($parent); } } $newData = $data; $cacheData = $this->cache->get($file); if ($cacheData) { if (isset($cacheData['fileid'])) { $this->permissionsCache->remove($cacheData['fileid']); } if ($reuseExisting) { // prevent empty etag $etag = $cacheData['etag']; $propagateETagChange = false; if (empty($etag)) { $etag = $data['etag']; $propagateETagChange = true; } // only reuse data if the file hasn't explicitly changed if (isset($data['mtime']) && isset($cacheData['mtime']) && $data['mtime'] === $cacheData['mtime']) { if ($reuseExisting & self::REUSE_SIZE && $data['size'] === -1) { $data['size'] = $cacheData['size']; } if ($reuseExisting & self::REUSE_ETAG) { $data['etag'] = $etag; if ($propagateETagChange) { $parent = $file; while ($parent !== '') { $parent = dirname($parent); if ($parent === '.') { $parent = ''; } $parentCacheData = $this->cache->get($parent); $this->cache->update($parentCacheData['fileid'], array('etag' => $this->storage->getETag($parent))); } } } } // Only update metadata that has changed $newData = array_diff_assoc($data, $cacheData); if (isset($newData['etag'])) { $cacheDataString = print_r($cacheData, true); $dataString = print_r($data, true); \OCP\Util::writeLog('OC\\Files\\Cache\\Scanner', "!!! No reuse of etag for '{$file}' !!! \ncache: {$cacheDataString} \ndata: {$dataString}", \OCP\Util::DEBUG); } } } if (!empty($newData)) { $this->cache->put($file, $newData); $this->emit('\\OC\\Files\\Cache\\Scanner', 'postScanFile', array($file, $this->storageId)); \OC_Hook::emit('\\OC\\Files\\Cache\\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); } } else { $this->cache->remove($file); } return $data; } return null; }
/** * Delete a share * * @param IShare $share * @throws ShareNotFound * @throws BackendError * @throws ShareNotFound */ public function deleteShare(IShare $share) { // Just to make sure we have all the info $share = $this->getShareById($share->getFullId()); $formatHookParams = function (IShare $share) { // Prepare hook $shareType = $share->getShareType(); $sharedWith = ''; if ($shareType === \OCP\Share::SHARE_TYPE_USER) { $sharedWith = $share->getSharedWith()->getUID(); } else { if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) { $sharedWith = $share->getSharedWith()->getGID(); } else { if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) { $sharedWith = $share->getSharedWith(); } } } $hookParams = ['id' => $share->getId(), 'itemType' => $share->getPath() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getPath()->getId(), 'shareType' => $shareType, 'shareWith' => $sharedWith, 'itemparent' => $share->getParent(), 'uidOwner' => $share->getSharedBy()->getUID(), 'fileSource' => $share->getPath()->getId(), 'fileTarget' => $share->getTarget()]; return $hookParams; }; $hookParams = $formatHookParams($share); // Emit pre-hook \OC_Hook::emit('OCP\\Share', 'pre_unshare', $hookParams); // Get all children and delete them as well $deletedShares = $this->deleteChildren($share); // Do the actual delete $provider = $this->factory->getProviderForType($share->getShareType()); $provider->delete($share); // All the deleted shares caused by this delete $deletedShares[] = $share; //Format hook info $formattedDeletedShares = array_map(function ($share) use($formatHookParams) { return $formatHookParams($share); }, $deletedShares); $hookParams['deletedShares'] = $formattedDeletedShares; // Emit post hook \OC_Hook::emit('OCP\\Share', 'post_unshare', $hookParams); }
/** * get the mountpoint of the storage object for a path ( note: because a storage is not always mounted inside the fakeroot, the returned mountpoint is relative to the absolute root of the filesystem and doesn't take the chroot into account * * @param string path * @return string */ public static function getMountPoint($path) { OC_Hook::emit(self::CLASSNAME, 'get_mountpoint', array('path' => $path)); if (!$path) { $path = '/'; } if ($path[0] !== '/') { $path = '/' . $path; } $foundMountPoint = ''; foreach (OC_Filesystem::$mounts as $mountpoint => $storage) { if ($mountpoint == $path) { return $mountpoint; } if (strpos($path, $mountpoint) === 0 and strlen($mountpoint) > strlen($foundMountPoint)) { $foundMountPoint = $mountpoint; } } return $foundMountPoint; }
/** * 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() . '"'; }
/** * * @param string $mountPoint Mount point * @param string $mountType MOUNT_TYPE_GROUP | MOUNT_TYPE_USER * @param string $applicable User or group to remove mount from * @param bool $isPersonal Personal or system mount point * @return bool */ public static function removeMountPoint($mountPoint, $mountType, $applicable, $isPersonal = false) { // Verify that the mount point applies for the current user $relMountPoints = $mountPoint; if ($isPersonal) { if ($applicable != OCP\User::getUser()) { return false; } $mountPoint = '/' . $applicable . '/files/' . ltrim($mountPoint, '/'); } else { $mountPoint = '/$user/files/' . ltrim($mountPoint, '/'); } $mountPoint = \OC\Files\Filesystem::normalizePath($mountPoint); $mountPoints = self::readData($isPersonal ? OCP\User::getUser() : NULL); // Remove mount point unset($mountPoints[$mountType][$applicable][$mountPoint]); // Unset parent arrays if empty if (empty($mountPoints[$mountType][$applicable])) { unset($mountPoints[$mountType][$applicable]); if (empty($mountPoints[$mountType])) { unset($mountPoints[$mountType]); } } self::writeData($isPersonal ? OCP\User::getUser() : NULL, $mountPoints); \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_delete_mount, array(\OC\Files\Filesystem::signal_param_path => $relMountPoints, \OC\Files\Filesystem::signal_param_mount_type => $mountType, \OC\Files\Filesystem::signal_param_users => $applicable)); return true; }
/** * abstraction for running most basic operations * @param string $operation * @param string #path * @param array (optional) hooks * @param mixed (optional) $extraParam * @return mixed */ private function basicOperation($operation, $path, $hooks = array(), $extraParam = null) { $absolutePath = $this->getAbsolutePath($path); if (OC_FileProxy::runPreProxies($operation, $absolutePath, $extraParam) and OC_Filesystem::isValidPath($path)) { $path = $this->getRelativePath($absolutePath); if ($path == null) { return false; } $internalPath = $this->getInternalPath($path); $run = true; if (OC_Filesystem::$loaded and $this->fakeRoot == OC_Filesystem::getRoot()) { foreach ($hooks as $hook) { if ($hook != 'read') { OC_Hook::emit(OC_Filesystem::CLASSNAME, $hook, array(OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); } else { OC_Hook::emit(OC_Filesystem::CLASSNAME, $hook, array(OC_Filesystem::signal_param_path => $path)); } } } if ($run and $storage = $this->getStorage($path)) { if (!is_null($extraParam)) { $result = $storage->{$operation}($internalPath, $extraParam); } else { $result = $storage->{$operation}($internalPath); } $result = OC_FileProxy::runPostProxies($operation, $this->getAbsolutePath($path), $result); if (OC_Filesystem::$loaded and $this->fakeRoot == OC_Filesystem::getRoot()) { if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open foreach ($hooks as $hook) { if ($hook != 'read') { OC_Hook::emit(OC_Filesystem::CLASSNAME, 'post_' . $hook, array(OC_Filesystem::signal_param_path => $path)); } } } } return $result; } } return null; }
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 )); }
// Set the content type to Javascript header("Content-type: text/javascript"); // Disallow caching header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Enable l10n support $l = \OC::$server->getL10N('core'); // Enable OC_Defaults support $defaults = new OC_Defaults(); // Get the config $apps_paths = array(); foreach (OC_App::getEnabledApps() as $app) { $apps_paths[$app] = OC_App::getAppWebPath($app); } $config = \OC::$server->getConfig(); $value = $config->getAppValue('core', 'shareapi_default_expire_date', 'no'); $defaultExpireDateEnabled = $value === 'yes' ? true : false; $defaultExpireDate = $enforceDefaultExpireDate = null; if ($defaultExpireDateEnabled) { $defaultExpireDate = (int) $config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); $value = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no'); $enforceDefaultExpireDate = $value === 'yes' ? true : false; } $outgoingServer2serverShareEnabled = $config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; $array = array("oc_debug" => defined('DEBUG') && DEBUG ? 'true' : 'false', "oc_isadmin" => OC_User::isAdminUser(OC_User::getUser()) ? 'true' : 'false', "oc_webroot" => "\"" . OC::$WEBROOT . "\"", "oc_appswebroots" => str_replace('\\/', '/', json_encode($apps_paths)), "datepickerFormatDate" => json_encode($l->getDateFormat()), "dayNames" => json_encode(array((string) $l->t('Sunday'), (string) $l->t('Monday'), (string) $l->t('Tuesday'), (string) $l->t('Wednesday'), (string) $l->t('Thursday'), (string) $l->t('Friday'), (string) $l->t('Saturday'))), "monthNames" => json_encode(array((string) $l->t('January'), (string) $l->t('February'), (string) $l->t('March'), (string) $l->t('April'), (string) $l->t('May'), (string) $l->t('June'), (string) $l->t('July'), (string) $l->t('August'), (string) $l->t('September'), (string) $l->t('October'), (string) $l->t('November'), (string) $l->t('December'))), "firstDay" => json_encode($l->getFirstWeekDay()), "oc_config" => json_encode(array('session_lifetime' => min(\OCP\Config::getSystemValue('session_lifetime', ini_get('session.gc_maxlifetime')), ini_get('session.gc_maxlifetime')), 'session_keepalive' => \OCP\Config::getSystemValue('session_keepalive', true), 'version' => implode('.', OC_Util::getVersion()), 'versionstring' => OC_Util::getVersionString(), 'enable_avatars' => \OC::$server->getConfig()->getSystemValue('enable_avatars', true))), "oc_appconfig" => json_encode(array("core" => array('defaultExpireDateEnabled' => $defaultExpireDateEnabled, 'defaultExpireDate' => $defaultExpireDate, 'defaultExpireDateEnforced' => $enforceDefaultExpireDate, 'enforcePasswordForPublicLink' => \OCP\Util::isPublicLinkPasswordRequired(), 'sharingDisabledForUser' => \OCP\Util::isSharingDisabledForUser(), 'resharingAllowed' => \OCP\Share::isResharingAllowed(), 'remoteShareAllowed' => $outgoingServer2serverShareEnabled, 'federatedCloudShareDoc' => \OC::$server->getURLGenerator()->linkToDocs('user-sharing-federated')))), "oc_defaults" => json_encode(array('entity' => $defaults->getEntity(), 'name' => $defaults->getName(), 'title' => $defaults->getTitle(), 'baseUrl' => $defaults->getBaseUrl(), 'syncClientUrl' => $defaults->getSyncClientUrl(), 'docBaseUrl' => $defaults->getDocBaseUrl(), 'slogan' => $defaults->getSlogan(), 'logoClaim' => $defaults->getLogoClaim(), 'shortFooter' => $defaults->getShortFooter(), 'longFooter' => $defaults->getLongFooter()))); // Allow hooks to modify the output values OC_Hook::emit('\\OCP\\Config', 'js', array('array' => &$array)); // Echo it foreach ($array as $setting => $value) { echo "var " . $setting . "=" . $value . ";\n"; }