예제 #1
0
 /**
  * @param string $url
  * @param string $userName
  * @param string $sharedSecret
  * @param string $syncToken
  * @param int $targetBookId
  * @param string $targetPrincipal
  * @param array $targetProperties
  * @return string
  * @throws \Exception
  */
 public function syncRemoteAddressBook($url, $userName, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties)
 {
     // 1. create addressbook
     $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
     $addressBookId = $book['id'];
     // 2. query changes
     try {
         $response = $this->requestSyncReport($url, $userName, $sharedSecret, $syncToken);
     } catch (ClientHttpException $ex) {
         if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
             // remote server revoked access to the address book, remove it
             $this->backend->deleteAddressBook($addressBookId);
             $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
             throw $ex;
         }
     }
     // 3. apply changes
     // TODO: use multi-get for download
     foreach ($response['response'] as $resource => $status) {
         $cardUri = basename($resource);
         if (isset($status[200])) {
             $vCard = $this->download($url, $sharedSecret, $resource);
             $existingCard = $this->backend->getCard($addressBookId, $cardUri);
             if ($existingCard === false) {
                 $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
             } else {
                 $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
             }
         } else {
             $this->backend->deleteCard($addressBookId, $cardUri);
         }
     }
     return $response['token'];
 }
 /**
  * @param array $data
  * @param integer $format
  * @return SubscriptionCollection
  */
 public function createCollectionFromData($data, $format)
 {
     $collection = new SubscriptionCollection();
     foreach ($data as $item) {
         try {
             $entity = $this->createEntity($item, $format);
             $collection->add($entity);
         } catch (CorruptDataException $ex) {
             $this->logger->info($ex->getMessage());
             continue;
         }
     }
     return $collection;
 }
예제 #3
0
 /**
  * @return null|string Returns the raw image data.
  */
 function data()
 {
     if (!$this->valid()) {
         return null;
     }
     ob_start();
     switch ($this->mimeType) {
         case "image/png":
             $res = imagepng($this->resource);
             break;
         case "image/jpeg":
             $res = imagejpeg($this->resource);
             break;
         case "image/gif":
             $res = imagegif($this->resource);
             break;
         default:
             $res = imagepng($this->resource);
             $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
             break;
     }
     if (!$res) {
         $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
     }
     return ob_get_clean();
 }
예제 #4
0
 /**
  * @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]);
 }
예제 #5
0
파일: migration.php 프로젝트: jzee/core
 /**
  * rename file keys
  *
  * @param string $user
  * @param string $path
  * @param bool $trash
  */
 private function renameFileKeys($user, $path, $trash = false)
 {
     if ($this->view->is_dir($user . '/' . $path) === false) {
         $this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
         return;
     }
     $dh = $this->view->opendir($user . '/' . $path);
     if (is_resource($dh)) {
         while (($file = readdir($dh)) !== false) {
             if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
                 if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
                     $this->renameFileKeys($user, $path . '/' . $file, $trash);
                 } else {
                     $target = $this->getTargetDir($user, $path, $file, $trash);
                     if ($target) {
                         $this->createPathForKeys(dirname($target));
                         $this->view->rename($user . '/' . $path . '/' . $file, $target);
                     } else {
                         $this->logger->warning('did not move key "' . $file . '" could not find the corresponding file in /data/' . $user . '/files.' . 'Most likely the key was already moved in a previous migration run and is already on the right place.');
                     }
                 }
             }
         }
         closedir($dh);
     }
 }
예제 #6
0
 protected function run($argument)
 {
     $target = $argument['url'];
     $source = $this->urlGenerator->getAbsoluteURL('/');
     $source = rtrim($source, '/');
     $token = $argument['token'];
     try {
         $result = $this->httpClient->post($target . $this->endPoint, ['body' => ['url' => $source, 'token' => $token], 'timeout' => 3, 'connect_timeout' => 3]);
         $status = $result->getStatusCode();
     } catch (ClientException $e) {
         $status = $e->getCode();
         if ($status === Http::STATUS_FORBIDDEN) {
             $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
         } else {
             $this->logger->logException($e, ['app' => 'federation']);
         }
     } catch (\Exception $e) {
         $status = Http::STATUS_INTERNAL_SERVER_ERROR;
         $this->logger->logException($e, ['app' => 'federation']);
     }
     // if we received a unexpected response we try again later
     if ($status !== Http::STATUS_OK && $status !== Http::STATUS_FORBIDDEN) {
         $this->retainJob = true;
     }
     if ($status === Http::STATUS_FORBIDDEN) {
         // clear token if remote server refuses to ask for shared secret
         $this->dbHandler->addToken($target, '');
     }
 }
예제 #7
0
 /**
  * opens or creates the given lucene index
  *
  * @throws SetUpException
  */
 public function openOrCreate()
 {
     $indexFolder = $this->files->setUpIndexFolder();
     $storage = $indexFolder->getStorage();
     $localPath = $storage->getLocalFolder($indexFolder->getInternalPath());
     //let lucene search for numbers as well as words
     Analyzer::setDefault(new CaseInsensitive());
     // can we use the index?
     if ($indexFolder->nodeExists('v0.6.0')) {
         // correct index present
         $this->index = Lucene::open($localPath);
     } else {
         $this->logger->info('recreating outdated lucene index');
         $indexFolder->delete();
         $this->index = Lucene::create($localPath);
         $indexFolder->newFile('v0.6.0');
     }
 }
예제 #8
0
 /**
  * @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]);
 }
예제 #9
0
파일: factory.php 프로젝트: kenwi/core
 /**
  * @param string $globalPrefix
  * @param ILogger $logger
  * @param string|null $localCacheClass
  * @param string|null $distributedCacheClass
  * @param string|null $lockingCacheClass
  */
 public function __construct($globalPrefix, ILogger $logger, $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null)
 {
     $this->logger = $logger;
     $this->globalPrefix = $globalPrefix;
     if (!$localCacheClass) {
         $localCacheClass = self::NULL_CACHE;
     }
     if (!$distributedCacheClass) {
         $distributedCacheClass = $localCacheClass;
     }
     $missingCacheMessage = 'Memcache {class} not available for {use} cache';
     $missingCacheHint = 'Is the matching PHP module installed and enabled?';
     if (!$localCacheClass::isAvailable()) {
         if (\OC::$CLI && !defined('PHPUNIT_RUN')) {
             // CLI should not hard-fail on broken memcache
             $this->logger->info($missingCacheMessage, ['class' => $localCacheClass, 'use' => 'local', 'app' => 'cli']);
             $localCacheClass = self::NULL_CACHE;
         } else {
             throw new \OC\HintException(strtr($missingCacheMessage, ['{class}' => $localCacheClass, '{use}' => 'local']), $missingCacheHint);
         }
     }
     if (!$distributedCacheClass::isAvailable()) {
         if (\OC::$CLI && !defined('PHPUNIT_RUN')) {
             // CLI should not hard-fail on broken memcache
             $this->logger->info($missingCacheMessage, ['class' => $distributedCacheClass, 'use' => 'distributed', 'app' => 'cli']);
             $distributedCacheClass = self::NULL_CACHE;
         } else {
             throw new \OC\HintException(strtr($missingCacheMessage, ['{class}' => $distributedCacheClass, '{use}' => 'distributed']), $missingCacheHint);
         }
     }
     if (!($lockingCacheClass && $lockingCacheClass::isAvailable())) {
         // dont fallback since the fallback might not be suitable for storing lock
         $lockingCacheClass = self::NULL_CACHE;
     }
     $this->localCacheClass = $localCacheClass;
     $this->distributedCacheClass = $distributedCacheClass;
     $this->lockingCacheClass = $lockingCacheClass;
 }
 /**
  * @param mixed $data
  * @param integer $format
  * @param boolean $autoAssignUri
  * @return ObjectCollection
  */
 public function createCollectionFromData($data, $format, $autoAssignUri = false)
 {
     $collection = new ObjectCollection();
     if ($format === self::FORMAT_ICAL || $format === self::FORMAT_JCAL) {
         return $this->parseRawCal($data, $format, false);
     }
     foreach ($data as $item) {
         try {
             $entity = $this->createEntity($item, $format);
             $collection->add($entity);
         } catch (CorruptDataException $ex) {
             $this->logger->info($ex->getMessage());
             continue;
         }
     }
     return $collection;
 }
예제 #11
0
파일: users.php 프로젝트: phongtnit/core
 /**
  * @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');
         }
     }
 }
예제 #12
0
파일: users.php 프로젝트: kenwi/core
 /**
  * @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');
     }
 }
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  *
  * @param string $username
  * @param string $password
  * @return JsonResponse
  */
 public function testSettings($username, $password)
 {
     $xmlrpc = new XmlRpc($username, $password);
     try {
         $serverInfo = $xmlrpc->serverInfo();
     } catch (HttpException $exception) {
         if ($exception->getCode() === Http::STATUS_UNAUTHORIZED) {
             $this->logger->info('Settings test failed (unauthorized)', ['app' => $this->appName]);
             return new JSONResponse(['success' => false, 'error' => 'Authorization failed'], Http::STATUS_UNAUTHORIZED);
         } else {
             $this->logger->warn(sprintf('Settings test failed (%d: %s)', $exception->getCode(), $exception->getMessage()), ['app' => $this->appName]);
             return new JSONResponse(['success' => false, 'error' => $exception->getMessage()], Http::STATUS_BAD_GATEWAY);
         }
     } catch (\Exception $exception) {
         $this->logger->error(sprintf('Settings test failed with exception (%s)', $exception->getMessage()), ['app' => $this->appName]);
         return new JSONResponse(['success' => false, 'error' => $exception->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
     }
     $this->logger->info('Settings test successful', ['app' => $this->appName]);
     return new JSONResponse(['success' => true, 'serverInfo' => $serverInfo->toJSON()]);
 }
예제 #14
0
 /**
  * request received to ask remote server for a shared secret
  *
  * @return \OC_OCS_Result
  */
 public function requestSharedSecret()
 {
     $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 requesting shared secret', ['app' => 'federation']);
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     // if both server initiated the exchange of the shared secret the greater
     // token wins
     $localToken = $this->dbHandler->getToken($url);
     if (strcmp($localToken, $token) > 0) {
         $this->logger->info('remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.', ['app' => 'federation']);
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     // we ask for the shared secret so we no longer have to ask the other server
     // to request the shared secret
     $this->jobList->remove('OCA\\Federation\\BackgroundJob\\RequestSharedSecret', ['url' => $url, 'token' => $localToken]);
     $this->jobList->add('OCA\\Federation\\BackgroundJob\\GetSharedSecret', ['url' => $url, 'token' => $token]);
     return new \OC_OCS_Result(null, Http::STATUS_OK);
 }
예제 #15
0
 protected function run($argument)
 {
     $target = $argument['url'];
     $source = $this->urlGenerator->getAbsoluteURL('/');
     $source = rtrim($source, '/');
     $token = $argument['token'];
     $result = null;
     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();
         if ($status === Http::STATUS_FORBIDDEN) {
             $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
         } else {
             $this->logger->logException($e, ['app' => 'federation']);
         }
     } catch (\Exception $e) {
         $status = Http::STATUS_INTERNAL_SERVER_ERROR;
         $this->logger->logException($e, ['app' => 'federation']);
     }
     // if we received a unexpected response we try again later
     if ($status !== Http::STATUS_OK && $status !== Http::STATUS_FORBIDDEN) {
         $this->retainJob = true;
     } else {
         // reset token if we received a valid response
         $this->dbHandler->addToken($target, '');
     }
     if ($status === Http::STATUS_OK && $result instanceof IResponse) {
         $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);
         }
     }
 }
예제 #16
0
파일: logger.php 프로젝트: WPSlicers/mail
 /**
  * @inheritdoc
  */
 public function info($message, array $context = array())
 {
     $this->logger->info($message, $this->context);
 }
예제 #17
0
 /**
  * @inheritdoc
  */
 public function info($message, array $context = [])
 {
     $this->logger->info($message, array_merge($this->context, $context));
 }
예제 #18
0
 /**
  * Invalidate (delete) old session tokens
  */
 public function invalidateOldTokens()
 {
     $olderThan = $this->time->getTime() - (int) $this->config->getSystemValue('session_lifetime', 60 * 60 * 24);
     $this->logger->info('Invalidating tokens older than ' . date('c', $olderThan));
     $this->mapper->invalidateOld($olderThan);
 }