/** * Returns a list of calendars for a principal. * * Every project is an array with the following keys: * * id, a unique id that will be used by other functions to modify the * calendar. This can be the same as the uri or a database key. * * uri, which the basename of the uri with which the calendar is * accessed. * * principalUri. The owner of the calendar. Almost always the same as * principalUri passed to this method. * * Furthermore it can contain webdav properties in clark notation. A very * common one is '{DAV:}displayname'. * * @param string $principalUri * @return array */ public function getCalendarsForUser($principalUri) { $raw = OC_Calendar_Calendar::allCalendarsWherePrincipalURIIs($principalUri); $calendars = array(); foreach ($raw as $row) { $components = explode(',', $row['components']); if ($row['userid'] != OCP\USER::getUser()) { $row['uri'] = $row['uri'] . '_shared_by_' . $row['userid']; } $calendar = array('id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => 'principals/' . $row['userid'], '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag'] ? $row['ctag'] : '0', '{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}supported-calendar-component-set' => new \Sabre\CalDAV\Property\SupportedCalendarComponentSet($components)); foreach ($this->propertyMap as $xmlName => $dbName) { $calendar[$xmlName] = isset($row[$dbName]) ? $row[$dbName] : ''; } $calendars[] = $calendar; } if (\OCP\App::isEnabled('contacts')) { $ctag = 0; $app = new \OCA\Contacts\App(); $addressBooks = $app->getAddressBooksForUser(); foreach ($addressBooks as $addressBook) { $tmp = $addressBook->lastModified(); if (!is_null($tmp)) { $ctag = max($ctag, $tmp); } } $ctag++; $calendars[] = array('id' => 'contact_birthdays', 'uri' => 'contact_birthdays', '{DAV:}displayname' => (string) OC_Calendar_App::$l10n->t('Contact birthdays'), 'principaluri' => 'principals/contact_birthdays', '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}getctag' => $ctag, '{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}supported-calendar-component-set' => new \Sabre\CalDAV\Property\SupportedCalendarComponentSet(array('VEVENT')), '{http://apple.com/ns/ical/}calendar-color' => '#CCCCCC'); } return $calendars; }
/** * @param array $arguments */ public function run($arguments) { if (!App::isEnabled('search_lucene')) { return; } $app = new Application(); $container = $app->getContainer(); /** @var Logger $logger */ $logger = $container->query('Logger'); if (empty($arguments['user'])) { $logger->debug('indexer job did not receive user in arguments: ' . json_encode($arguments)); return; } $userId = $arguments['user']; $logger->debug('background job optimizing index for ' . $userId); $container->query('FileUtility')->setUpIndexFolder($userId); /** @var Index $index */ $index = $container->query('Index'); /** @var StatusMapper $mapper */ $mapper = $container->query('StatusMapper'); $deletedIds = $mapper->getDeleted(); $count = 0; foreach ($deletedIds as $fileId) { $logger->debug('deleting status for (' . $fileId . ') '); //delete status $status = new Status($fileId); $mapper->delete($status); //delete from lucene $count += $index->deleteFile($fileId); } $logger->debug('removed ' . $count . ' files from index'); }
/** * Asynchronously scan data that are written to the file * @param string $path * @param string $mode * @return resource | bool */ public function fopen($path, $mode) { $stream = $this->storage->fopen($path, $mode); if (is_resource($stream) && $this->isWritingMode($mode)) { try { $scanner = $this->scannerFactory->getScanner(); $scanner->initAsyncScan(); return CallBackWrapper::wrap($stream, null, function ($data) use($scanner) { $scanner->onAsyncData($data); }, function () use($scanner, $path) { $status = $scanner->completeAsyncScan(); if (intval($status->getNumericStatus()) === \OCA\Files_Antivirus\Status::SCANRESULT_INFECTED) { //prevent from going to trashbin if (App::isEnabled('files_trashbin')) { \OCA\Files_Trashbin\Storage::preRenameHook([]); } $owner = $this->getOwner($path); $this->unlink($path); if (App::isEnabled('files_trashbin')) { \OCA\Files_Trashbin\Storage::postRenameHook([]); } \OC::$server->getActivityManager()->publishActivity('files_antivirus', Activity::SUBJECT_VIRUS_DETECTED, [$path, $status->getDetails()], Activity::MESSAGE_FILE_DELETED, [], $path, '', $owner, Activity::TYPE_VIRUS_DETECTED, Activity::PRIORITY_HIGH); throw new InvalidContentException($this->l10n->t('Virus %s is detected in the file. Upload cannot be completed.', $status->getDetails())); } }); } catch (\Exception $e) { $message = implode(' ', [__CLASS__, __METHOD__, $e->getMessage()]); $this->logger->warning($message); } } return $stream; }
/** * @brief clean up user specific settings if user gets deleted * @param array with uid * * This function is connected to the pre_deleteUser signal of OC_Users * to remove the used space for versions stored in the database */ public static function deleteUser_hook($params) { if (\OCP\App::isEnabled('files_versions')) { $uid = $params['uid']; Storage::deleteUser($uid); } }
/** * get list of users with access to the file * * @param string $path to the file * @return array */ public function getAccessList($path) { // Make sure that a share key is generated for the owner too list($owner, $ownerPath) = $this->util->getUidAndFilename($path); // always add owner to the list of users with access to the file $userIds = array($owner); if (!$this->util->isFile($ownerPath)) { return array('users' => $userIds, 'public' => false); } $ownerPath = substr($ownerPath, strlen('/files')); $ownerPath = $this->util->stripPartialFileExtension($ownerPath); // Find out who, if anyone, is sharing the file $result = \OCP\Share::getUsersSharingFile($ownerPath, $owner); $userIds = \array_merge($userIds, $result['users']); $public = $result['public'] || $result['remote']; // check if it is a group mount if (\OCP\App::isEnabled("files_external")) { $mounts = \OC_Mount_Config::getSystemMountPoints(); foreach ($mounts as $mount) { if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) { $mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']); $userIds = array_merge($userIds, $mountedFor); } } } // Remove duplicate UIDs $uniqueUserIds = array_unique($userIds); return array('users' => $uniqueUserIds, 'public' => $public); }
/** * @brief clean up user specific settings if user gets deleted * @param array with uid * * This function is connected to the pre_deleteUser signal of OC_Users * to remove the used space for the trash bin stored in the database */ public static function deleteUser_hook($params) { if (\OCP\App::isEnabled('files_trashbin')) { $uid = $params['uid']; Trashbin::deleteUser($uid); } }
/** * Search for query in calendar events * * @param string $query * @return array list of \OCA\Calendar\Search\Event */ function search($query) { $calendars = \OC_Calendar_Calendar::allCalendars(\OCP\USER::getUser(), true); // check if the calenar is enabled if (count($calendars) == 0 || !\OCP\App::isEnabled('calendar')) { return array(); } $results = array(); foreach ($calendars as $calendar) { $objects = \OC_Calendar_Object::all($calendar['id']); $date = strtotime($query); // search all calendar objects, one by one foreach ($objects as $object) { // skip non-events if ($object['objecttype'] != 'VEVENT') { continue; } // check the event summary string if (stripos($object['summary'], $query) !== false) { $results[] = new \OCA\Calendar\Search\Event($object); continue; } // check if the event is happening on a queried date $range = $this->getDateRange($object); if ($date && $this->fallsWithin($date, $range)) { $results[] = new \OCA\Calendar\Search\Event($object); continue; } } } return $results; }
public static function run() { if (!\OCP\App::isEnabled('files_antivirus')) { return; } $application = new Application(); $container = $application->getContainer(); $container->query('BackgroundScanner')->run(); }
/** * rename/move versions of renamed/moved files * @param array $params array with oldpath and newpath * * This function is connected to the rename signal of OC_Filesystem and adjust the name and location * of the stored versions along the actual file */ public static function rename_hook($params) { if (\OCP\App::isEnabled('files_versions')) { $oldpath = $params['oldpath']; $newpath = $params['newpath']; if ($oldpath != '' && $newpath != '') { Storage::rename($oldpath, $newpath); } } }
/** * Get an layer * @NoAdminRequired * @NoCSRFRequired */ public function getlayer() { $layer = $this->params('layer') ? $this->params('layer') : null; if ($layer === "contacts") { if (\OCP\App::isEnabled('contacts')) { } else { OCP\Util::writeLog('maps', "App contacts missing for Maps", \OCP\Util::WARN); } } }
/** * @param array $arguments */ public function run($arguments) { if ((\OCP\App::isEnabled('contacts') || \OCP\App::isEnabled('contactsplus')) && \OCP\App::isEnabled('fbsync')) { $cache = \OC::$server->getCache(); $cache->set("test", "test"); } else { \OCP\Util::writeLog('fbsync', "App not enabled", \OCP\Util::INFO); return; } }
private static function getUidAndFilename($filename) { if (\OCP\App::isEnabled('files_sharing') && substr($filename, 0, 7) == '/Shared' && ($source = \OCP\Share::getItemSharedWith('file', substr($filename, 7), \OC_Share_Backend_File::FORMAT_SHARED_STORAGE))) { $filename = $source['path']; $pos = strpos($filename, '/files', 1); $uid = substr($filename, 1, $pos - 1); $filename = substr($filename, $pos + 6); } else { $uid = \OCP\User::getUser(); } return array($uid, $filename); }
/** * Search for query in tasks * * @param string $query * @return array list of \OCA\Tasks\Controller\Task */ function search($query) { $calendars = \OC_Calendar_Calendar::allCalendars(\OC::$server->getUserSession()->getUser()->getUID(), true); $user_timezone = \OC_Calendar_App::getTimezone(); // check if the calenar is enabled if (count($calendars) == 0 || !\OCP\App::isEnabled('tasks')) { return array(); } $results = array(); foreach ($calendars as $calendar) { // $calendar_entries = \OC_Calendar_Object::all($calendar['id']); $objects = \OC_Calendar_Object::all($calendar['id']); // $date = strtotime($query); // // search all calendar objects, one by one foreach ($objects as $object) { // skip non-todos if ($object['objecttype'] != 'VTODO') { continue; } if (!($vtodo = Helper::parseVTODO($object))) { continue; } $id = $object['id']; $calendarId = $object['calendarid']; // check these properties $properties = array('SUMMARY', 'DESCRIPTION', 'LOCATION', 'CATEGORIES'); foreach ($properties as $property) { $string = $vtodo->{$property}; if (stripos($string, $query) !== false) { // $results[] = new \OCA\Tasks\Controller\Task($id,$calendarId,$vtodo,$property,$query,$user_timezone); $results[] = Helper::arrayForJSON($id, $vtodo, $user_timezone, $calendarId); continue 2; } } $comments = $vtodo->COMMENT; if ($comments) { foreach ($comments as $com) { if (stripos($com->getValue(), $query) !== false) { // $results[] = new \OCA\Tasks\Controller\Task($id,$calendarId,$vtodo,'COMMENTS',$query,$user_timezone); $results[] = Helper::arrayForJSON($id, $vtodo, $user_timezone, $calendarId); continue 2; } } } } } usort($results, array($this, 'sort_completed')); return $results; }
public static function check() { if (!\OCP\App::isEnabled('files_antivirus')) { return; } // get mimetype code for directory $query = \OCP\DB::prepare('SELECT `id` FROM `*PREFIX*mimetypes` WHERE `mimetype` = ?'); $result = $query->execute(array('httpd/unix-directory')); if ($row = $result->fetchRow()) { $dir_mimetype = $row['id']; } else { $dir_mimetype = 0; } // locate files that are not checked yet $sql = 'SELECT `*PREFIX*filecache`.`fileid`, `path`, `*PREFIX*storages`.`id`' . ' FROM `*PREFIX*filecache`' . ' LEFT JOIN `*PREFIX*files_antivirus` ON `*PREFIX*files_antivirus`.`fileid` = `*PREFIX*filecache`.`fileid`' . ' JOIN `*PREFIX*storages` ON `*PREFIX*storages`.`numeric_id` = `*PREFIX*filecache`.`storage`' . ' WHERE `mimetype` != ?' . ' AND (`*PREFIX*storages`.`id` LIKE ? OR `*PREFIX*storages`.`id` LIKE ?)' . ' AND (`*PREFIX*files_antivirus`.`fileid` IS NULL OR `mtime` > `check_time`)' . ' AND `path` LIKE ?'; $stmt = \OCP\DB::prepare($sql, 5); try { $result = $stmt->execute(array($dir_mimetype, 'local::%', 'home::%', 'files/%')); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return; } } catch (\Exception $e) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return; } $serverContainer = \OC::$server; /** @var $serverContainer \OCP\IServerContainer */ $root = $serverContainer->getRootFolder(); // scan the found files while ($row = $result->fetchRow()) { $file = $root->getById($row['fileid']); // this should always work ... if (!empty($file)) { $file = $file[0]; $storage = $file->getStorage(); $path = $file->getInternalPath(); self::scan($file->getId(), $path, $storage); } else { // ... but sometimes it doesn't, try to get the storage $storage = self::getStorage($serverContainer, $row['id']); if ($storage !== null && $storage->is_dir('')) { self::scan($row['fileid'], $row['path'], $storage); } else { \OCP\Util::writeLog('files_antivirus', 'Can\'t get \\OCP\\Files\\File for id "' . $row['fileid'] . '"', \OCP\Util::ERROR); } } } }
/** * @NoAdminRequired * @NoCSRFRequired * * Shows the albums and pictures at the root folder or a message if * there are no pictures. * * This is the entry page for logged-in users accessing the app from * within ownCloud. * A TemplateResponse response uses a template from the templates folder * and parameters provided here to build the page users will see * * @return TemplateResponse */ public function index() { $appName = $this->appName; if (\OCP\App::isEnabled('gallery')) { $url = $this->urlGenerator->linkToRoute($appName . '.page.error_page', ['message' => "You need to disable the Pictures app before being able to use the Gallery+ app", 'code' => Http::STATUS_INTERNAL_SERVER_ERROR]); return new RedirectResponse($url); } else { // Parameters sent to the template $params = ['appName' => $appName]; // Will render the page using the template found in templates/index.php $response = new TemplateResponse($appName, 'index', $params); $this->addContentSecurityToResponse($response); return $response; } }
/** * Format file infos for JSON * @param \OCP\Files\FileInfo[] $fileInfos file infos */ public static function formatFileInfos($fileInfos) { $files = array(); $id = 0; foreach ($fileInfos as $i) { $entry = \OCA\Files\Helper::formatFileInfo($i); $entry['id'] = $id++; $entry['etag'] = $entry['mtime']; // add fake etag, it is only needed to identify the preview image $entry['permissions'] = \OCP\Constants::PERMISSION_READ; if (\OCP\App::isEnabled('files_encryption')) { $entry['isPreviewAvailable'] = false; } $files[] = $entry; } return $files; }
/** * @param array $arguments */ public function run($arguments) { if (!App::isEnabled('ownbackup')) { return; } $app = new Application(); $container = $app->getContainer(); /** @var BackupService $backupService */ $backupService = $container->query('OCA\\OwnBackup\\Service\\BackupService'); // check if we need a new backup if ($backupService->needNewBackup()) { // create new backup $backupService->createDBBackup(); // expiring old backups $backupService->expireOldBackups(); } }
/** * @param array $arguments */ public function run($arguments) { if (!App::isEnabled('search_lucene')) { return; } $app = new Application(); $container = $app->getContainer(); /** @var Logger $logger */ $logger = $container->query('Logger'); if (!empty($arguments['user'])) { $userId = $arguments['user']; $logger->debug('background job optimizing index for ' . $userId); $container->query('FileUtility')->setUpIndexFolder($userId); $container->query('Index')->optimizeIndex(); } else { $logger->debug('indexer job did not receive user in arguments: ' . json_encode($arguments)); } }
protected function execute(InputInterface $input, OutputInterface $output) { $username = $input->getArgument('user'); /** @var $user \OCP\IUser */ $user = $this->userManager->get($username); if (is_null($user)) { $output->writeln('<error>User does not exist</error>'); return 1; } if ($input->getOption('password-from-env')) { $password = getenv('OC_PASS'); if (!$password) { $output->writeln('<error>--password-from-env given, but OC_PASS is empty!</error>'); return 1; } } elseif ($input->isInteractive()) { /** @var $dialog \Symfony\Component\Console\Helper\DialogHelper */ $dialog = $this->getHelperSet()->get('dialog'); if (\OCP\App::isEnabled('encryption')) { $output->writeln('<error>Warning: Resetting the password when using encryption will result in data loss!</error>'); if (!$dialog->askConfirmation($output, '<question>Do you want to continue?</question>', true)) { return 1; } } $password = $dialog->askHiddenResponse($output, '<question>Enter a new password: </question>', false); $confirm = $dialog->askHiddenResponse($output, '<question>Confirm the new password: </question>', false); if ($password !== $confirm) { $output->writeln("<error>Passwords did not match!</error>"); return 1; } } else { $output->writeln("<error>Interactive input or --password-from-env is needed for entering a new password!</error>"); return 1; } $success = $user->setPassword($password); if ($success) { $output->writeln("<info>Successfully reset password for " . $username . "</info>"); } else { $output->writeln("<error>Error while resetting password!</error>"); return 1; } }
/** * @param array $arguments */ public function run($arguments) { if (!App::isEnabled('search_lucene')) { return; } $app = new Application(); $container = $app->getContainer(); /** @var Logger $logger */ $logger = $container->query('Logger'); if (isset($arguments['user'])) { $userId = $arguments['user']; $folder = $container->query('FileUtility')->setUpUserFolder($userId); if ($folder) { $fileIds = $container->query('StatusMapper')->getUnindexed(); $logger->debug('background job indexing ' . count($fileIds) . ' files for ' . $userId); $container->query('Indexer')->indexFiles($fileIds); } } else { $logger->debug('indexer job did not receive user in arguments: ' . json_encode($arguments)); } }
function search($query) { $addressbooks = Addressbook::all(\OCP\USER::getUser(), 1); if (count($addressbooks) == 0 || !\OCP\App::isEnabled('contacts')) { return array(); } $results = array(); $l = new \OC_l10n('contacts'); foreach ($addressbooks as $addressbook) { $vcards = VCard::all($addressbook['id']); foreach ($vcards as $vcard) { if (substr_count(strtolower($vcard['fullname']), strtolower($query)) > 0) { //$link = \OCP\Util::linkTo('contacts', 'index.php').'?id='.urlencode($vcard['id']); $link = 'javascript:openContact(' . $vcard['id'] . ')'; $results[] = new \OC_Search_Result($vcard['fullname'], '', $link, (string) $l->t('Contact')); //$name,$text,$link,$type } } } return $results; }
/** * Returns a list of calendars for a principal. * * Every project is an array with the following keys: * * id, a unique id that will be used by other functions to modify the * calendar. This can be the same as the uri or a database key. * * uri, which the basename of the uri with which the calendar is * accessed. * * principalUri. The owner of the calendar. Almost always the same as * principalUri passed to this method. * * Furthermore it can contain webdav properties in clark notation. A very * common one is '{DAV:}displayname'. * * @param string $principalUri * @return array */ public function getCalendarsForUser($principalUri) { $raw = OC_Calendar_Calendar::allCalendarsWherePrincipalURIIs($principalUri); $calendars = array(); foreach ($raw as $row) { $components = explode(',', $row['components']); if ($row['userid'] != OCP\USER::getUser()) { $row['uri'] = $row['uri'] . '_shared_by_' . $row['userid']; } $calendar = array('id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => 'principals/' . $row['userid'], '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag'] ? $row['ctag'] : '0', '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components)); foreach ($this->propertyMap as $xmlName => $dbName) { $calendar[$xmlName] = $row[$dbName]; } $calendars[] = $calendar; } if (\OCP\App::isEnabled('contacts')) { \OCP\Share::registerBackend('addressbook', 'OCA\\Contacts\\Share\\Addressbook', 'contact'); $app = new \OCA\Contacts\App(\OCP\User::getUser()); $calendars[] = array('id' => 'contact_birthdays', 'uri' => 'contact_birthdays', '{DAV:}displayname' => (string) OC_Calendar_App::$l10n->t('Contact birthdays'), 'principaluri' => 'principals/contact_birthdays', '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => '0', '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT'))); } return $calendars; }
/** * check if the file is stored on a system wide mount point * @param string $path relative to /data/user with leading '/' * @return boolean */ public function isSystemWideMountPoint($path) { $normalizedPath = ltrim($path, '/'); if (\OCP\App::isEnabled("files_external")) { $mounts = \OC_Mount_Config::getSystemMountPoints(); foreach ($mounts as $mount) { if ($mount['mountpoint'] == substr($normalizedPath, 0, strlen($mount['mountpoint']))) { if ($this->isMountPointApplicableToUser($mount)) { return true; } } } } return false; }
/** * Constructor * * @param array $urlParams */ public function __construct(array $urlParams = []) { parent::__construct('galleryplus', $urlParams); $container = $this->getContainer(); /** * Controllers */ $container->registerService('PageController', function (IContainer $c) { return new PageController($c->query('AppName'), $c->query('Request'), $c->query('Environment'), $c->query('OCP\\IURLGenerator'), $c->query('OCP\\IConfig')); }); $container->registerService('ConfigController', function (IContainer $c) { return new ConfigController($c->query('AppName'), $c->query('Request'), $c->query('ConfigService'), $c->query('PreviewService'), $c->query('Logger')); }); $container->registerService('ConfigPublicController', function (IContainer $c) { return new ConfigPublicController($c->query('AppName'), $c->query('Request'), $c->query('ConfigService'), $c->query('PreviewService'), $c->query('Logger')); }); $container->registerService('ConfigApiController', function (IContainer $c) { return new ConfigApiController($c->query('AppName'), $c->query('Request'), $c->query('ConfigService'), $c->query('PreviewService'), $c->query('Logger')); }); $container->registerService('FilesController', function (IContainer $c) { return new FilesController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('SearchFolderService'), $c->query('ConfigService'), $c->query('SearchMediaService'), $c->query('DownloadService'), $c->query('Logger')); }); $container->registerService('FilesPublicController', function (IContainer $c) { return new FilesPublicController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('SearchFolderService'), $c->query('ConfigService'), $c->query('SearchMediaService'), $c->query('DownloadService'), $c->query('Logger')); }); $container->registerService('FilesApiController', function (IContainer $c) { return new FilesApiController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('SearchFolderService'), $c->query('ConfigService'), $c->query('SearchMediaService'), $c->query('DownloadService'), $c->query('Logger')); }); $container->registerService('PreviewController', function (IContainer $c) { return new PreviewController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('ThumbnailService'), $c->query('PreviewService'), $c->query('DownloadService'), $c->query('EventSource'), $c->query('Logger')); }); $container->registerService('PreviewPublicController', function (IContainer $c) { return new PreviewPublicController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('ThumbnailService'), $c->query('PreviewService'), $c->query('DownloadService'), $c->query('EventSource'), $c->query('Logger')); }); $container->registerService('PreviewApiController', function (IContainer $c) { return new PreviewApiController($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IURLGenerator'), $c->query('ThumbnailService'), $c->query('PreviewService'), $c->query('DownloadService'), $c->query('EventSource'), $c->query('Logger')); }); /** * Core */ $container->registerService('OCP\\IServerContainer', function (IAppContainer $c) { return $c->getServer(); }); $container->registerService('EventSource', function (IAppContainer $c) { return new EventSource(); }); $container->registerService('Token', function (IContainer $c) { return $c->query('Request')->getParam('token'); }); $container->registerService('Session', function (IAppContainer $c) { return $c->getServer()->getSession(); }); $container->registerService('L10N', function (IAppContainer $c) { return $c->getServer()->getL10N('gallery'); // Keep the same translations }); $container->registerService('UserFolder', function (IAppContainer $c) { return $c->getServer()->getUserFolder($c->query('UserId')); }); /** * OCA */ $container->registerService('ConfigParser', function () { return new ConfigParser(); }); $container->registerService('CustomPreviewManager', function (IContainer $c) { return new Preview($c->query('OCP\\IConfig'), $c->query('OCP\\IPreview'), $c->query('Logger')); }); $container->registerService('Environment', function (IContainer $c) { return new Environment($c->query('AppName'), $c->query('UserId'), $c->query('UserFolder'), $c->query('OCP\\IUserManager'), $c->query('OCP\\IServerContainer'), $c->query('Logger')); }); /*// The same thing as above, but in OC9, hopefully. See https://github.com/owncloud/core/issues/12676 $container->registerService( 'Environment', function (IAppContainer $c) { $token = $c->query('Token'); return $c ->getServer() ->getEnvironment($token); } );*/ /** * OCA External */ if (\OCP\App::isEnabled('ocutility')) { // @codeCoverageIgnoreStart $container->registerService('UtilityContainer', function () { $app = new OcUtility(); return $app->getContainer(); }); $container->registerService('Helper', function (IContainer $c) { return $c->query('UtilityContainer')->query('OCA\\OcUtility\\Service\\Helper'); }); $container->registerService('Logger', function (IContainer $c) { return new SmarterLogger($c->query('AppName'), $c->query('OCP\\ILogger')); }); } else { // @codeCoverageIgnoreEnd $container->registerService('Logger', function (IContainer $c) { return $c->query('OCP\\ILogger'); }); } /** * Services */ $container->registerService('SearchFolderService', function (IContainer $c) { return new SearchFolderService($c->query('AppName'), $c->query('Environment'), $c->query('Logger')); }); $container->registerService('ConfigService', function (IContainer $c) { return new ConfigService($c->query('AppName'), $c->query('Environment'), $c->query('ConfigParser'), $c->query('Logger')); }); $container->registerService('SearchMediaService', function (IContainer $c) { return new SearchMediaService($c->query('AppName'), $c->query('Environment'), $c->query('Logger')); }); $container->registerService('ThumbnailService', function () { return new ThumbnailService(); }); $container->registerService('PreviewService', function (IContainer $c) { return new PreviewService($c->query('AppName'), $c->query('Environment'), $c->query('CustomPreviewManager'), $c->query('Logger')); }); $container->registerService('DownloadService', function (IContainer $c) { return new DownloadService($c->query('AppName'), $c->query('Environment'), $c->query('Logger')); }); /** * Middleware */ $container->registerService('SharingCheckMiddleware', function (IAppContainer $c) { return new SharingCheckMiddleware($c->query('AppName'), $c->query('Request'), $c->query('OCP\\IConfig'), $c->query('OCP\\AppFramework\\Utility\\IControllerMethodReflector'), $c->query('OCP\\IURLGenerator'), $c->query('Logger')); }); $container->registerService('EnvCheckMiddleware', function (IContainer $c) { return new EnvCheckMiddleware($c->query('AppName'), $c->query('Request'), $c->query('OCP\\Security\\IHasher'), $c->query('Session'), $c->query('Environment'), $c->query('OCP\\AppFramework\\Utility\\IControllerMethodReflector'), $c->query('OCP\\IURLGenerator'), $c->query('Logger')); }); // Executed in the order that it is registered $container->registerMiddleware('SharingCheckMiddleware'); $container->registerMiddleware('EnvCheckMiddleware'); }
/** * @return array|false */ public function getDirectDownload() { if (\OCP\App::isEnabled('encryption')) { return []; } /** @var \OCP\Files\Storage $storage */ list($storage, $internalPath) = $this->fileView->resolvePath($this->path); if (is_null($storage)) { return []; } return $storage->getDirectDownload($internalPath); }
/** * check if server-to-server sharing is enabled * * @param bool $incoming * @return bool */ private function isS2SEnabled($incoming = false) { $result = \OCP\App::isEnabled('files_sharing'); if ($incoming) { $result = $result && \OCA\Files_Sharing\Helper::isIncomingServer2serverShareEnabled(); } else { $result = $result && \OCA\Files_Sharing\Helper::isOutgoingServer2serverShareEnabled(); } return $result; }
/** * @brief remember the file which should be deleted and it's owner * @param array $params * @return boolean */ public static function preDelete($params) { $path = $params[\OC\Files\Filesystem::signal_param_path]; // skip this method if the trash bin is enabled or if we delete a file // outside of /data/user/files if (\OCP\App::isEnabled('files_trashbin')) { return true; } $util = new Util(new \OC_FilesystemView('/'), \OCP\USER::getUser()); list($owner, $ownerPath) = $util->getUidAndFilename($path); self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]] = array('uid' => $owner, 'path' => $ownerPath); }
OCP\JSON::checkUserExists($rootLinkItem['uid_owner']); // Setup FS with owner OC_Util::tearDownFS(); OC_Util::setupFS($rootLinkItem['uid_owner']); // The token defines the target directory (security reasons) $path = \OC\Files\Filesystem::getPath($linkItem['file_source']); $dir = sprintf("/%s/%s", $path, $publicDirectory); if (!$dir || empty($dir) || $dir === false) { OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('Unable to set upload directory.'))))); die; } $dir = rtrim($dir, '/'); } } OCP\JSON::callCheck(); if (!\OCP\App::isEnabled('files_encryption')) { // encryption app need to create keys later, so can't close too early \OC::$session->close(); } // get array with current storage stats (e.g. max file size) $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir); if (!isset($_FILES['files'])) { OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('No file was uploaded. Unknown error')), $storageStats))); exit; } foreach ($_FILES['files']['error'] as $error) { if ($error != 0) { $errors = array(UPLOAD_ERR_OK => $l->t('There is no error, the file uploaded with success'), UPLOAD_ERR_INI_SIZE => $l->t('The uploaded file exceeds the upload_max_filesize directive in php.ini: ') . ini_get('upload_max_filesize'), UPLOAD_ERR_FORM_SIZE => $l->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'), UPLOAD_ERR_PARTIAL => $l->t('The uploaded file was only partially uploaded'), UPLOAD_ERR_NO_FILE => $l->t('No file was uploaded'), UPLOAD_ERR_NO_TMP_DIR => $l->t('Missing a temporary folder'), UPLOAD_ERR_CANT_WRITE => $l->t('Failed to write to disk')); $errorMessage = $errors[$error]; \OC::$server->getLogger()->alert("Upload error: {$error} - {$errorMessage}", array('app' => 'files')); OCP\JSON::error(array('data' => array_merge(array('message' => $errorMessage), $storageStats)));
/** * @param $path * @param $size * @return bool */ public function postFileSize($path, $size, $fileInfo = null) { $view = new \OC_FilesystemView('/'); $userId = Helper::getUser($path); $util = new Util($view, $userId); // if encryption is no longer enabled or if the files aren't migrated yet // we return the default file size if (!\OCP\App::isEnabled('files_encryption') || $util->getMigrationStatus() !== Util::MIGRATION_COMPLETED) { return $size; } // if path is a folder do nothing if ($view->is_dir($path)) { $proxyState = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $fileInfo = $view->getFileInfo($path); \OC_FileProxy::$enabled = $proxyState; if (isset($fileInfo['unencrypted_size']) && $fileInfo['unencrypted_size'] > 0) { return $fileInfo['unencrypted_size']; } return $size; } // get relative path $relativePath = \OCA\Encryption\Helper::stripUserFilesPath($path); // if path is empty we cannot resolve anything if (empty($relativePath)) { return $size; } // get file info from database/cache if not .part file if (empty($fileInfo) && !Helper::isPartialFilePath($path)) { $proxyState = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $fileInfo = $view->getFileInfo($path); \OC_FileProxy::$enabled = $proxyState; } // if file is encrypted return real file size if (isset($fileInfo['encrypted']) && $fileInfo['encrypted'] === true) { // try to fix unencrypted file size if it doesn't look plausible if ((int) $fileInfo['size'] > 0 && (int) $fileInfo['unencrypted_size'] === 0) { $fixSize = $util->getFileSize($path); $fileInfo['unencrypted_size'] = $fixSize; // put file info if not .part file if (!Helper::isPartialFilePath($relativePath)) { $view->putFileInfo($path, $fileInfo); } } $size = $fileInfo['unencrypted_size']; } else { // self healing if file was removed from file cache if (!is_array($fileInfo)) { $fileInfo = array(); } $fixSize = $util->getFileSize($path); if ($fixSize > 0) { $size = $fixSize; $fileInfo['encrypted'] = true; $fileInfo['unencrypted_size'] = $size; // put file info if not .part file if (!Helper::isPartialFilePath($relativePath)) { $view->putFileInfo($path, $fileInfo); } } } return $size; }
/** * @param \OC\Files\View $view */ private static function deleteEncryptionKeys($view, $file, $filename, $timestamp) { $size = 0; if (\OCP\App::isEnabled('files_encryption')) { $user = \OCP\User::getUser(); if ($view->is_dir('/files_trashbin/files/' . $file)) { $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename); $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename); } else { $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename . '.key'); $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename . '.' . $user . '.shareKey'); } if ($timestamp) { $keyfile .= '.d' . $timestamp; $sharekeys .= '.d' . $timestamp; } if ($view->file_exists($keyfile)) { if ($view->is_dir($keyfile)) { $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $keyfile)); $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $sharekeys)); } else { $size += $view->filesize($keyfile); $size += $view->filesize($sharekeys); } $view->unlink($keyfile); $view->unlink($sharekeys); } } return $size; }