/** * Deleting orphaned user tag mappings * * @return int Number of deleted entries */ protected function cleanUserTags() { $subQuery = $this->connection->getQueryBuilder(); $subQuery->select($subQuery->expr()->literal('1'))->from('filecache', 'f')->where($subQuery->expr()->eq('objid', 'f.fileid')); $query = $this->connection->getQueryBuilder(); $deletedEntries = $query->delete('vcategory_to_object')->where($query->expr()->eq('type', $query->expr()->literal('files')))->andWhere($query->expr()->isNull($query->createFunction('(' . $subQuery->getSql() . ')')))->execute(); $this->logger->debug("{$deletedEntries} orphaned user tag relations deleted", ['app' => 'DeleteOrphanedTagsJob']); return $deletedEntries; }
/** * Deleting orphaned comment read markers * * @return int Number of deleted entries */ protected function cleanCommentMarkers() { $qb = $this->connection->getQueryBuilder(); $deletedEntries = $this->cleanUp('comments_read_markers', $qb->expr()->castColumn('object_id', IQueryBuilder::PARAM_INT), 'object_type'); $this->logger->debug("{$deletedEntries} orphaned comment read marks deleted", ['app' => 'DeleteOrphanedItems']); return $deletedEntries; }
/** * @NoAdminRequired * * @param string $accountName * @param string $emailAddress * @param string $password * @param string $imapHost * @param int $imapPort * @param string $imapSslMode * @param string $imapUser * @param string $imapPassword * @param string $smtpHost * @param int $smtpPort * @param string $smtpSslMode * @param string $smtpUser * @param string $smtpPassword * @param bool $autoDetect * @return JSONResponse */ public function create($accountName, $emailAddress, $password, $imapHost, $imapPort, $imapSslMode, $imapUser, $imapPassword, $smtpHost, $smtpPort, $smtpSslMode, $smtpUser, $smtpPassword, $autoDetect) { try { if ($autoDetect) { $this->logger->info('setting up auto detected account'); $newAccount = $this->autoConfig->createAutoDetected($emailAddress, $password, $accountName); } else { $this->logger->info('Setting up manually configured account'); $newAccount = new MailAccount(['accountName' => $accountName, 'emailAddress' => $emailAddress, 'imapHost' => $imapHost, 'imapPort' => $imapPort, 'imapSslMode' => $imapSslMode, 'imapUser' => $imapUser, 'imapPassword' => $imapPassword, 'smtpHost' => $smtpHost, 'smtpPort' => $smtpPort, 'smtpSslMode' => $smtpSslMode, 'smtpUser' => $smtpUser, 'smtpPassword' => $smtpPassword]); $newAccount->setUserId($this->currentUserId); $newAccount->setInboundPassword($this->crypto->encrypt($newAccount->getInboundPassword())); $newAccount->setOutboundPassword($this->crypto->encrypt($newAccount->getOutboundPassword())); $a = new Account($newAccount); $this->logger->debug('Connecting to account {account}', ['account' => $newAccount->getEmail()]); $a->testConnectivity(); } if ($newAccount) { $this->accountService->save($newAccount); $this->logger->debug("account created " . $newAccount->getId()); return new JSONResponse(['data' => ['id' => $newAccount->getId()]], Http::STATUS_CREATED); } } catch (\Exception $ex) { $this->logger->error('Creating account failed: ' . $ex->getMessage()); return new JSONResponse(array('message' => $this->l10n->t('Creating account failed: ') . $ex->getMessage()), HTTP::STATUS_BAD_REQUEST); } $this->logger->info('Auto detect failed'); return new JSONResponse(array('message' => $this->l10n->t('Auto detect failed. Please use manual mode.')), HTTP::STATUS_BAD_REQUEST); }
/** * Send an email to {$limit} users * * @param int $limit Number of users we want to send an email to * @return int Number of users we sent an email to */ protected function runStep($limit) { // We don't use time() but "time() - 1" here, so we don't run into // runtime issues later and delete emails, which were created in the // same second, but were not collected for the emails. $sendTime = time() - 1; // Get all users which should receive an email $affectedUsers = $this->mqHandler->getAffectedUsers($limit, $sendTime); if (empty($affectedUsers)) { // No users found to notify, mission abort return 0; } $userLanguages = $this->config->getUserValueForUsers('core', 'lang', $affectedUsers); $userTimezones = $this->config->getUserValueForUsers('core', 'timezone', $affectedUsers); $userEmails = $this->config->getUserValueForUsers('settings', 'email', $affectedUsers); // Get all items for these users $mailData = $this->mqHandler->getItemsForUsers($affectedUsers, $sendTime); // Send Email $default_lang = $this->config->getSystemValue('default_language', 'en'); $defaultTimeZone = date_default_timezone_get(); foreach ($mailData as $user => $data) { if (empty($userEmails[$user])) { // The user did not setup an email address // So we will not send an email :( $this->logger->debug("Couldn't send notification email to user '" . $user . "' (email address isn't set for that user)", ['app' => 'activity']); continue; } $language = !empty($userLanguages[$user]) ? $userLanguages[$user] : $default_lang; $timezone = !empty($userTimezones[$user]) ? $userTimezones[$user] : $defaultTimeZone; $this->mqHandler->sendEmailToUser($user, $userEmails[$user], $language, $timezone, $data); } // Delete all entries we dealt with $this->mqHandler->deleteSentItems($affectedUsers, $sendTime); return sizeof($affectedUsers); }
/** * update encrypted file, e.g. give additional users access to the file * * @param string $path path to the file which should be updated * @param string $uid of the user who performs the operation * @param array $accessList who has access to the file contains the key 'users' and 'public' * @return boolean */ public function update($path, $uid, array $accessList) { if (empty($accessList)) { if (isset(self::$rememberVersion[$path])) { $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); unset(self::$rememberVersion[$path]); } return; } $fileKey = $this->keyManager->getFileKey($path, $uid); if (!empty($fileKey)) { $publicKeys = array(); if ($this->useMasterPassword === true) { $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); } else { foreach ($accessList['users'] as $user) { try { $publicKeys[$user] = $this->keyManager->getPublicKey($user); } catch (PublicKeyMissingException $e) { $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); } } } $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid); $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); $this->keyManager->deleteAllFileKeys($path); $this->keyManager->setAllFileKeys($path, $encryptedFileKey); } else { $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', array('file' => $path, 'app' => 'encryption')); return false; } return true; }
/** * {@inheritDoc} */ public function formatItems($items, $format, $parameters = null) { $entities = []; if ($format === Types::ENTITY) { foreach ($items as $item) { try { $calendar = $this->calendars->find($item['item_source'], $item['uid_owner']); } catch (BusinessLayer\Exception $ex) { $this->logger->debug($ex->getMessage()); continue; } $calendar->setId(null); $calendar->setBackend($this->sharingBackend); $calendar->setCruds($item['permissions']); $calendar->setPrivateUri('calendar::' . $item['item_source']); $calendar->setUserId($item['share_with']); $entities[] = $calendar; } return $this->factory->createCollectionFromEntities($entities); } elseif ($format === Types::ENTITYLIST) { foreach ($items as $item) { $entities[] = $item['item_source']; } return $entities; } else { return null; } }
/** * runs the update actions in maintenance mode, does not upgrade the source files * except the main .htaccess file * * @return bool true if the operation succeeded, false otherwise */ public function upgrade() { $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false); if(!$wasMaintenanceModeEnabled) { $this->config->setSystemValue('maintenance', true); $this->emit('\OC\Updater', 'maintenanceEnabled'); } $installedVersion = $this->config->getSystemValue('version', '0.0.0'); $currentVersion = implode('.', \OC_Util::getVersion()); if ($this->log) { $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core')); } $success = true; try { $this->doUpgrade($currentVersion, $installedVersion); } catch (\Exception $exception) { \OCP\Util::logException('update', $exception); $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage())); $success = false; } $this->emit('\OC\Updater', 'updateEnd', array($success)); if(!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); $this->emit('\OC\Updater', 'maintenanceDisabled'); } else { $this->emit('\OC\Updater', 'maintenanceActive'); } return $success; }
/** * Send an email to {$limit} users * * @param int $limit Number of users we want to send an email to * @param int $sendTime The latest send time * @return int Number of users we sent an email to */ protected function runStep($limit, $sendTime) { // Get all users which should receive an email $affectedUsers = $this->mqHandler->getAffectedUsers($limit, $sendTime); if (empty($affectedUsers)) { // No users found to notify, mission abort return 0; } $userLanguages = $this->config->getUserValueForUsers('core', 'lang', $affectedUsers); $userTimezones = $this->config->getUserValueForUsers('core', 'timezone', $affectedUsers); $userEmails = $this->config->getUserValueForUsers('settings', 'email', $affectedUsers); // Send Email $default_lang = $this->config->getSystemValue('default_language', 'en'); $defaultTimeZone = date_default_timezone_get(); foreach ($affectedUsers as $user) { if (empty($userEmails[$user])) { // The user did not setup an email address // So we will not send an email :( $this->logger->debug("Couldn't send notification email to user '" . $user . "' (email address isn't set for that user)", ['app' => 'activity']); continue; } $language = !empty($userLanguages[$user]) ? $userLanguages[$user] : $default_lang; $timezone = !empty($userTimezones[$user]) ? $userTimezones[$user] : $defaultTimeZone; $this->mqHandler->sendEmailToUser($user, $userEmails[$user], $language, $timezone, $sendTime); } // Delete all entries we dealt with $this->mqHandler->deleteSentItems($affectedUsers, $sendTime); return sizeof($affectedUsers); }
/** * runs the update actions in maintenance mode, does not upgrade the source files * except the main .htaccess file * * @return bool true if the operation succeeded, false otherwise */ public function upgrade() { $this->emitRepairEvents(); $logLevel = $this->config->getSystemValue('loglevel', \OCP\Util::WARN); $this->emit('\\OC\\Updater', 'setDebugLogLevel', [$logLevel, $this->logLevelNames[$logLevel]]); $this->config->setSystemValue('loglevel', \OCP\Util::DEBUG); $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false); if (!$wasMaintenanceModeEnabled) { $this->config->setSystemValue('maintenance', true); $this->emit('\\OC\\Updater', 'maintenanceEnabled'); } $installedVersion = $this->config->getSystemValue('version', '0.0.0'); $currentVersion = implode('.', \OCP\Util::getVersion()); $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core')); $success = true; try { $this->doUpgrade($currentVersion, $installedVersion); } catch (\Exception $exception) { $this->log->logException($exception, ['app' => 'core']); $this->emit('\\OC\\Updater', 'failure', array(get_class($exception) . ': ' . $exception->getMessage())); $success = false; } $this->emit('\\OC\\Updater', 'updateEnd', array($success)); if (!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); $this->emit('\\OC\\Updater', 'maintenanceDisabled'); } else { $this->emit('\\OC\\Updater', 'maintenanceActive'); } $this->emit('\\OC\\Updater', 'resetLogLevel', [$logLevel, $this->logLevelNames[$logLevel]]); $this->config->setSystemValue('loglevel', $logLevel); return $success; }
public function __destruct() { // Only releaseAll if we have locks to release if (!empty($this->handle) || !empty($this->lockFile)) { $this->log->debug(sprintf('INFO: Destroying locks on %s', $this->path), ['app' => 'files_locking']); $this->releaseAll(); } }
/** * @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]); }
/** * removes a file from the lucene index * * @param int $fileId file id to remove from the index * * @return int count of deleted documents in the index */ public function deleteFile($fileId) { $hits = $this->index->find('fileId:' . $fileId); $this->logger->debug('found ' . count($hits) . ' hits for file id ' . $fileId); foreach ($hits as $hit) { $this->logger->debug('removing ' . $hit->id . ':' . $hit->path . ' from index'); $this->index->delete($hit); } return count($hits); }
/** * @param string $token * @throws InvalidTokenException * @return DefaultToken user UID */ public function validateToken($token) { try { $dbToken = $this->mapper->getToken($this->hashToken($token)); $this->logger->debug('valid default token for ' . $dbToken->getUID()); return $dbToken; } catch (DoesNotExistException $ex) { throw new InvalidTokenException(); } }
/** * @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(); }
/** * Send the specified message. Also sets the from address to the value defined in config.php * if no-one has been passed. * * @param Message $message Message to send * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and * therefore should be considered * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address * has been supplied.) */ public function send(Message $message) { $debugMode = $this->config->getSystemValue('mail_smtpdebug', false); if (sizeof($message->getFrom()) === 0) { $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName())]); } $failedRecipients = []; $mailer = $this->getInstance(); // Enable logger if debug mode is enabled if ($debugMode) { $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); } $mailer->send($message->getSwiftMessage(), $failedRecipients); // Debugging logging $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject()); $this->logger->debug($logMessage, ['app' => 'core']); if ($debugMode && isset($mailLogger)) { $this->logger->debug($mailLogger->dump(), ['app' => 'core']); } return $failedRecipients; }
/** * update encrypted file, e.g. give additional users access to the file * * @param string $path path to the file which should be updated * @param string $uid of the user who performs the operation * @param array $accessList who has access to the file contains the key 'users' and 'public' * @return boolean */ public function update($path, $uid, array $accessList) { $fileKey = $this->keyManager->getFileKey($path, $uid); if (!empty($fileKey)) { $publicKeys = array(); foreach ($accessList['users'] as $user) { $publicKeys[$user] = $this->keyManager->getPublicKey($user); } $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid); $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); $this->keyManager->deleteAllFileKeys($path); $this->keyManager->setAllFileKeys($path, $encryptedFileKey); } else { $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', array('file' => $path, 'app' => 'encryption')); return false; } return true; }
/** * Loads an image from a base64 encoded string. * * @param string $str A string base64 encoded string of image data. * @return bool|resource An image resource or false on error */ public function loadFromBase64($str) { if (!is_string($str)) { return false; } $data = base64_decode($str); if ($data) { // try to load from string data $this->resource = @imagecreatefromstring($data); if ($this->fileInfo) { $this->mimeType = $this->fileInfo->buffer($data); } if (!$this->resource) { $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core')); return false; } return $this->resource; } else { return false; } }
/** * If an SecurityException is being caught, ajax requests return a JSON error * response and non ajax requests redirect to the index * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param \Exception $exception the thrown exception * @throws \Exception the passed in exception if it can't handle it * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception) { if ($exception instanceof SecurityException) { if (stripos($this->request->getHeader('Accept'), 'html') === false) { $response = new JSONResponse(array('message' => $exception->getMessage()), $exception->getCode()); } else { if ($exception instanceof NotLoggedInException) { $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', ['redirect_url' => urlencode($this->request->server['REQUEST_URI'])]); $response = new RedirectResponse($url); } else { $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest'); $response->setStatus($exception->getCode()); } } $this->logger->debug($exception->getMessage()); return $response; } throw $exception; }
/** * Share a path * * @param IShare $share * @return IShare The share object * @throws ShareNotFound * @throws \Exception */ public function create(IShare $share) { $shareWith = $share->getSharedWith(); $itemSource = $share->getNodeId(); $itemType = $share->getNodeType(); $uidOwner = $share->getShareOwner(); $permissions = $share->getPermissions(); $sharedBy = $share->getSharedBy(); /* * Check if file is not already shared with the remote user */ $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0); if (!empty($alreadyShared)) { $message = 'Sharing %s failed, because this item is already shared with %s'; $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith)); $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']); throw new \Exception($message_t); } // don't allow federated shares if source and target server are the same list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith); $currentServer = $this->addressHandler->generateRemoteURL(); $currentUser = $sharedBy; if ($this->addressHandler->compareAddresses($user, $remote, $currentUser, $currentServer)) { $message = 'Not allowed to create a federated share with the same user.'; $message_t = $this->l->t('Not allowed to create a federated share with the same user'); $this->logger->debug($message, ['app' => 'Federated File Sharing']); throw new \Exception($message_t); } $token = $this->tokenHandler->generateToken(); $shareWith = $user . '@' . $remote; $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token); $send = $this->notifications->sendRemoteShare($token, $shareWith, $share->getNode()->getName(), $shareId, $share->getSharedBy()); $data = $this->getRawShare($shareId); $share = $this->createShare($data); if ($send === false) { $this->delete($share); $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', [$share->getNode()->getName(), $shareWith]); throw new \Exception($message_t); } return $share; }
/** * scan all * @param string $userId */ public function scan($userId) { $backends = $this->backends->getObjects(); /* @var IBackend $backend */ foreach ($backends as $backend) { try { $backendId = $backend->getId(); $calendars = $backend->getCalendarAPI()->listAll($userId); foreach ($calendars as $privateUri) { try { $this->scanCalendar($backendId, $privateUri, $userId); } catch (\Exception $ex) { $this->logger->debug($ex->getMessage()); continue; } } } catch (\Exception $ex) { $this->logger->debug($ex->getMessage()); } } }
/** * {@inheritDoc} */ public function isValidSource($itemSource, $uidOwner) { //format of itemSource: $calendarId::$objectUri if (substr_count($itemSource, '::') === 0) { return false; } list($calendarId, $objectUri) = explode('::', $itemSource, 1); try { $calendar = $this->calendars->find($calendarId, $uidOwner); /** @var BusinessLayer\ObjectManager $objects */ $objects = call_user_func_array($this->objects, [$calendar]); $object = $objects->find($objectUri); } catch (\Exception $ex) { $this->logger->debug($ex->getMessage()); return false; } /** @var \OCA\Calendar\IObject $object */ if ($object && $object->getCalendar() === $calendar) { return true; } return false; }
/** * Returns a JSON response to the client * * @param string $message * @param int $code * * @return JSONResponse */ private function sendJsonResponse($message, $code) { $this->logger->debug("[TokenCheckException] JSON response"); $jsonData = ['message' => $message, 'success' => false]; return new JSONResponse($jsonData, $code); }
/** * Share a path * * @param IShare $share * @return IShare The share object * @throws ShareNotFound * @throws \Exception */ public function create(IShare $share) { $shareWith = $share->getSharedWith(); $itemSource = $share->getNodeId(); $itemType = $share->getNodeType(); $permissions = $share->getPermissions(); $sharedBy = $share->getSharedBy(); /* * Check if file is not already shared with the remote user */ $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0); if (!empty($alreadyShared)) { $message = 'Sharing %s failed, because this item is already shared with %s'; $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith)); $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']); throw new \Exception($message_t); } // don't allow federated shares if source and target server are the same list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith); $currentServer = $this->addressHandler->generateRemoteURL(); $currentUser = $sharedBy; if ($this->addressHandler->compareAddresses($user, $remote, $currentUser, $currentServer)) { $message = 'Not allowed to create a federated share with the same user.'; $message_t = $this->l->t('Not allowed to create a federated share with the same user'); $this->logger->debug($message, ['app' => 'Federated File Sharing']); throw new \Exception($message_t); } $share->setSharedWith($user . '@' . $remote); try { $remoteShare = $this->getShareFromExternalShareTable($share); } catch (ShareNotFound $e) { $remoteShare = null; } if ($remoteShare) { try { $uidOwner = $remoteShare['owner'] . '@' . $remoteShare['remote']; $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, 'tmp_token_' . time()); $share->setId($shareId); list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId); // remote share was create successfully if we get a valid token as return $send = is_string($token) && $token !== ''; } catch (\Exception $e) { // fall back to old re-share behavior if the remote server // doesn't support flat re-shares (was introduced with ownCloud 9.1) $this->removeShareFromTable($share); $shareId = $this->createFederatedShare($share); } if ($send) { $this->updateSuccessfulReshare($shareId, $token); $this->storeRemoteId($shareId, $remoteId); } else { $this->removeShareFromTable($share); $message_t = $this->l->t('File is already shared with %s', [$shareWith]); throw new \Exception($message_t); } } else { $shareId = $this->createFederatedShare($share); } $data = $this->getRawShare($shareId); return $this->createShareObject($data); }
/** * @inheritdoc */ public function debug($message, array $context = array()) { $this->logger->debug($message, $this->context); }
/** * @inheritdoc */ public function debug($message, array $context = []) { $this->logger->debug($message, array_merge($this->context, $context)); }
public static function onAll($number, $message, $file, $line) { $msg = $message . ' at ' . $file . '#' . $line; self::$logger->debug(self::removePassword($msg), array('app' => 'PHP')); }
/** * Deleting orphaned comment read markers * * @return int Number of deleted entries */ protected function cleanCommentMarkers() { $deletedEntries = $this->cleanUp('comments_read_markers', 'object_id', 'object_type'); $this->logger->debug("{$deletedEntries} orphaned comment read marks deleted", ['app' => 'DeleteOrphanedItems']); return $deletedEntries; }
protected function logException(\Exception $e) { $this->logger->error($e->getMessage(), array('app' => $this->appName)); $this->logger->debug($e->getTraceAsString(), array('app' => $this->appName)); }