public static function onError($number, $message, $file, $line) { if (error_reporting() === 0) { return; } $msg = $message . ' at ' . $file . '#' . $line; self::$logger->error(self::removePassword($msg), array('app' => 'PHP')); }
/** * Log error message and return a response which can be displayed to the user * * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param \Exception $exception * @return JSONResponse */ public function afterException($controller, $methodName, \Exception $exception) { $this->logger->error($exception->getMessage(), ['app' => $this->appName]); if ($exception instanceof HintException) { $message = $exception->getHint(); } else { $message = $exception->getMessage(); } return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); }
/** * Event handler for the 'schedule' event. * * @param ITip\Message $iTipMessage * @return void */ function schedule(ITip\Message $iTipMessage) { // Not sending any emails if the system considers the update // insignificant. if (!$iTipMessage->significantChange) { if (!$iTipMessage->scheduleStatus) { $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email'; } return; } $summary = $iTipMessage->message->VEVENT->SUMMARY; if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') { return; } if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') { return; } $sender = substr($iTipMessage->sender, 7); $recipient = substr($iTipMessage->recipient, 7); $senderName = $iTipMessage->senderName ? $iTipMessage->senderName : null; $recipientName = $iTipMessage->recipientName ? $iTipMessage->recipientName : null; $subject = 'SabreDAV iTIP message'; switch (strtoupper($iTipMessage->method)) { case 'REPLY': $subject = 'Re: ' . $summary; break; case 'REQUEST': $subject = $summary; break; case 'CANCEL': $subject = 'Cancelled: ' . $summary; break; } $contentType = 'text/calendar; charset=UTF-8; method=' . $iTipMessage->method; $message = $this->mailer->createMessage(); $message->setReplyTo([$sender => $senderName])->setTo([$recipient => $recipientName])->setSubject($subject)->setBody($iTipMessage->message->serialize(), $contentType); try { $failed = $this->mailer->send($message); if ($failed) { $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip'; } catch (\Exception $ex) { $this->logger->logException($ex, ['app' => 'dav']); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } }
/** * @inheritdoc */ public function getFile($size) { $ext = $this->getExtension(); if ($size === -1) { $path = 'avatar.' . $ext; } else { $path = 'avatar.' . $size . '.' . $ext; } try { $file = $this->folder->get($path); } catch (NotFoundException $e) { if ($size <= 0) { throw new NotFoundException(); } $avatar = new OC_Image(); /** @var File $file */ $file = $this->folder->get('avatar.' . $ext); $avatar->loadFromData($file->getContent()); if ($size !== -1) { $avatar->resize($size); } try { $file = $this->folder->newFile($path); $file->putContent($avatar->data()); } catch (NotPermittedException $e) { $this->logger->error('Failed to save avatar for ' . $this->user->getUID()); } } return $file; }
/** * Get the download url for an application from the OCS server * @param string $id * @param array $targetVersion The target ownCloud version * @return array|null an array of application data or null */ public function getApplicationDownload($id, array $targetVersion) { if (!$this->isAppStoreEnabled()) { return null; } $url = $this->getAppStoreUrl() . '/content/download/' . urlencode($id) . '/1'; $client = $this->httpClientService->newClient(); try { $response = $client->get($url, ['timeout' => 5, 'query' => ['version' => implode('x', $targetVersion)]]); } catch (\Exception $e) { $this->logger->error(sprintf('Could not get application download URL: %s', $e->getMessage()), ['app' => 'core']); return null; } $data = $this->loadData($response->getBody(), 'application download URL'); if ($data === null) { return null; } $tmp = $data->data->content; $app = []; if (isset($tmp->downloadlink)) { $app['downloadlink'] = (string) $tmp->downloadlink; } else { $app['downloadlink'] = ''; } return $app; }
/** * @NoAdminRequired * * @param string $username * @param string $password * @param array $groups * @param string $email * @return DataResponse */ public function create($username, $password, array $groups = array(), $email = '') { if ($email !== '' && !$this->mail->validateAddress($email)) { return new DataResponse(array('message' => (string) $this->l10n->t('Invalid mail address')), Http::STATUS_UNPROCESSABLE_ENTITY); } if (!$this->isAdmin) { $userId = $this->userSession->getUser()->getUID(); if (!empty($groups)) { foreach ($groups as $key => $group) { if (!$this->subAdminFactory->isGroupAccessible($userId, $group)) { unset($groups[$key]); } } } if (empty($groups)) { $groups = $this->subAdminFactory->getSubAdminsOfGroups($userId); } } if ($this->userManager->userExists($username)) { return new DataResponse(array('message' => (string) $this->l10n->t('A user with that name already exists.')), Http::STATUS_CONFLICT); } try { $user = $this->userManager->createUser($username, $password); } catch (\Exception $exception) { return new DataResponse(array('message' => (string) $this->l10n->t('Unable to create user.')), Http::STATUS_FORBIDDEN); } if ($user instanceof User) { if ($groups !== null) { foreach ($groups as $groupName) { $group = $this->groupManager->get($groupName); if (empty($group)) { $group = $this->groupManager->createGroup($groupName); } $group->addUser($user); } } /** * Send new user mail only if a mail is set */ if ($email !== '') { $this->config->setUserValue($username, 'settings', 'email', $email); // data for the mail template $mailData = array('username' => $username, 'url' => $this->urlGenerator->getAbsoluteURL('/')); $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank'); $mailContent = $mail->render(); $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank'); $plainTextMailContent = $mail->render(); $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]); try { $this->mail->send($email, $username, $subject, $mailContent, $this->fromMailAddress, $this->defaults->getName(), 1, $plainTextMailContent); } catch (\Exception $e) { $this->log->error("Can't send new user mail to {$email}: " . $e->getMessage(), array('app' => 'settings')); } } // fetch users groups $userGroups = $this->groupManager->getUserGroupIds($user); return new DataResponse($this->formatUserForIndex($user, $userGroups), Http::STATUS_CREATED); } return new DataResponse(array('message' => (string) $this->l10n->t('Unable to create user.')), Http::STATUS_FORBIDDEN); }
protected function run($argument) { $target = $argument['url']; $source = $this->urlGenerator->getAbsoluteURL('/'); $source = rtrim($source, '/'); $token = $argument['token']; try { $result = $this->httpClient->get($target . $this->endPoint, ['query' => ['url' => $source, 'token' => $token], 'timeout' => 3, 'connect_timeout' => 3]); $status = $result->getStatusCode(); } catch (ClientException $e) { $status = $e->getCode(); $this->logger->logException($e); } // if we received a unexpected response we try again later if ($status !== Http::STATUS_OK && $status !== Http::STATUS_FORBIDDEN) { $this->jobList->add('OCA\\Federation\\BackgroundJob\\GetSharedSecret', $argument); } else { // reset token if we received a valid response $this->dbHandler->addToken($target, ''); } if ($status === Http::STATUS_OK) { $body = $result->getBody(); $result = json_decode($body, true); if (isset($result['ocs']['data']['sharedSecret'])) { $this->trustedServers->addSharedSecret($target, $result['ocs']['data']['sharedSecret']); } else { $this->logger->error('remote server "' . $target . '"" does not return a valid shared secret', ['app' => 'federation']); $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE); } } }
/** * @param ICalendar $calendar */ public function __construct(ICalendar $calendar) { $this->calendar = $calendar; $backend = $this->calendar->getBackend(); if (!$backend instanceof IBackend) { $identifier = implode('::', [$this->calendar->getUserId(), '?', $this->calendar->getPrivateUri()]); $this->logger->error('Backend of calendar \'' . $identifier . '\' not found'); } else { $this->cache = $backend->getObjectCache($calendar); try { $this->objectAPI = $backend->getObjectAPI($calendar); } catch (BackendUtils\Exception $ex) { //TODO } } }
/** * @NoAdminRequired * * @param int $accountId * @param string $subject * @param string $body * @param string $to * @param string $cc * @param string $bcc * @param int $uid * @param string $messageId * @return JSONResponse */ public function draft($accountId, $subject, $body, $to, $cc, $bcc, $uid, $messageId) { if (is_null($uid)) { $this->logger->info("Saving a new draft in account <{$accountId}>"); } else { $this->logger->info("Updating draft <{$uid}> in account <{$accountId}>"); } $account = $this->accountService->find($this->currentUserId, $accountId); if ($account instanceof UnifiedAccount) { list($account) = $account->resolve($messageId); } if (!$account instanceof Account) { return new JSONResponse(array('message' => 'Invalid account'), Http::STATUS_BAD_REQUEST); } $message = $account->newMessage(); $message->setTo(Message::parseAddressList($to)); $message->setSubject($subject ?: ''); $message->setFrom($account->getEMailAddress()); $message->setCC(Message::parseAddressList($cc)); $message->setBcc(Message::parseAddressList($bcc)); $message->setContent($body); // create transport and save message try { $newUID = $account->saveDraft($message, $uid); } catch (\Horde_Exception $ex) { $this->logger->error('Saving draft failed: ' . $ex->getMessage()); return new JSONResponse(['message' => $ex->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR); } return new JSONResponse(['uid' => $newUID]); }
/** * @param string $dir * @throws \OC\ForbiddenException */ public function scan($dir = '') { if (!Filesystem::isValidPath($dir)) { throw new \InvalidArgumentException('Invalid path to scan'); } $mounts = $this->getMounts($dir); foreach ($mounts as $mount) { if (is_null($mount->getStorage())) { continue; } $storage = $mount->getStorage(); // if the home storage isn't writable then the scanner is run as the wrong user if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') and (!$storage->isCreatable('') or !$storage->isCreatable('files'))) { throw new ForbiddenException(); } $relativePath = $mount->getInternalPath($dir); $scanner = $storage->getScanner(); $scanner->setUseTransactions(false); $this->attachListener($mount); $isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider; if (!$isDbLocking) { $this->db->beginTransaction(); } try { $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE); } catch (StorageNotAvailableException $e) { $this->logger->error('Storage ' . $storage->getId() . ' not available'); $this->logger->logException($e); $this->emit('\\OC\\Files\\Utils\\Scanner', 'StorageNotAvailable', [$e]); } if (!$isDbLocking) { $this->db->commit(); } } }
private function addToCache(ICachedMountInfo $mount) { if ($mount->getStorageId() !== -1) { $this->connection->insertIfNotExist('*PREFIX*mounts', ['storage_id' => $mount->getStorageId(), 'root_id' => $mount->getRootId(), 'user_id' => $mount->getUser()->getUID(), 'mount_point' => $mount->getMountPoint()], ['root_id', 'user_id']); } else { $this->logger->error('Error getting storage info for mount at ' . $mount->getMountPoint()); } }
/** * @NoAdminRequired * * @param int $accountId * @param string $subject * @param string $body * @param string $to * @param string $cc * @param string $bcc * @param int $uid * @param string $messageId * @return JSONResponse */ public function draft($accountId, $subject, $body, $to, $cc, $bcc, $uid, $messageId) { if (is_null($uid)) { $this->logger->info("Saving a new draft in account <{$accountId}>"); } else { $this->logger->info("Updating draft <{$uid}> in account <{$accountId}>"); } $account = $this->accountService->find($this->currentUserId, $accountId); if ($account instanceof UnifiedAccount) { list($account) = $account->resolve($messageId); } if (!$account instanceof Account) { return new JSONResponse(array('message' => 'Invalid account'), Http::STATUS_BAD_REQUEST); } // get sender data $headers = []; $from = new Horde_Mail_Rfc822_Address($account->getEMailAddress()); $from->personal = $account->getName(); $headers['From'] = $from; $headers['Subject'] = $subject; if (trim($cc) !== '') { $headers['Cc'] = trim($cc); } if (trim($bcc) !== '') { $headers['Bcc'] = trim($bcc); } $headers['To'] = $to; $headers['Date'] = Horde_Mime_Headers_Date::create(); // build mime body $mail = new Horde_Mime_Mail(); $mail->addHeaders($headers); $bodyPart = new Horde_Mime_Part(); $bodyPart->appendContents($body, ['encoding' => \Horde_Mime_Part::ENCODE_8BIT]); $mail->setBasePart($bodyPart); // create transport and save message try { // save the message in the drafts folder $draftsFolder = $account->getDraftsFolder(); /** @var resource $raw */ $raw = $mail->getRaw(); $raw = stream_get_contents($raw); $newUid = $draftsFolder->saveDraft($raw); // delete old version if one exists if (!is_null($uid)) { $folderId = $draftsFolder->getFolderId(); $this->logger->debug("deleting outdated draft <{$uid}> in folder <{$folderId}>"); $draftsFolder->setMessageFlag($uid, \Horde_Imap_Client::FLAG_DELETED, true); $account->deleteDraft($uid); $this->logger->debug("draft <{$uid}> deleted"); } } catch (\Horde_Exception $ex) { $this->logger->error('Saving draft failed: ' . $ex->getMessage()); return new JSONResponse(['message' => $ex->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR); } return new JSONResponse(['uid' => $newUid]); }
/** * @param string $dir * @throws \OC\ForbiddenException */ public function scan($dir = '') { if (!Filesystem::isValidPath($dir)) { throw new \InvalidArgumentException('Invalid path to scan'); } $mounts = $this->getMounts($dir); foreach ($mounts as $mount) { if (is_null($mount->getStorage())) { continue; } $storage = $mount->getStorage(); // if the home storage isn't writable then the scanner is run as the wrong user if ($storage->instanceOfStorage('\\OC\\Files\\Storage\\Home') and (!$storage->isCreatable('') or !$storage->isCreatable('files'))) { if ($storage->file_exists('') or $storage->getCache()->inCache('')) { throw new ForbiddenException(); } else { // if the root exists in neither the cache nor the storage the user isn't setup yet break; } } $relativePath = $mount->getInternalPath($dir); $scanner = $storage->getScanner(); $scanner->setUseTransactions(false); $this->attachListener($mount); $isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider; $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'removeFromCache', function ($path) use($storage) { $this->triggerPropagator($storage, $path); }); $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'updateCache', function ($path) use($storage) { $this->triggerPropagator($storage, $path); }); $scanner->listen('\\OC\\Files\\Cache\\Scanner', 'addToCache', function ($path) use($storage) { $this->triggerPropagator($storage, $path); }); if (!$isDbLocking) { $this->db->beginTransaction(); } try { $storage->getPropagator()->beginBatch(); $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE); $cache = $storage->getCache(); if ($cache instanceof Cache) { // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner $cache->correctFolderSize($relativePath); } $storage->getPropagator()->commitBatch(); } catch (StorageNotAvailableException $e) { $this->logger->error('Storage ' . $storage->getId() . ' not available'); $this->logger->logException($e); $this->emit('\\OC\\Files\\Utils\\Scanner', 'StorageNotAvailable', [$e]); } if (!$isDbLocking) { $this->db->commit(); } } }
/** * copy file between two storages * * @param Storage $sourceStorage * @param string $sourceInternalPath * @param string $targetInternalPath * @param bool $preserveMtime * @param bool $isRename * @return bool */ private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) { // first copy the keys that we reuse the existing file key on the target location // and don't create a new one which would break versions for example. $mount = $this->mountManager->findByStorageId($sourceStorage->getId()); if (count($mount) === 1) { $mountPoint = $mount[0]->getMountPoint(); $source = $mountPoint . '/' . $sourceInternalPath; $target = $this->getFullPath($targetInternalPath); $this->copyKeys($source, $target); } else { $this->logger->error('Could not find mount point, can\'t keep encryption keys'); } if ($sourceStorage->is_dir($sourceInternalPath)) { $dh = $sourceStorage->opendir($sourceInternalPath); $result = $this->mkdir($targetInternalPath); if (is_resource($dh)) { while ($result and ($file = readdir($dh)) !== false) { if (!Filesystem::isIgnoredDir($file)) { $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file); } } } } else { try { $source = $sourceStorage->fopen($sourceInternalPath, 'r'); $target = $this->fopen($targetInternalPath, 'w'); list(, $result) = \OC_Helper::streamCopy($source, $target); fclose($source); fclose($target); } catch (\Exception $e) { fclose($source); fclose($target); throw $e; } if ($result) { if ($preserveMtime) { $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath)); } $isEncrypted = $this->encryptionManager->isEnabled() && $this->mount->getOption('encrypt', true) ? 1 : 0; // in case of a rename we need to manipulate the source cache because // this information will be kept for the new target if ($isRename) { $sourceStorage->getCache()->put($sourceInternalPath, ['encrypted' => $isEncrypted]); } else { $this->getCache()->put($targetInternalPath, ['encrypted' => $isEncrypted]); } } else { // delete partially written target file $this->unlink($targetInternalPath); // delete cache entry that was created by fopen $this->getCache()->remove($targetInternalPath); } } return (bool) $result; }
/** * decrypt data * * @param string $data you want to decrypt * @param int $position * @return string decrypted data * @throws DecryptionFailedException */ public function decrypt($data, $position = 0) { if (empty($this->fileKey)) { $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'; $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); $this->logger->error($msg); throw new DecryptionFailedException($msg, $hint); } return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position); }
/** * @param string $plainContent * @param string $iv * @param string $passPhrase * @param string $cipher * @return string * @throws EncryptionFailedException */ private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) { $encryptedContent = openssl_encrypt($plainContent, $cipher, $passPhrase, false, $iv); if (!$encryptedContent) { $error = 'Encryption (symmetric) of content failed'; $this->logger->error($error . openssl_error_string(), ['app' => 'encryption']); throw new EncryptionFailedException($error); } return $encryptedContent; }
/** * Get all mountpoints applicable for the user and check for shares where we need to update the etags * * @param \OCP\IUser $user * @param \OCP\Files\Storage\IStorageFactory $storageFactory * @return \OCP\Files\Mount\IMountPoint[] */ public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) { $shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1); $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1)); // filter out excluded shares and group shares that includes self $shares = array_filter($shares, function (\OCP\Share\IShare $share) use($user) { return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID(); }); $mounts = []; foreach ($shares as $share) { try { $mounts[] = new SharedMount('\\OC\\Files\\Storage\\Shared', $mounts, ['user' => $user->getUID(), 'newShare' => $share], $storageFactory); } catch (\Exception $e) { $this->logger->logException($e); $this->logger->error('Error while trying to create shared mount'); } } // array_filter removes the null values from the array return array_filter($mounts); }
/** * @param JobList $jobList * @param ILogger $logger */ public function execute($jobList, ILogger $logger = null) { $jobList->setLastRun($this); try { $this->run($this->argument); } catch (\Exception $e) { if ($logger) { $logger->error('Error while running background job: ' . $e->getMessage()); } } }
/** * Finds the resources and adds them to the list * * @param array $resources */ public function find($resources) { foreach ($resources as $resource) { try { $this->doFind($resource); } catch (ResourceNotFoundException $e) { $resourceApp = substr($resource, 0, strpos($resource, '/')); $this->logger->error('Could not find resource file "' . $e->getResourcePath() . '"', ['app' => $resourceApp]); } } if (!empty($this->theme)) { foreach ($resources as $resource) { try { $this->doFindTheme($resource); } catch (ResourceNotFoundException $e) { $resourceApp = substr($resource, 0, strpos($resource, '/')); $this->logger->error('Could not find resource file "' . $e->getResourcePath() . '"', ['app' => $resourceApp]); } } } }
/** * @param array $fileIds * @param \OC_EventSource $eventSource */ public function indexFiles(array $fileIds, \OC_EventSource $eventSource = null) { foreach ($fileIds as $id) { $fileStatus = $this->mapper->getOrCreateFromFileId($id); try { // before we start mark the file as error so we know there // was a problem in case the php execution dies and we don't try // the file again $this->mapper->markError($fileStatus); $nodes = $this->server->getUserFolder()->getById($id); // getById can return more than one id because the containing storage might be mounted more than once // Since we only want to index the file once, we only use the first entry if (isset($nodes[0])) { /** @var File $node */ $node = $nodes[0]; } else { throw new VanishedException($id); } if (!$node instanceof File) { throw new NotIndexedException(); } $path = $node->getPath(); foreach ($this->skippedDirs as $skippedDir) { if (strpos($path, '/' . $skippedDir . '/') !== false || strrpos($path, '/' . $skippedDir) === strlen($path) - (strlen($skippedDir) + 1)) { throw new SkippedException('skipping file ' . $id . ':' . $path); } } if ($eventSource) { $eventSource->send('indexing', $path); } if ($this->indexFile($node, false)) { $this->mapper->markIndexed($fileStatus); } } catch (VanishedException $e) { $this->mapper->markVanished($fileStatus); } catch (NotIndexedException $e) { $this->mapper->markUnIndexed($fileStatus); } catch (SkippedException $e) { $this->mapper->markSkipped($fileStatus); $this->logger->debug($e->getMessage()); } catch (\Exception $e) { //sqlite might report database locked errors when stock filescan is in progress //this also catches db locked exception that might come up when using sqlite $this->logger->error($e->getMessage() . ' Trace:\\n' . $e->getTraceAsString()); $this->mapper->markError($fileStatus); // TODO Add UI to trigger rescan of files with status 'E'rror? if ($eventSource) { $eventSource->send('error', $e->getMessage()); } } } $this->index->commit(); }
/** * Shrinks larger images to fit within specified boundaries while preserving ratio. * * @param integer $maxWidth * @param integer $maxHeight * @return bool */ public function scaleDownToFit($maxWidth, $maxHeight) { if (!$this->valid()) { $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); return false; } $widthOrig = imageSX($this->resource); $heightOrig = imageSY($this->resource); if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) { return $this->fitIn($maxWidth, $maxHeight); } return false; }
/** * save text file * * @NoAdminRequired * * @param string $path * @param string $filecontents * @param integer $mtime * @return DataResponse */ public function save($path, $filecontents, $mtime) { try { if ($path !== '' && (is_integer($mtime) && $mtime > 0)) { // Get file mtime $filemtime = $this->view->filemtime($path); if ($mtime !== $filemtime) { // Then the file has changed since opening $this->logger->error('File: ' . $path . ' modified since opening.', ['app' => 'files_texteditor']); return new DataResponse(['message' => $this->l->t('Cannot save file as it has been modified since opening')], Http::STATUS_BAD_REQUEST); } else { // File same as when opened, save file if ($this->view->isUpdatable($path)) { $filecontents = iconv(mb_detect_encoding($filecontents), "UTF-8", $filecontents); try { $this->view->file_put_contents($path, $filecontents); } catch (LockedException $e) { $message = (string) $this->l->t('The file is locked.'); return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST); } catch (ForbiddenException $e) { return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); } // Clear statcache clearstatcache(); // Get new mtime $newmtime = $this->view->filemtime($path); $newsize = $this->view->filesize($path); return new DataResponse(['mtime' => $newmtime, 'size' => $newsize], Http::STATUS_OK); } else { // Not writeable! $this->logger->error('User does not have permission to write to file: ' . $path, ['app' => 'files_texteditor']); return new DataResponse(['message' => $this->l->t('Insufficient permissions')], Http::STATUS_BAD_REQUEST); } } } else { if ($path === '') { $this->logger->error('No file path supplied'); return new DataResponse(['message' => $this->l->t('File path not supplied')], Http::STATUS_BAD_REQUEST); } else { $this->logger->error('No file mtime supplied', ['app' => 'files_texteditor']); return new DataResponse(['message' => $this->l->t('File mtime not supplied')], Http::STATUS_BAD_REQUEST); } } } catch (HintException $e) { $message = (string) $e->getHint(); return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST); } catch (\Exception $e) { $message = (string) $this->l->t('An internal server error occurred.'); return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST); } }
/** * Resizes the image to fit within a boundary while preserving ratio. * * @param integer $maxWidth * @param integer $maxHeight * @return bool */ public function fitIn($maxWidth, $maxHeight) { if (!$this->valid()) { $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core')); return false; } $widthOrig = imageSX($this->resource); $heightOrig = imageSY($this->resource); $ratio = $widthOrig / $heightOrig; $newWidth = min($maxWidth, $ratio * $maxHeight); $newHeight = min($maxHeight, $maxWidth / $ratio); $this->preciseResize(round($newWidth), round($newHeight)); return true; }
/** * check if URL point to a ownCloud server * * @param string $url * @return bool */ public function isOwnCloudServer($url) { $isValidOwnCloud = false; $client = $this->httpClientService->newClient(); try { $result = $client->get($url . '/status.php', ['timeout' => 3, 'connect_timeout' => 3]); if ($result->getStatusCode() === Http::STATUS_OK) { $isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody()); } } catch (\Exception $e) { $this->logger->error($e->getMessage(), ['app' => 'federation']); return false; } return $isValidOwnCloud; }
/** * Change a user's encryption passphrase * * @param array $params keys: uid, password * @return boolean|null */ public function setPassphrase($params) { // Get existing decrypted private key $privateKey = $this->session->getPrivateKey(); $user = $this->user->getUser(); // current logged in user changes his own password if ($user && $params['uid'] === $user->getUID() && $privateKey) { // Encrypt private key with new user pwd as passphrase $encryptedPrivateKey = $this->crypt->encryptPrivateKey($privateKey, $params['password'], $params['uid']); // Save private key if ($encryptedPrivateKey) { $this->keyManager->setPrivateKey($this->user->getUser()->getUID(), $this->crypt->generateHeader() . $encryptedPrivateKey); } else { $this->logger->error('Encryption could not update users encryption password'); } // NOTE: Session does not need to be updated as the // private key has not changed, only the passphrase // used to decrypt it has changed } else { // admin changed the password for a different user, create new keys and re-encrypt file keys $user = $params['uid']; $this->initMountPoints($user); $recoveryPassword = isset($params['recoveryPassword']) ? $params['recoveryPassword'] : null; // we generate new keys if... // ...we have a recovery password and the user enabled the recovery key // ...encryption was activated for the first time (no keys exists) // ...the user doesn't have any files if ($this->recovery->isRecoveryEnabledForUser($user) && $recoveryPassword || !$this->keyManager->userHasKeys($user) || !$this->util->userHasFiles($user)) { // backup old keys //$this->backupAllKeys('recovery'); $newUserPassword = $params['password']; $keyPair = $this->crypt->createKeyPair(); // Save public key $this->keyManager->setPublicKey($user, $keyPair['publicKey']); // Encrypt private key with new password $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $newUserPassword, $user); if ($encryptedKey) { $this->keyManager->setPrivateKey($user, $this->crypt->generateHeader() . $encryptedKey); if ($recoveryPassword) { // if recovery key is set we can re-encrypt the key files $this->recovery->recoverUsersFiles($recoveryPassword, $user); } } else { $this->logger->error('Encryption Could not update users encryption password'); } } } }
/** * generate initialization vector * * @return string * @throws GenericEncryptionException */ private function generateIv() { $random = openssl_random_pseudo_bytes(12, $strong); if ($random) { if (!$strong) { // If OpenSSL indicates randomness is insecure log error $this->logger->error('Encryption Library: Insecure symmetric key was generated using openssl_random_psudo_bytes()', ['app' => 'encryption']); } /* * We encode the iv purely for string manipulation * purposes -it gets decoded before use */ return base64_encode($random); } // If we ever get here we've failed anyway no need for an else throw new GenericEncryptionException('Generating IV Failed'); }
/** * @return OC_OCS_Result */ public function addUser() { $userId = isset($_POST['userid']) ? $_POST['userid'] : null; $password = isset($_POST['password']) ? $_POST['password'] : null; if ($this->userManager->userExists($userId)) { $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); return new OC_OCS_Result(null, 102, 'User already exists'); } else { try { $this->userManager->createUser($userId, $password); $this->logger->info('Successful addUser call with userid: ' . $_POST['userid'], ['app' => 'ocs_api']); return new OC_OCS_Result(null, 100); } catch (\Exception $e) { $this->logger->error('Failed addUser attempt with exception: ' . $e->getMessage(), ['app' => 'ocs_api']); return new OC_OCS_Result(null, 101, 'Bad request'); } } }
/** * @return OC_OCS_Result */ public function addUser() { $userId = isset($_POST['userid']) ? $_POST['userid'] : null; $password = isset($_POST['password']) ? $_POST['password'] : null; $groups = isset($_POST['groups']) ? $_POST['groups'] : null; $user = $this->userSession->getUser(); $isAdmin = $this->groupManager->isAdmin($user->getUID()); $subAdminManager = $this->groupManager->getSubAdmin(); if (!$isAdmin && !$subAdminManager->isSubAdmin($user)) { return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED); } if ($this->userManager->userExists($userId)) { $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); return new OC_OCS_Result(null, 102, 'User already exists'); } if (is_array($groups)) { foreach ($groups as $group) { if (!$this->groupManager->groupExists($group)) { return new OC_OCS_Result(null, 104, 'group ' . $group . ' does not exist'); } if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { return new OC_OCS_Result(null, 105, 'insufficient privileges for group ' . $group); } } } else { if (!$isAdmin) { return new OC_OCS_Result(null, 106, 'no group specified (required for subadmins)'); } } try { $newUser = $this->userManager->createUser($userId, $password); $this->logger->info('Successful addUser call with userid: ' . $userId, ['app' => 'ocs_api']); if (is_array($groups)) { foreach ($groups as $group) { $this->groupManager->get($group)->addUser($newUser); $this->logger->info('Added userid ' . $userId . ' to group ' . $group, ['app' => 'ocs_api']); } } return new OC_OCS_Result(null, 100); } catch (\Exception $e) { $this->logger->error('Failed addUser attempt with exception: ' . $e->getMessage(), ['app' => 'ocs_api']); return new OC_OCS_Result(null, 101, 'Bad request'); } }
/** * create shared secret and return it * * @return \OC_OCS_Result */ public function getSharedSecret() { $url = $this->request->getParam('url'); $token = $this->request->getParam('token'); if ($this->trustedServers->isTrustedServer($url) === false) { $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']); return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN); } if ($this->isValidToken($url, $token) === false) { $expectedToken = $this->dbHandler->getToken($url); $this->logger->error('remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "' . $expectedToken . '") while getting shared secret', ['app' => 'federation']); return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN); } $sharedSecret = $this->secureRandom->generate(32); $this->trustedServers->addSharedSecret($url, $sharedSecret); // reset token after the exchange of the shared secret was successful $this->dbHandler->addToken($url, ''); return new \OC_OCS_Result(['sharedSecret' => $sharedSecret], Http::STATUS_OK); }
/** * inform recipient about public link share * * @param string $recipient recipient email address * @param string $filename the shared file * @param string $link the public link * @param int $expiration expiration date (timestamp) * @return array $result of failed recipients */ public function sendLinkShareMail($recipient, $filename, $link, $expiration) { $subject = (string) $this->l->t('%s shared »%s« with you', [$this->senderDisplayName, $filename]); list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration); try { $message = $this->mailer->createMessage(); $message->setSubject($subject); $message->setTo([$recipient]); $message->setHtmlBody($htmlBody); $message->setPlainBody($textBody); $message->setFrom([\OCP\Util::getDefaultEmailAddress('sharing-noreply') => (string) $this->l->t('%s via %s', [$this->senderDisplayName, $this->defaults->getName()])]); if (!is_null($this->replyTo)) { $message->setReplyTo([$this->replyTo]); } return $this->mailer->send($message); } catch (\Exception $e) { $this->logger->error("Can't send mail with public link to {$recipient}: " . $e->getMessage(), ['app' => 'sharing']); return [$recipient]; } }