/**
  * @param IEvent $event
  * @param string $parameter The parameter to be formatted
  * @return string The formatted parameter
  */
 public function format(IEvent $event, $parameter)
 {
     $param = $this->fixLegacyFilename($parameter);
     // If the activity is about the very same file, we use the current path
     // for the link generation instead of the one that was saved.
     $fileId = '';
     if (is_array($param)) {
         $fileId = key($param);
         $param = $param[$fileId];
         $info = $this->infoCache->getInfoById($this->user, $fileId, $param);
     } elseif ($event->getObjectType() === 'files' && $event->getObjectName() === $param) {
         $fileId = $event->getObjectId();
         $info = $this->infoCache->getInfoById($this->user, $fileId, $param);
     } else {
         $info = $this->infoCache->getInfoByPath($this->user, $param);
     }
     if ($info['is_dir']) {
         $linkData = ['dir' => $info['path']];
     } else {
         $parentDir = substr_count($info['path'], '/') === 1 ? '/' : dirname($info['path']);
         $fileName = basename($info['path']);
         $linkData = ['dir' => $parentDir, 'scrollto' => $fileName];
     }
     if ($info['view'] !== '') {
         $linkData['view'] = $info['view'];
     }
     $param = trim($param, '/');
     $fileLink = $this->urlGenerator->linkToRouteAbsolute('files.view.index', $linkData);
     return '<file link="' . $fileLink . '" id="' . Util::sanitizeHTML($fileId) . '">' . Util::sanitizeHTML($param) . '</file>';
 }
Example #2
0
 public function testIndexWithIE8RedirectAndViewAndDirDefined()
 {
     $this->request->expects($this->once())->method('isUserAgent')->with(['/MSIE 8.0/'])->will($this->returnValue(true));
     $this->urlGenerator->expects($this->once())->method('linkToRoute')->with('files.view.index')->will($this->returnValue('/apps/files/'));
     $expected = new RedirectResponse('/apps/files/#?dir=MyDir&view=MyView');
     $this->assertEquals($expected, $this->viewController->index('MyDir', 'MyView'));
 }
 /**
  * @dataProvider dataFormat
  *
  * @param string $user
  * @param string $parameter
  * @param bool $isDir
  * @param array $info
  * @param bool $allowHtml
  * @param bool $verbose
  * @param string $expected
  */
 public function testFormat($user, $parameter, $isDir, array $info, $allowHtml, $verbose, $expected)
 {
     /** @var \OCP\Activity\IEvent|\PHPUnit_Framework_MockObject_MockObject $event */
     $event = $this->getMockBuilder('OCP\\Activity\\IEvent')->disableOriginalConstructor()->getMock();
     if (!empty($info)) {
         $event->expects($this->once())->method('getObjectType')->willReturn('files');
         $event->expects($this->once())->method('getObjectName')->willReturn($parameter);
         $event->expects($this->once())->method('getObjectId')->willReturn(42);
     }
     $this->urlGenerator->expects($allowHtml ? $this->once() : $this->never())->method('linkTo')->with('files', 'index.php', $this->anything())->willReturnCallback(function ($app, $file, $parameters) {
         $paramList = [];
         foreach ($parameters as $key => $value) {
             $paramList[] = $key . '=' . urlencode($value);
         }
         return $app . '/' . $file . '?' . implode('&', $paramList);
     });
     $formatter = $this->getFormatter(['fixLegacyFilename'], $user);
     $formatter->expects($this->once())->method('fixLegacyFilename')->willReturnArgument(0);
     if (!empty($info)) {
         $this->infoCache->expects($this->once())->method('getInfoById')->with($user, 42, $parameter)->willReturn($info);
     } else {
         $this->infoCache->expects($this->once())->method('getInfoByPath')->with($user, $parameter)->willReturn(['path' => $parameter, 'is_dir' => $isDir, 'exists' => true, 'view' => '']);
     }
     $this->assertSame($expected, $formatter->format($event, $parameter, $allowHtml, $verbose));
 }
Example #4
0
 /**
  * @PublicPage
  * @NoCSRFRequired
  *
  * @return TemplateResponse
  */
 public function show()
 {
     try {
         $user = $this->activityManager->getCurrentUserId();
         $userLang = $this->config->getUserValue($user, 'core', 'lang');
         // Overwrite user and language in the helper
         $l = Util::getL10N('activity', $userLang);
         $l->forceLanguage($userLang);
         $this->helper->setL10n($l);
         $this->helper->setUser($user);
         $description = (string) $l->t('Personal activity feed for %s', $user);
         $activities = $this->data->read($this->helper, $this->settings, 0, self::DEFAULT_PAGE_SIZE, 'all', $user);
     } catch (\UnexpectedValueException $e) {
         $l = Util::getL10N('activity');
         $description = (string) $l->t('Your feed URL is invalid');
         $activities = [['activity_id' => -1, 'timestamp' => time(), 'subject' => true, 'subjectformatted' => ['full' => $description]]];
     }
     $response = new TemplateResponse('activity', 'rss', ['rssLang' => $l->getLanguageCode(), 'rssLink' => $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show'), 'rssPubDate' => date('r'), 'description' => $description, 'activities' => $activities], '');
     if ($this->request->getHeader('accept') !== null && stristr($this->request->getHeader('accept'), 'application/rss+xml')) {
         $response->addHeader('Content-Type', 'application/rss+xml');
     } else {
         $response->addHeader('Content-Type', 'text/xml; charset=UTF-8');
     }
     return $response;
 }
Example #5
0
 /**
  * {@inheritdoc }
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getOption('path');
     $privateKeyPath = $input->getOption('privateKey');
     $keyBundlePath = $input->getOption('certificate');
     if (is_null($path) || is_null($privateKeyPath) || is_null($keyBundlePath)) {
         $documentationUrl = $this->urlGenerator->linkToDocs('developer-code-integrity');
         $output->writeln('This command requires the --path, --privateKey and --certificate.');
         $output->writeln('Example: ./occ integrity:sign-app --path="/Users/lukasreschke/Programming/myapp/" --privateKey="/Users/lukasreschke/private/myapp.key" --certificate="/Users/lukasreschke/public/mycert.crt"');
         $output->writeln('For more information please consult the documentation: ' . $documentationUrl);
         return null;
     }
     $privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath);
     $keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath);
     if ($privateKey === false) {
         $output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath));
         return null;
     }
     if ($keyBundle === false) {
         $output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath));
         return null;
     }
     $rsa = new RSA();
     $rsa->loadKey($privateKey);
     $x509 = new X509();
     $x509->loadX509($keyBundle);
     $x509->setPrivateKey($rsa);
     $this->checker->writeAppSignature($path, $x509, $rsa);
     $output->writeln('Successfully signed "' . $path . '"');
 }
Example #6
0
 public function setRSSToken($rssToken)
 {
     if ($rssToken) {
         $this->rssLink = $this->URLGenerator->getAbsoluteURL($this->URLGenerator->linkToRoute('activity.rss', array('token' => $rssToken)));
     } else {
         $this->rssLink = '';
     }
 }
Example #7
0
 /**
  * @NoAdminRequired
  * @UseSession
  *
  * @return RedirectResponse
  */
 public function logout()
 {
     $loginToken = $this->request->getCookie('oc_token');
     if (!is_null($loginToken)) {
         $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
     }
     $this->userSession->logout();
     return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
 }
Example #8
0
 /**
  * @param IURLGenerator $urlGenerator
  * @param string $appName
  * @param \Exception $exception
  *
  * @return RedirectResponse
  */
 public function htmlError($urlGenerator, $appName, Exception $exception)
 {
     $message = $exception->getMessage();
     $code = $this->getHttpStatusCode($exception);
     $url = $urlGenerator->linkToRoute($appName . '.page.error_page', ['code' => $code]);
     $response = new RedirectResponse($url);
     $response->addCookie('galleryErrorMessage', $message);
     return $response;
 }
Example #9
0
 /**
  * @param string $path
  * @param bool $isDir
  * @return string
  */
 protected function getPreviewLink($path, $isDir)
 {
     if ($isDir) {
         return $this->urlGenerator->linkTo('files', 'index.php', array('dir' => $path));
     } else {
         $parentDir = substr_count($path, '/') === 1 ? '/' : dirname($path);
         $fileName = basename($path);
         return $this->urlGenerator->linkTo('files', 'index.php', array('dir' => $parentDir, 'scrollto' => $fileName));
     }
 }
 public function testLogoutWithToken()
 {
     $this->request->expects($this->once())->method('getCookie')->with('oc_token')->willReturn('MyLoginToken');
     $user = $this->getMock('\\OCP\\IUser');
     $user->expects($this->once())->method('getUID')->willReturn('JohnDoe');
     $this->userSession->expects($this->once())->method('getUser')->willReturn($user);
     $this->config->expects($this->once())->method('deleteUserValue')->with('JohnDoe', 'login_token', 'MyLoginToken');
     $this->urlGenerator->expects($this->once())->method('linkToRouteAbsolute')->with('core.login.showLoginForm')->willReturn('/login');
     $expected = new RedirectResponse('/login');
     $this->assertEquals($expected, $this->loginController->logout());
 }
Example #11
0
 /**
  * Get all items for the users we want to send an email to
  *
  * @return array Notification data (user => array of rows from the table)
  */
 public function getLinkList()
 {
     $topEntries = [['id' => 'all', 'name' => (string) $this->l->t('All Activities'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList')]];
     if ($this->user && $this->userSettings->getUserSetting($this->user, 'setting', 'self')) {
         $topEntries[] = ['id' => 'self', 'name' => (string) $this->l->t('Activities by you'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'self'))];
         $topEntries[] = ['id' => 'by', 'name' => (string) $this->l->t('Activities by others'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'by'))];
     }
     $additionalEntries = $this->activityManager->getNavigation();
     $topEntries = array_merge($topEntries, $additionalEntries['top']);
     return array('top' => $topEntries, 'apps' => $additionalEntries['apps']);
 }
Example #12
0
 /**
  * @param string $file the xml file to be loaded
  * @return null|array where null is an indicator for an error
  */
 public function parse($file)
 {
     if (!file_exists($file)) {
         return null;
     }
     libxml_use_internal_errors(true);
     $loadEntities = libxml_disable_entity_loader(false);
     $xml = simplexml_load_file($file);
     libxml_disable_entity_loader($loadEntities);
     if ($xml == false) {
         libxml_clear_errors();
         return null;
     }
     $array = $this->xmlToArray($xml);
     if (is_null($array)) {
         return null;
     }
     if (!array_key_exists('info', $array)) {
         $array['info'] = array();
     }
     if (!array_key_exists('remote', $array)) {
         $array['remote'] = array();
     }
     if (!array_key_exists('public', $array)) {
         $array['public'] = array();
     }
     if (!array_key_exists('types', $array)) {
         $array['types'] = array();
     }
     if (array_key_exists('documentation', $array) && is_array($array['documentation'])) {
         foreach ($array['documentation'] as $key => $url) {
             // If it is not an absolute URL we assume it is a key
             // i.e. admin-ldap will get converted to go.php?to=admin-ldap
             if (!$this->httpHelper->isHTTPURL($url)) {
                 $url = $this->urlGenerator->linkToDocs($url);
             }
             $array['documentation'][$key] = $url;
         }
     }
     if (array_key_exists('types', $array)) {
         if (is_array($array['types'])) {
             foreach ($array['types'] as $type => $v) {
                 unset($array['types'][$type]);
                 if (is_string($type)) {
                     $array['types'][] = $type;
                 }
             }
         } else {
             $array['types'] = array();
         }
     }
     return $array;
 }
Example #13
0
 public function toCollection(IURLGenerator $urlGenerator, $userFolder)
 {
     $nodes = $userFolder->getById($this->getFileId());
     if (count($nodes) == 0) {
         throw new \OCP\Files\NotFoundException();
     }
     // get the first valid node
     $node = $nodes[0];
     $path = $node->getPath();
     $relativePath = $userFolder->getRelativePath($path);
     return array('title' => $this->getTitle(), 'number' => $this->getNumber(), 'artistId' => $this->getArtistId(), 'albumId' => $this->getAlbumId(), 'files' => array($this->getMimetype() => $urlGenerator->getAbsoluteUrl('remote.php/webdav' . $relativePath)), 'id' => $this->getId());
 }
 public function testAppNavigation()
 {
     $this->navigationManager->expects($this->once())->method('add')->willReturnCallback(function ($closure) {
         $this->assertInstanceOf('\\Closure', $closure);
         $navigation = $closure();
         $this->assertInternalType('array', $navigation);
         $this->assertCount(5, $navigation);
         $this->assertSame(['id' => 'announcementcenter', 'order' => 10, 'href' => '/apps/announcementcenter/announcement', 'icon' => '/apps/announcementcenter/img/announcementcenter.svg', 'name' => 'Announcements'], $navigation);
     });
     $this->urlGenerator->expects($this->once())->method('linkToRoute')->with('announcementcenter.page.index')->willReturn('/apps/announcementcenter/announcement');
     $this->urlGenerator->expects($this->once())->method('imagePath')->with('announcementcenter', 'announcementcenter.svg')->willReturn('/apps/announcementcenter/img/announcementcenter.svg');
     $this->languageFactory->expects($this->once())->method('get')->with('announcementcenter')->willReturn($this->language);
     include __DIR__ . '/../../appinfo/app.php';
 }
Example #15
0
 /**
  * Redirects the client to an error page
  *
  * @param string $message
  * @param int $code
  *
  * @return RedirectResponse
  */
 private function redirectToErrorPage($message, $code)
 {
     $url = $this->urlGenerator->linkToRoute($this->appName . '.page.error_page', ['code' => $code]);
     $response = new RedirectResponse($url);
     $response->addCookie('galleryErrorMessage', $message);
     return $response;
 }
 /**
  * @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);
 }
 /**
  * Send a notification to one user
  *
  * @param string $userName Username of the recipient
  * @param string $email Email address of the recipient
  * @param string $lang Selected language of the recipient
  * @param string $timezone Selected timezone of the recipient
  * @param int $maxTime
  */
 public function sendEmailToUser($userName, $email, $lang, $timezone, $maxTime)
 {
     $user = $this->userManager->get($userName);
     if (!$user instanceof IUser) {
         return;
     }
     list($mailData, $skippedCount) = $this->getItemsForUser($userName, $maxTime);
     $l = $this->getLanguage($lang);
     $this->dataHelper->setUser($userName);
     $this->dataHelper->setL10n($l);
     $activityList = array();
     foreach ($mailData as $activity) {
         $relativeDateTime = $this->dateFormatter->formatDateTimeRelativeDay($activity['amq_timestamp'], 'long', 'medium', new \DateTimeZone($timezone), $l);
         $activityList[] = array($this->dataHelper->translation($activity['amq_appid'], $activity['amq_subject'], $this->dataHelper->getParameters($activity['amq_subjectparams'])), $relativeDateTime);
     }
     $alttext = new Template('activity', 'email.notification', '');
     $alttext->assign('username', $user->getDisplayName());
     $alttext->assign('activities', $activityList);
     $alttext->assign('skippedCount', $skippedCount);
     $alttext->assign('owncloud_installation', $this->urlGenerator->getAbsoluteURL('/'));
     $alttext->assign('overwriteL10N', $l);
     $emailText = $alttext->fetchPage();
     $message = $this->mailer->createMessage();
     $message->setTo([$email => $user->getDisplayName()]);
     $message->setSubject((string) $l->t('Activity notification'));
     $message->setPlainBody($emailText);
     $message->setFrom([$this->getSenderData('email') => $this->getSenderData('name')]);
     $this->mailer->send($message);
 }
 public function testRescanFailedIntegrityCheck()
 {
     $this->checker->expects($this->once())->method('runInstanceVerification');
     $this->urlGenerator->expects($this->once())->method('linkToRoute')->with('settings_admin')->will($this->returnValue('/admin'));
     $expected = new RedirectResponse('/admin');
     $this->assertEquals($expected, $this->checkSetupController->rescanFailedIntegrityCheck());
 }
 private function createPublicUrl($parameter)
 {
     $route = 'myapp.author_api.do_something';
     $parameters = array('id' => $parameter);
     $url = $this->urlGenerator->linkToRoute($route, $parameters);
     return new RedirectResponse($url);
 }
Example #20
0
 /**
  * @PublicPage
  * @NoCSRFRequired
  *
  * @return TemplateResponse
  */
 public function show()
 {
     try {
         $user = $this->activityManager->getCurrentUserId();
         $userLang = $this->config->getUserValue($user, 'core', 'lang');
         // Overwrite user and language in the helper
         $this->l = $this->l10nFactory->get('activity', $userLang);
         $parser = new PlainTextParser($this->l);
         $this->helper->setL10n($this->l);
         $this->helper->setUser($user);
         $description = (string) $this->l->t('Personal activity feed for %s', $user);
         $response = $this->data->get($this->helper, $this->settings, $user, 0, self::DEFAULT_PAGE_SIZE, 'desc', 'all');
         $data = $response['data'];
         $activities = [];
         foreach ($data as $activity) {
             $activity['subject_prepared'] = $parser->parseMessage($activity['subject_prepared']);
             $activity['message_prepared'] = $parser->parseMessage($activity['message_prepared']);
             $activities[] = $activity;
         }
     } catch (\UnexpectedValueException $e) {
         $this->l = $this->l10nFactory->get('activity');
         $description = (string) $this->l->t('Your feed URL is invalid');
         $activities = [['activity_id' => -1, 'timestamp' => time(), 'subject' => true, 'subject_prepared' => $description]];
     }
     $response = new TemplateResponse('activity', 'rss', ['rssLang' => $this->l->getLanguageCode(), 'rssLink' => $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show'), 'rssPubDate' => date('r'), 'description' => $description, 'activities' => $activities], '');
     if ($this->request->getHeader('accept') !== null && stristr($this->request->getHeader('accept'), 'application/rss+xml')) {
         $response->addHeader('Content-Type', 'application/rss+xml');
     } else {
         $response->addHeader('Content-Type', 'text/xml; charset=UTF-8');
     }
     return $response;
 }
Example #21
0
 /**
  * @dataProvider dataGetShare
  */
 public function testGetShare(\OCP\Share\IShare $share, array $result)
 {
     $ocs = $this->getMockBuilder('OCA\\Files_Sharing\\API\\Share20OCS')->setConstructorArgs([$this->shareManager, $this->groupManager, $this->userManager, $this->request, $this->rootFolder, $this->urlGenerator, $this->currentUser])->setMethods(['canAccessShare'])->getMock();
     $ocs->method('canAccessShare')->willReturn(true);
     $this->shareManager->expects($this->once())->method('getShareById')->with($share->getFullId())->willReturn($share);
     $userFolder = $this->getMock('OCP\\Files\\Folder');
     $userFolder->method('getRelativePath')->will($this->returnArgument(0));
     $this->rootFolder->method('getUserFolder')->with($share->getShareOwner())->willReturn($userFolder);
     $this->urlGenerator->method('linkToRouteAbsolute')->willReturn('url');
     $initiator = $this->getMock('OCP\\IUser');
     $initiator->method('getUID')->willReturn('initiatorId');
     $initiator->method('getDisplayName')->willReturn('initiatorDisplay');
     $owner = $this->getMock('OCP\\IUser');
     $owner->method('getUID')->willReturn('ownerId');
     $owner->method('getDisplayName')->willReturn('ownerDisplay');
     $user = $this->getMock('OCP\\IUser');
     $user->method('getUID')->willReturn('userId');
     $user->method('getDisplayName')->willReturn('userDisplay');
     $group = $this->getMock('OCP\\IGroup');
     $group->method('getGID')->willReturn('groupId');
     $this->userManager->method('get')->will($this->returnValueMap([['userId', $user], ['initiatorId', $initiator], ['ownerId', $owner]]));
     $this->groupManager->method('get')->will($this->returnValueMap([['group', $group]]));
     $expected = new \OC_OCS_Result([$result]);
     $this->assertEquals($expected->getData(), $ocs->getShare($share->getId())->getData());
 }
 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);
         }
     }
 }
Example #23
0
 /**
  * Redirects to the file list and highlight the given file id
  *
  * @param string $fileId file id to show
  * @return RedirectResponse redirect response or not found response
  * @throws \OCP\Files\NotFoundException
  *
  * @NoCSRFRequired
  * @NoAdminRequired
  */
 public function showFile($fileId)
 {
     $uid = $this->userSession->getUser()->getUID();
     $baseFolder = $this->rootFolder->get($uid . '/files/');
     $files = $baseFolder->getById($fileId);
     $params = [];
     if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
         $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
         $files = $baseFolder->getById($fileId);
         $params['view'] = 'trashbin';
     }
     if (!empty($files)) {
         $file = current($files);
         if ($file instanceof Folder) {
             // set the full path to enter the folder
             $params['dir'] = $baseFolder->getRelativePath($file->getPath());
         } else {
             // set parent path as dir
             $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
             // and scroll to the entry
             $params['scrollto'] = $file->getName();
         }
         return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
     }
     throw new \OCP\Files\NotFoundException();
 }
Example #24
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, '');
     }
 }
 /**
  * Prepares a file parameter for usage
  *
  * Removes the path from filenames and adds highlights
  *
  * @param string $param
  * @param bool $stripPath Shall we remove the path from the filename
  * @param bool $highlightParams
  * @return string
  */
 protected function prepareFileParam($param, $stripPath, $highlightParams)
 {
     $param = $this->fixLegacyFilename($param);
     $is_dir = $this->rootView->is_dir('/' . $this->user . '/files' . $param);
     if ($is_dir) {
         $linkData = ['dir' => $param];
     } else {
         $parentDir = substr_count($param, '/') === 1 ? '/' : dirname($param);
         $fileName = basename($param);
         $linkData = ['dir' => $parentDir, 'scrollto' => $fileName];
     }
     $fileLink = $this->urlGenerator->linkTo('files', 'index.php', $linkData);
     $param = trim($param, '/');
     list($path, $name) = $this->splitPathFromFilename($param);
     if (!$stripPath || $path === '') {
         if (!$highlightParams) {
             return $param;
         }
         return '<a class="filename" href="' . $fileLink . '">' . Util::sanitizeHTML($param) . '</a>';
     }
     if (!$highlightParams) {
         return $name;
     }
     $title = ' title="' . $this->l->t('in %s', array(Util::sanitizeHTML($path))) . '"';
     return '<a class="filename has-tooltip" href="' . $fileLink . '"' . $title . '>' . Util::sanitizeHTML($name) . '</a>';
 }
Example #26
0
 /**
  * @param string $user
  * @throws \Exception
  */
 protected function sendEmail($user)
 {
     if (!$this->userManager->userExists($user)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
     }
     $email = $this->config->getUserValue($user, 'settings', 'email');
     if (empty($email)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.'));
     }
     $token = $this->secureRandom->getMediumStrengthGenerator()->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
     $this->config->setUserValue($user, 'owncloud', 'lostpassword', $token);
     $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
     $tmpl = new \OC_Template('core/lostpassword', 'email');
     $tmpl->assign('link', $link, false);
     $msg = $tmpl->fetchPage();
     try {
         $message = $this->mailer->createMessage();
         $message->setTo([$email => $user]);
         $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
         $message->setPlainBody($msg);
         $message->setFrom([$this->from => $this->defaults->getName()]);
         $this->mailer->send($message);
     } catch (\Exception $e) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.'));
     }
 }
 /**
  * @param $uri
  * @param $context
  * @return HTMLPurifier_URI
  */
 private function filterHttp(&$uri, $context)
 {
     $originalURL = urlencode($uri->scheme . '://' . $uri->host . $uri->path);
     if ($uri->query !== null) {
         $originalURL = $originalURL . urlencode('?' . $uri->query);
     }
     // Get the HTML attribute
     $element = $context->get('CurrentAttr');
     // If element is of type "href" it is most likely a link that should get redirected
     // otherwise it's an element that we send through our proxy
     if ($element === 'href') {
         $uri = new \HTMLPurifier_URI(Util::getServerProtocol(), null, Util::getServerHost(), null, $this->urlGenerator->linkToRoute('mail.proxy.redirect'), 'src=' . $originalURL, null);
         return $uri;
     } else {
         $uri = new \HTMLPurifier_URI(Util::getServerProtocol(), null, Util::getServerHost(), null, $this->urlGenerator->linkToRoute('mail.proxy.proxy'), 'src=' . $originalURL . '&requesttoken=' . \OC::$server->getSession()->get('requesttoken'), null);
         return $uri;
     }
 }
 /**
  * Get all items for the users we want to send an email to
  *
  * @return array Notification data (user => array of rows from the table)
  */
 public function getLinkList()
 {
     $topEntries = array(array('id' => 'all', 'name' => (string) $this->l->t('All Activities'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList')), array('id' => 'self', 'name' => (string) $this->l->t('Activities by you'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'self'))), array('id' => 'by', 'name' => (string) $this->l->t('Activities by others'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'by'))), array('id' => 'shares', 'name' => (string) $this->l->t('Shares'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'shares'))));
     $appFilterEntries = array(array('id' => 'files', 'name' => (string) $this->l->t('Files'), 'url' => $this->URLGenerator->linkToRoute('activity.Activities.showList', array('filter' => 'files'))));
     $additionalEntries = $this->activityManager->getNavigation();
     $topEntries = array_merge($topEntries, $additionalEntries['top']);
     $appFilterEntries = array_merge($appFilterEntries, $additionalEntries['apps']);
     return array('top' => $topEntries, 'apps' => $appFilterEntries);
 }
 public function afterException($controller, $methodName, Exception $exception)
 {
     if ($exception instanceof TwoFactorAuthRequiredException) {
         return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', ['redirect_url' => urlencode($this->request->server['REQUEST_URI'])]));
     }
     if ($exception instanceof UserAlreadyLoggedInException) {
         return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
     }
 }
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  * @CORS
  *
  * Sends the file matching the fileId
  *
  * @param int $fileId the ID of the file we want to download
  * @param string|null $filename
  *
  * @return ImageResponse|RedirectResponse
  */
 public function download($fileId, $filename = null)
 {
     $download = $this->getDownload($fileId, $filename);
     if (!$download) {
         $url = $this->urlGenerator->linkToRoute($this->appName . '.page.error_page', ['message' => 'There was a problem accessing the file', 'code' => Http::STATUS_NOT_FOUND]);
         return new RedirectResponse($url);
     }
     return new ImageResponse($download);
 }