/** * @NoAdminRequired */ public function set() { \OCP\Config::setUserValue($this->api->getUserId(), 'tasks_enhanced', $this->params('type') . '_' . $this->params('setting'), $this->params('value')); $response = new JSONResponse(); $response->setData(); return $response; }
public function testChainability() { $params = array('hi', 'yo'); $this->json->setData($params)->setStatus(Http::STATUS_NOT_FOUND); $this->assertEquals(Http::STATUS_NOT_FOUND, $this->json->getStatus()); $this->assertEquals(array('hi', 'yo'), $this->json->getData()); }
public function testSetException() { $this->config->expects($this->once())->method('setUserValue')->with('JohnDoe', 'contacts', 'keyValue', 'valueValue')->will($this->throwException(new \Exception())); $expected = new JSONResponse(); $expected->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); $this->assertEquals($expected, $this->controller->set('keyValue', 'valueValue')); }
/** * @NoAdminRequired */ public function get() { $settings = array(array('id' => 'various', 'showHidden' => (int) $this->settings->getUserValue($this->userId, $this->appName, 'various_showHidden'), 'startOfWeek' => (int) $this->settings->getUserValue($this->userId, $this->appName, 'various_startOfWeek'), 'userID' => $this->userId)); $result = array('data' => array('settings' => $settings)); $response = new JSONResponse(); $response->setData($result); return $response; }
public function testShowDoesNotExist() { $this->accountService->expects($this->once())->method('find')->with($this->equalTo($this->userId), $this->equalTo($this->accountId))->will($this->returnValue($this->account)); $this->account->expects($this->once())->method('getConfiguration')->will($this->throwException(new OCP\AppFramework\Db\DoesNotExistException('test123'))); $response = $this->controller->show($this->accountId); $expectedResponse = new JSONResponse([]); $expectedResponse->setStatus(404); $this->assertEquals($expectedResponse, $response); }
public function testWithValidCredentialsBut2faEnabled() { $user = $this->getMock('\\OCP\\IUser'); $this->userManager->expects($this->once())->method('checkPassword')->with('john', '123456')->will($this->returnValue($user)); $this->twoFactorAuthManager->expects($this->once())->method('isTwoFactorAuthenticated')->with($user)->will($this->returnValue(true)); $this->secureRandom->expects($this->never())->method('generate'); $expected = new JSONResponse(); $expected->setStatus(Http::STATUS_UNAUTHORIZED); $actual = $this->tokenController->generateToken('john', '123456'); $this->assertEquals($expected, $actual); }
/** * @NoAdminRequired * @param $backends * @return JSONResponse */ public function set($backends) { foreach ($backends as $backend) { foreach ($backend['config'] as $key => $value) { $this->configMapper->set($backend['id'], $key, $value); } } $res = new JSONResponse(); $res->setStatus(Http::STATUS_OK); return $res; }
/** * constructor of the controller * @param string $appName the name of the app * @param IRequest $request an instance of the request * @since 6.0.0 - parameter $appName was added in 7.0.0 - parameter $app was removed in 7.0.0 */ public function __construct($appName, IRequest $request) { $this->appName = $appName; $this->request = $request; // default responders $this->responders = array('json' => function ($data) { if ($data instanceof DataResponse) { $response = new JSONResponse($data->getData(), $data->getStatus()); $response->setHeaders(array_merge($data->getHeaders(), $response->getHeaders())); return $response; } else { return new JSONResponse($data); } }); }
/** * @NoAdminRequired * @NoCSRFRequired */ public function articles() { $feeds = $this->feedBusinessLayer->findAll($this->userId); $items = $this->itemBusinessLayer->getUnreadOrStarred($this->userId); // build assoc array for fast access $feedsDict = array(); foreach ($feeds as $feed) { $feedsDict['feed' . $feed->getId()] = $feed; } $articles = array(); foreach ($items as $item) { array_push($articles, $item->toExport($feedsDict)); } $response = new JSONResponse($articles); $response->addHeader('Content-Disposition', 'attachment; filename="articles.json"'); return $response; }
/** * @NoAdminRequired */ public function download($path) { if (!$path) { $response = new JSONResponse(); $response->setStatus(Http::STATUS_BAD_REQUEST); return $response; } $fullPath = '/files' . $path; $fileInfo = \OC\Files\Filesystem::getFileInfo($path); if ($fileInfo) { if ($fileInfo->getMimeType() !== \OCA\Documents\Filter\Office::NATIVE_MIMETYPE) { $file = new File($fileInfo->getId()); $genesis = new Genesis($file); $fullPath = $genesis->getPath(); } } return new DownloadResponse($this->request, $this->uid, $fullPath); }
/** * @NoAdminRequired */ public function getCollections() { $collections = array(array('id' => "starred", 'displayname' => (string) $this->l10n->t('Important'), 'show' => 2), array('id' => "today", 'displayname' => (string) $this->l10n->t('Today'), 'show' => 2), array('id' => "week", 'displayname' => (string) $this->l10n->t('Week'), 'show' => 2), array('id' => "all", 'displayname' => (string) $this->l10n->t('All'), 'show' => 2), array('id' => "current", 'displayname' => (string) $this->l10n->t('Current'), 'show' => 2), array('id' => "completed", 'displayname' => (string) $this->l10n->t('Completed'), 'show' => 2)); foreach ($collections as $key => $collection) { try { $tmp = $this->settings->getUserValue($this->userId, $this->appName, 'show_' . $collection['id']); if (!in_array((int) $tmp, array(0, 1, 2)) || $tmp === null) { $tmp = 2; $this->settings->setUserValue($this->userId, $this->appName, 'show_' . $collection['id'], $tmp); } $collections[$key]['show'] = (int) $tmp; } catch (\Exception $e) { \OCP\Util::writeLog($this->appName, $e->getMessage(), \OCP\Util::ERROR); } } $result = array('data' => array('collections' => $collections)); $response = new JSONResponse(); $response->setData($result); return $response; }
/** * constructor of the controller * @param string $appName the name of the app * @param IRequest $request an instance of the request * @since 6.0.0 - parameter $appName was added in 7.0.0 - parameter $app was removed in 7.0.0 */ public function __construct($appName, IRequest $request) { $this->appName = $appName; $this->request = $request; // default responders $this->responders = array('json' => function ($data) { if ($data instanceof DataResponse) { $response = new JSONResponse($data->getData(), $data->getStatus()); $dataHeaders = $data->getHeaders(); $headers = $response->getHeaders(); // do not overwrite Content-Type if it already exists if (isset($dataHeaders['Content-Type'])) { unset($headers['Content-Type']); } $response->setHeaders(array_merge($dataHeaders, $headers)); return $response; } else { return new JSONResponse($data); } }); }
/** * @param \OCA\Calendar\IObject|\OCA\Calendar\IObjectCollection $data * @param TimezoneMapper $timezones * @param int $statusCode */ public function __construct($data, TimezoneMapper $timezones = null, $statusCode = Http::STATUS_OK) { $vobject = $data->getVObject(); if ($vobject) { if ($timezones) { SabreUtility::addMissingVTimezones($vobject, $timezones); } $serialized = $vobject->jsonSerialize(); parent::__construct($serialized, $statusCode); $this->addHeader('Content-type', 'application/calendar+json; charset=utf-8'); if ($data instanceof IObject) { $this->setETag($data->getEtag(true)); } } else { parent::__construct(null, HTTP::STATUS_NO_CONTENT); } }
/** * @NoAdminRequired * * @param string $key * @param string $value * @return JSONResponse */ public function set($key = '', $value = '') { $response = new JSONResponse(); if ($key === '' || $value === '') { $response->setStatus(Http::STATUS_PRECONDITION_FAILED); return $response; } try { $this->config->setUserValue($this->userId, $this->appName, $key, $value); $response->setData(['key' => $key, 'value' => $value]); return $response; } catch (\Exception $e) { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); return $response; } }
/** * Generate a new access token clients can authenticate with * * @PublicPage * @NoCSRFRequired * * @param string $user * @param string $password * @param string $name the name of the client * @return JSONResponse */ public function generateToken($user, $password, $name = 'unknown client') { if (is_null($user) || is_null($password)) { $response = new JSONResponse(); $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY); return $response; } $loginName = $user; $user = $this->userManager->checkPassword($loginName, $password); if ($user === false) { $response = new JSONResponse(); $response->setStatus(Http::STATUS_UNAUTHORIZED); return $response; } if ($this->twoFactorAuthManager->isTwoFactorAuthenticated($user)) { $resp = new JSONResponse(); $resp->setStatus(Http::STATUS_UNAUTHORIZED); return $resp; } $token = $this->secureRandom->generate(128); $this->tokenProvider->generateToken($token, $user->getUID(), $loginName, $password, $name, IToken::PERMANENT_TOKEN); return ['token' => $token]; }
/** * @NoAdminRequired * @PublicPage */ public function poll($command, $args) { $response = new JSONResponse(); try { $esId = isset($args['es_id']) ? $args['es_id'] : null; $session = new Db\Session(); $session->load($esId); $memberId = isset($args['member_id']) ? $args['member_id'] : null; $member = new Db\Member(); $member->load($memberId); if (!$member->getIsGuest()) { \OCP\JSON::checkLoggedIn(); } try { new File($session->getFileId()); } catch (\Exception $e) { $this->logger->warning('Error. Session no longer exists. ' . $e->getMessage(), array('app' => $this->appName)); $ex = new BadRequestException(); $ex->setBody(implode(',', $this->request->getParams())); throw $ex; } switch ($command) { case 'sync_ops': $seqHead = (string) isset($args['seq_head']) ? $args['seq_head'] : null; if (!is_null($seqHead)) { $ops = isset($args['client_ops']) ? $args['client_ops'] : array(); $op = new Db\Op(); $currentHead = $op->getHeadSeq($esId); try { $member->updateActivity($memberId); } catch (\Exception $e) { //Db error. Not critical } $response->setData($session->syncOps($memberId, $currentHead, $seqHead, $ops)); $inactiveMembers = $member->updateByTimeout($esId); foreach ($inactiveMembers as $inactive) { $op->removeCursor($esId, $inactive); $op->removeMember($esId, $inactive); } } else { // Error - no seq_head passed throw new BadRequestException(); } break; default: $ex = new BadRequestException(); $ex->setBody(implode(',', $this->request->getParams())); throw $ex; } } catch (BadRequestException $e) { $response->setStatus(Http::STATUS_BAD_REQUEST); $response->setData(array('err' => 'bad request:[' . $e->getBody() . ']')); } return $response; }
/** * Creates a standard response with exception data * * @param \Exception ex The exception to send back * @param string callee The calle function/route * @param int code HTTP Status code to return, default to Http::STATUS_INTERNAL_SERVER_ERROR * * @return JSONResponse */ private function createResponseException(\Exception $ex, $callee, $code = Http::STATUS_INTERNAL_SERVER_ERROR) { $response = new JSONResponse((object) array('type' => 'error', 'callee' => $callee, 'exception' => get_class($ex), 'message' => $ex->getMessage())); $response->setStatus($code); return $response; }
/** * @NoCSRFRequired * @PublicPage * * Generates a web app manifest, according to specs in: * https://developer.mozilla.org/en-US/Apps/Build/Manifest */ public function manifest() { $config = $this->appConfig->getConfig(); // size of the icons: 128x128 is required by FxOS for all app manifests $iconSizes = ['128', '512']; $icons = []; $locale = str_replace('_', '-', $this->l10n->getLanguageCode()); foreach ($iconSizes as $size) { $filename = 'app-' . $size . '.png'; if (file_exists(__DIR__ . '/../img/' . $filename)) { $icons[$size] = $this->urlGenerator->imagePath($config['id'], $filename); } } $data = [ "name" => $config['name'], "type" => 'web', "default_locale" => $locale, "description" => $config['description'], "launch_path" => $this->urlGenerator->linkToRoute( $config['navigation']['route']), "icons" => $icons, "developer" => [ "name" => $config['author'], "url" => $config['homepage'] ] ]; $response = new JSONResponse($data); $response->addHeader('Content-Type', 'application/x-web-app-manifest+json'); return $response; }
/** * @NoAdminRequired * */ public function saveUserViewSettings() { $checked = $this->params('checked'); $pName = $this->params('name'); $userConfig = ''; if (!$this->configInfo->getUserValue($this->userId, $this->appName, 'userconfig')) { $userConfig = '{"agendaDay":"true","agendaThreeDays":"false","agendaWorkWeek":"false","agendaWeek":"true","month":"true","year":"false","list":"false"}'; $userConfig = json_decode($userConfig); } else { $userConfig = json_decode($this->configInfo->getUserValue($this->userId, $this->appName, 'userconfig')); } $userConfig->{$pName} = $checked; $this->configInfo->setUserValue($this->userId, $this->appName, 'userconfig', json_encode($userConfig)); $data = ['status' => 'success', 'data' => ['name' => $pName, 'checked' => $checked], 'msg' => 'Saving success!']; $response = new JSONResponse(); $response->setData($data); return $response; }
/** * Store the document content to its origin * @NoAdminRequired */ public function save() { $response = new JSONResponse(); try { $esId = $this->request->server['HTTP_WEBODF_SESSION_ID']; $session = $this->loadSession($esId); $memberId = $this->request->server['HTTP_WEBODF_MEMBER_ID']; $currentMember = $this->loadMember($memberId, $esId); // Extra info for future usage // $sessionRevision = $this->request->server['HTTP_WEBODF_SESSION_REVISION']; //NB ouch! New document content is passed as an input stream content $stream = fopen('php://input', 'r'); if (!$stream) { throw new \Exception('New content missing'); } $content = stream_get_contents($stream); try { if ($currentMember->getIsGuest()) { $file = File::getByShareToken($currentMember->getToken()); } else { $file = new File($session->getFileId()); } $view = $file->getOwnerView(true); $path = $file->getPath(true); } catch (\Exception $e) { //File was deleted or unshared. We need to save content as new file anyway //Sorry, but for guests it would be lost :( if ($this->uid) { $view = new View('/' . $this->uid . '/files'); $dir = \OC::$server->getConfig()->getUserValue($this->uid, 'richdocuments', 'save_path', ''); $path = Helper::getNewFileName($view, $dir . 'New Document.odt'); } else { throw $e; } } $member = new Db\Member(); $members = $member->getActiveCollection($esId); $memberIds = array_map(function ($x) { return $x['member_id']; }, $members); // Active users except current user $memberCount = count($memberIds) - 1; if ($view->file_exists($path)) { $currentHash = $view->hash('sha1', $path, false); if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()) { // Original file was modified externally. Save to a new one $path = Helper::getNewFileName($view, $path, '-conflict'); } $mimetype = $view->getMimeType($path); } else { $mimetype = Storage::MIMETYPE_LIBREOFFICE_WORDPROCESSOR; } $data = Filter::write($content, $mimetype); if ($view->file_put_contents($path, $data['content'])) { // Not a last user if ($memberCount > 0) { // Update genesis hash to prevent conflicts $this->logger->debug('Update hash', ['app' => $this->appName]); $session->updateGenesisHash($esId, sha1($data['content'])); } else { // Last user. Kill session data Db\Session::cleanUp($esId); } $view->touch($path); } $response->setData(['status' => 'success']); } catch (\Exception $e) { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); $response->setData([]); $this->logger->warning('Saving failed. Reason:' . $e->getMessage(), ['app' => $this->appName]); } return $response; }
/** * @PublicPage * @NoCSRFRequired */ public function getEventsPublic() { $token = $this->params('t'); $pStart = $this->params('start'); $pEnd = $this->params('end'); $calendar_id = null; \OC::$server->getSession()->close(); if (isset($token)) { $linkItem = \OCP\Share::getShareByToken($token, false); if (is_array($linkItem) && isset($linkItem['uid_owner'])) { $rootLinkItem = \OCP\Share::resolveReShare($linkItem); if (isset($rootLinkItem['uid_owner'])) { \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']); $calendar_id = CalendarApp::validateItemSource($linkItem['item_source'], CalendarApp::SHARECALENDARPREFIX); } } } $start = new \DateTime('@' . $pStart); $end = new \DateTime('@' . $pEnd); $events = CalendarApp::getrequestedEvents($calendar_id, $start, $end); $output = array(); foreach ($events as $event) { $eventArray = CalendarApp::generateEventOutput($event, $start, $end); if (is_array($eventArray)) { $output = array_merge($output, $eventArray); } } $response = new JSONResponse(); $response->setData($output); return $response; }
public function testGetPreviewWithWrongId() { $fileId = 99999; $width = 1024; $height = 768; $this->mockGetResourceFromId($fileId, false); $errorResponse = new JSONResponse(['message' => "I'm truly sorry, but we were unable to generate a preview for this file", 'success' => false], Http::STATUS_INTERNAL_SERVER_ERROR); $response = $this->controller->getPreview($fileId, $width, $height); $this->assertEquals($errorResponse->getStatus(), $response->getStatus()); $this->assertEquals($errorResponse->getData()['success'], $response->getData()['success']); }
/** * @NoAdminRequired * @NoCSRFRequired * * @return JSONResponse */ public function get() { // When there are no apps registered that use the notifications // We stop polling for them. if (!$this->manager->hasNotifiers()) { $response = new Response(); $response->setStatus(Http::STATUS_NO_CONTENT); return $response; } $filter = $this->manager->createNotification(); $filter->setUser($this->user); $language = $this->config->getUserValue($this->user, 'core', 'lang', null); $notifications = $this->handler->get($filter); $data = []; $notificationIds = []; foreach ($notifications as $notificationId => $notification) { try { $notification = $this->manager->prepare($notification, $language); } catch (\InvalidArgumentException $e) { // The app was disabled, skip the notification continue; } $notificationIds[] = $notificationId; $data[] = $this->notificationToArray($notificationId, $notification); } $response = new JSONResponse($data); $response->setETag($this->generateEtag($notificationIds)); return $response; }
public function setStatus($status) { parent::setStatus($status); return $this; }
public function __construct($requestType, $action, $data = array()) { $data["status"] = "success"; parent::__construct(array("type" => $requestType . "::" . $action . "::response", "data" => $data)); }
/** * @NoAdminRequired * @param $accountId * @param $folders * @return JSONResponse */ public function detectChanges($accountId, $folders) { try { $query = []; foreach ($folders as $folder) { $folderId = base64_decode($folder['id']); $parts = explode('/', $folderId); if (count($parts) > 1 && $parts[1] === 'FLAGGED') { continue; } if (isset($folder['error'])) { continue; } $query[$folderId] = $folder; } $account = $this->accountService->find($this->currentUserId, $accountId); $mailBoxes = $account->getChangedMailboxes($query); return new JSONResponse($mailBoxes); } catch (\Horde_Imap_Client_Exception $e) { $response = new JSONResponse(); $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); return $response; } catch (DoesNotExistException $e) { return new JSONResponse(); } }
/** * If an SecurityException is being caught return a JSON error response * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param \Exception $exception the thrown exception * @throws \Exception the passed in exception if it cant handle it * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception) { if ($exception instanceof SecurityException) { $response = new JSONResponse(['message' => $exception->getMessage()]); if ($exception->getCode() !== 0) { $response->setStatus($exception->getCode()); } else { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); } return $response; } throw $exception; }
/** * @NoAdminRequired * @NoSubadminRequired * * @return JSONResponse */ public function create($name) { try { $sessionId = $this->session->getId(); } catch (SessionNotAvailableException $ex) { $resp = new JSONResponse(); $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE); return $resp; } try { $sessionToken = $this->tokenProvider->getToken($sessionId); $loginName = $sessionToken->getLoginName(); try { $password = $this->tokenProvider->getPassword($sessionToken, $sessionId); } catch (PasswordlessTokenException $ex) { $password = null; } } catch (InvalidTokenException $ex) { $resp = new JSONResponse(); $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE); return $resp; } $token = $this->generateRandomDeviceToken(); $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN); return ['token' => $token, 'deviceToken' => $deviceToken]; }
/** * @NoAdminRequired */ public function uploadPhoto() { //$type = $this->request->getHeader('Content-Type'); $id = $this->params('id'); $file = $this->request->getUploadedFile('imagefile'); $error = $file['error']; if ($error !== UPLOAD_ERR_OK) { $errors = array(0 => $this->l10n->t("There is no error, the file uploaded with success"), 1 => $this->l10n->t("The uploaded file exceeds the upload_max_filesize directive in php.ini") . ini_get('upload_max_filesize'), 2 => $this->l10n->t("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"), 3 => $this->l10n->t("The uploaded file was only partially uploaded"), 4 => $this->l10n->t("No file was uploaded"), 6 => $this->l10n->t("Missing a temporary folder")); \OCP\Util::writeLog($this->appName, 'Uploaderror: ' . $errors[$error], \OCP\Util::DEBUG); } if (file_exists($file['tmp_name'])) { $tmpkey = 'editphoto'; $size = getimagesize($file['tmp_name'], $info); //$exif = @exif_read_data($file['tmp_name']); $image = new \OCP\Image(); if ($image->loadFromFile($file['tmp_name'])) { if (!$image->fixOrientation()) { // No fatal error so we don't bail out. \OCP\Util::writeLog($this->appName, 'Couldn\'t save correct image orientation: ' . $tmpkey, \OCP\Util::DEBUG); } \OC::$server->getCache()->remove($tmpkey); \OC::$server->getCache()->remove($tmpkey . 'ratio'); $originalWidth = $image->width(); if (\OC::$server->getCache()->set($tmpkey, $image->data(), 600)) { if ($image->width() > 400 || $image->height() > 400) { $image->resize(400); // Prettier resizing than with browser and saves bandwidth. } $ratio = $originalWidth / $image->width(); if (\OC::$server->getCache()->set($tmpkey . 'ratio', $ratio, 600)) { $imgString = $image->__toString(); $resultData = array('mime' => $file['type'], 'size' => $file['size'], 'name' => $file['name'], 'id' => $id, 'tmp' => $tmpkey, 'imgdata' => $imgString); $response = new JSONResponse(); $response->setData($resultData); return $response; } } } } }
/** * @param \OC_OCS_Result $ocsResult * @return JSONResponse */ protected function ocsToJsonResponse(\OC_OCS_Result $ocsResult) { $response = new JSONResponse(['ocs' => ['meta' => ['status' => 'ok', 'statuscode' => 100, 'message' => null], 'data' => $ocsResult->getData()]], $ocsResult->getStatusCode() === 100 ? Http::STATUS_OK : $ocsResult->getStatusCode()); $response->setHeaders(array_merge($ocsResult->getHeaders(), ['Content-Type' => 'application/json; charset=utf-8'])); return $response; }