예제 #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'];
 }
예제 #2
0
 /**
  * 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;
 }
예제 #3
0
파일: scanfiles.php 프로젝트: loulancn/core
 /**
  * @param IUser $user
  */
 protected function runScanner(IUser $user)
 {
     try {
         $scanner = new Scanner($user->getUID(), $this->dbConnection, $this->logger);
         $scanner->backgroundScan('');
     } catch (\Exception $e) {
         $this->logger->logException($e, ['app' => 'files']);
     }
     \OC_Util::tearDownFS();
 }
 /**
  * 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);
 }
예제 #5
0
파일: Job.php 프로젝트: GitHubUser4234/core
 /**
  * @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->logException($e, ['app' => 'core', 'message' => 'Error while running background job (class: ' . get_class($this) . ', arguments: ' . print_r($this->argument, true) . ')']);
         }
     }
 }
예제 #6
0
파일: job.php 프로젝트: Angelos0/core
 /**
  * @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());
         }
     }
 }
예제 #7
0
파일: logger.php 프로젝트: evanjt/core
 /**
  * @dataProvider userAndPasswordData
  */
 public function testDetectcheckPassword($user, $password)
 {
     $e = new \Exception('test');
     $this->logger->logException($e);
     $logLines = $this->getLogs();
     foreach ($logLines as $logLine) {
         $this->assertNotContains($user, $logLine);
         $this->assertNotContains($password, $logLine);
         $this->assertContains('checkPassword(*** username and password replaced ***)', $logLine);
     }
 }
예제 #8
0
    /**
     * check if new encryption is ready
     *
     * @return boolean
     */
    public function isReady()
    {
        // check if we are still in transit between the old and the new encryption
        $oldEncryption = $this->config->getAppValue('files_encryption', 'installed_version');
        if (!empty($oldEncryption)) {
            $warning = 'Installation is in transit between the old Encryption (ownCloud <= 8.0)
			and the new encryption. Please enable the "Default encryption module"
			and run \'occ encryption:migrate\'';
            $this->logger->warning($warning);
            return false;
        }
        return true;
    }
예제 #9
0
 /**
  * become another user
  * @param string $userid
  * @UseSession
  * @return JSONResponse
  */
 public function impersonate($userid)
 {
     $oldUserId = $this->userSession->getUser()->getUID();
     $this->logger->warning("User {$oldUserId} trying to impersonate user {$userid}", ['app' => 'impersonate']);
     $user = $this->userManager->get($userid);
     if ($user === null) {
         return new JSONResponse("No user found for {$userid}", Http::STATUS_NOT_FOUND);
     } else {
         $this->logger->warning("changing to user {$userid}", ['app' => 'impersonate']);
         $this->userSession->setUser($user);
     }
     return new JSONResponse();
 }
 /**
  * @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;
 }
예제 #11
0
 /**
  * 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';
     }
 }
예제 #12
0
 /**
  * @param int $calendarId
  * @param int $newCalendarId
  */
 private function migrateCalendar($calendarId, $newCalendarId)
 {
     $this->adapter->foreachCalendarObject($calendarId, function ($calObject) use($newCalendarId) {
         try {
             $this->backend->createCalendarObject($newCalendarId, $calObject['uri'], $calObject['calendardata']);
         } catch (\Exception $ex) {
             $eventId = $calObject['id'];
             $calendarId = $calObject['calendarId'];
             $msg = "One event could not be migrated. (id: {$eventId}, calendarid: {$calendarId})";
             $this->logger->logException($ex, ['app' => 'dav', 'message' => $msg]);
             if (!is_null($this->consoleOutput)) {
                 $this->consoleOutput->writeln($msg);
             }
         }
     });
 }
예제 #13
0
파일: ocsclient.php 프로젝트: kenwi/core
 /**
  * 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;
 }
예제 #14
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]);
 }
예제 #15
0
 public function testAddUserAsSubAdminExistingGroups()
 {
     $_POST['userid'] = 'NewUser';
     $_POST['password'] = '******';
     $_POST['groups'] = ['ExistingGroup1', 'ExistingGroup2'];
     $this->userManager->expects($this->once())->method('userExists')->with('NewUser')->willReturn(false);
     $loggedInUser = $this->getMock('\\OCP\\IUser');
     $loggedInUser->expects($this->once())->method('getUID')->will($this->returnValue('subAdminUser'));
     $this->userSession->expects($this->once())->method('getUser')->will($this->returnValue($loggedInUser));
     $this->groupManager->expects($this->once())->method('isAdmin')->with('subAdminUser')->willReturn(false);
     $this->groupManager->expects($this->exactly(2))->method('groupExists')->withConsecutive(['ExistingGroup1'], ['ExistingGroup2'])->willReturn(true);
     $user = $this->getMock('\\OCP\\IUser');
     $this->userManager->expects($this->once())->method('createUser')->with('NewUser', 'PasswordOfTheNewUser')->willReturn($user);
     $existingGroup1 = $this->getMock('\\OCP\\IGroup');
     $existingGroup2 = $this->getMock('\\OCP\\IGroup');
     $existingGroup1->expects($this->once())->method('addUser')->with($user);
     $existingGroup2->expects($this->once())->method('addUser')->with($user);
     $this->groupManager->expects($this->exactly(4))->method('get')->withConsecutive(['ExistingGroup1'], ['ExistingGroup2'], ['ExistingGroup1'], ['ExistingGroup2'])->will($this->returnValueMap([['ExistingGroup1', $existingGroup1], ['ExistingGroup2', $existingGroup2]]));
     $this->logger->expects($this->exactly(3))->method('info')->withConsecutive(['Successful addUser call with userid: NewUser', ['app' => 'ocs_api']], ['Added userid NewUser to group ExistingGroup1', ['app' => 'ocs_api']], ['Added userid NewUser to group ExistingGroup2', ['app' => 'ocs_api']]);
     $subAdminManager = $this->getMockBuilder('\\OC\\Subadmin')->disableOriginalConstructor()->getMock();
     $this->groupManager->expects($this->once())->method('getSubAdmin')->willReturn($subAdminManager);
     $subAdminManager->expects($this->once())->method('isSubAdmin')->with($loggedInUser)->willReturn(true);
     $subAdminManager->expects($this->exactly(2))->method('isSubAdminOfGroup')->withConsecutive([$loggedInUser, $existingGroup1], [$loggedInUser, $existingGroup2])->wilLReturn(true);
     $expected = new \OC_OCS_Result(null, 100);
     $this->assertEquals($expected, $this->api->addUser());
 }
예제 #16
0
 /**
  * @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
         }
     }
 }
예제 #17
0
 /**
  * @NoAdminRequired
  *
  * @param array $crop
  * @return DataResponse
  */
 public function postCroppedAvatar($crop)
 {
     $userId = $this->userSession->getUser()->getUID();
     if (is_null($crop)) {
         return new DataResponse(['data' => ['message' => $this->l->t("No crop data provided")]], Http::STATUS_BAD_REQUEST);
     }
     if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) {
         return new DataResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]], Http::STATUS_BAD_REQUEST);
     }
     $tmpAvatar = $this->cache->get('tmpAvatar');
     if (is_null($tmpAvatar)) {
         return new DataResponse(['data' => ['message' => $this->l->t("No temporary profile picture available, try again")]], Http::STATUS_BAD_REQUEST);
     }
     $image = new \OC_Image($tmpAvatar);
     $image->crop($crop['x'], $crop['y'], round($crop['w']), round($crop['h']));
     try {
         $avatar = $this->avatarManager->getAvatar($userId);
         $avatar->set($image);
         // Clean up
         $this->cache->remove('tmpAvatar');
         return new DataResponse(['status' => 'success']);
     } catch (\OC\NotSquareException $e) {
         return new DataResponse(['data' => ['message' => $this->l->t('Crop is not square')]], Http::STATUS_BAD_REQUEST);
     } catch (\Exception $e) {
         $this->logger->logException($e, ['app' => 'core']);
         return new DataResponse(['data' => ['message' => $this->l->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST);
     }
 }
예제 #18
0
 function getPhoto(Card $node)
 {
     // TODO: this is kind of expensive - load carddav data from database and parse it
     //       we might want to build up a cache one day
     try {
         $vObject = $this->readCard($node->get());
         if (!$vObject->PHOTO) {
             return false;
         }
         $photo = $vObject->PHOTO;
         $type = $this->getType($photo);
         $val = $photo->getValue();
         if ($photo->getValueType() === 'URI') {
             $parsed = \Sabre\URI\parse($val);
             //only allow data://
             if ($parsed['scheme'] !== 'data') {
                 return false;
             }
             if (substr_count($parsed['path'], ';') === 1) {
                 list($type, ) = explode(';', $parsed['path']);
             }
             $val = file_get_contents($val);
         }
         return ['Content-Type' => $type, 'body' => $val];
     } catch (\Exception $ex) {
         $this->logger->logException($ex);
     }
     return false;
 }
예제 #19
0
 /**
  * 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;
 }
예제 #20
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);
     }
 }
예제 #21
0
	/**
	 * 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;
	}
예제 #22
0
 /**
  * @param int $addressBookId
  * @param int $newAddressBookId
  */
 private function migrateBook($addressBookId, $newAddressBookId)
 {
     $this->adapter->foreachCard($addressBookId, function ($card) use($newAddressBookId) {
         try {
             $this->backend->createCard($newAddressBookId, $card['uri'], $card['carddata']);
         } catch (\Exception $ex) {
             $eventId = $card['id'];
             $addressBookId = $card['addressbookid'];
             $msg = "One event could not be migrated. (id: {$eventId}, addressbookid: {$addressBookId})";
             $this->logger->logException($ex, ['app' => 'dav', 'message' => $msg]);
             if (!is_null($this->consoleOutput)) {
                 $this->consoleOutput->writeln($msg);
             }
         }
     });
 }
 /**
  * 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);
 }
예제 #24
0
 /**
  * @param array $argument
  * @throws \Exception
  * @throws \OC\NeedsUpdateException
  */
 protected function run($argument)
 {
     if (!isset($argument['app']) || !isset($argument['step'])) {
         // remove the job - we can never execute it
         $this->jobList->remove($this, $this->argument);
         return;
     }
     $app = $argument['app'];
     try {
         $this->loadApp($app);
     } catch (NeedsUpdateException $ex) {
         // as long as the app is not yet done with it's offline migration
         // we better not start with the live migration
         return;
     }
     $step = $argument['step'];
     $repair = new Repair([], $this->dispatcher);
     try {
         $repair->addStep($step);
     } catch (\Exception $ex) {
         $this->logger->logException($ex, ['app' => 'migration']);
         // remove the job - we can never execute it
         $this->jobList->remove($this, $this->argument);
         return;
     }
     // execute the repair step
     $repair->run();
     // remove the job once executed successfully
     $this->jobList->remove($this, $this->argument);
 }
예제 #25
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();
         $this->logger->logException($e);
     } catch (\Exception $e) {
         $status = HTTP::STATUS_INTERNAL_SERVER_ERROR;
         $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\\RequestSharedSecret', $argument);
     }
     if ($status === Http::STATUS_FORBIDDEN) {
         // clear token if remote server refuses to ask for shared secret
         $this->dbHandler->addToken($target, '');
     }
 }
 /**
  * @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);
 }
예제 #27
0
 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);
         }
     }
 }
예제 #28
0
 /**
  * @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;
 }
예제 #29
0
파일: scanner.php 프로젝트: gvde/core
 /**
  * @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();
         }
     }
 }
 /**
  * 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);
 }