=========== Controllers =========== .. sectionauthor:: Bernhard Posselt Controllers are used to connect :doc:`routes ` with app logic. Think of it as callbacks that are executed once a request has come in. Controllers are defined inside the **lib/Controller/** directory. To create a controller, simply extend the Controller class and create a method that should be executed on a request: .. code-block:: php $id = 3 // $doMore = false // $value = 3.5 } } The following types will be cast: * **bool** or **boolean** * **float** * **int** or **integer** JSON parameters ^^^^^^^^^^^^^^^ It is possible to pass JSON using a POST, PUT or PATCH request. To do that the **Content-Type** header has to be set to **application/json**. The JSON is being parsed as an array and the first level keys will be used to pass in the arguments, e.g.:: POST /index.php/apps/myapp/authors Content-Type: application/json { "name": "test", "number": 3, "publisher": true, "customFields": { "mail": "test@example.com", "address": "Somewhere" } } .. code-block:: php "test@example.com", "address" => "Somewhere") } } Reading headers, files, cookies and environment variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Headers, files, cookies and environment variables can be accessed directly from the request object: .. code-block:: php request->getHeader('Content-Type'); // $_SERVER['HTTP_CONTENT_TYPE'] $cookie = $this->request->getCookie('myCookie'); // $_COOKIES['myCookie'] $file = $this->request->getUploadedFile('myfile'); // $_FILES['myfile'] $env = $this->request->getEnv('SOME_VAR'); // $_ENV['SOME_VAR'] } } Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: `because it's bad practice `_ and will make testing harder. .. _controller-use-session: Reading and writing session variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To set, get or modify session variables, the ISession object has to be injected into the controller. Nextcloud will read existing session data at the beginning of the request lifecycle and close the session afterwards. This means that in order to write to the session, the session has to be opened first. This is done implicitly when calling the set method, but would close immediately afterwards. To prevent this, the session has to be explicitly opened by calling the reopen method. Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you. .. code-block:: php :emphasize-lines: 2,7 use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Attribute\UseSession; use OCP\AppFramework\Http\Response; class PageController extends Controller { #[UseSession] public function writeASessionVariable(): Response { // ... } } .. note:: The ``#[UseSession]`` was added in Nextcloud 26 and requires PHP 8.0 or later. If your app targets older releases and PHP 7.x then use the deprecated ``@UseSession`` annotation. .. code-block:: php :emphasize-lines: 2 /** * @UseSession */ public function writeASessionVariable(): Response { // .... } In case the session may be read and written by concurrent requests of your application, keeping the session open during your controller method execution may be required to ensure that the session is locked and no other request can write to the session at the same time. When reopening the session, the session data will also get updated with the latest changes from other requests. Using the annotation will keep the session lock for the whole duration of the controller method execution. For additional information on how session locking works in PHP see the article about `PHP Session Locking: How To Prevent Sessions Blocking in PHP requests `_. Then session variables can be accessed like this: .. note:: The session is closed automatically for writing, unless you add the ``#[UseSession]`` attribute! .. code-block:: php session = $session; } #[UseSession] public function writeASessionVariable(): Response { // read a session variable $value = $this->session['value']; // write a session variable $this->session['value'] = 'new value'; } } Setting cookies ^^^^^^^^^^^^^^^ Cookies can be set or modified directly on the response class: .. code-block:: php addCookie('foo', 'bar'); $response->addCookie('bar', 'foo', new DateTime('2015-01-01 00:00')); return $response; } /** * Invalidates the cookie "foo" * Invalidates the cookie "bar" and "bazinga" */ public function invalidateCookie(): TemplateResponse { $response = new TemplateResponse(...); $response->invalidateCookie('foo'); $response->invalidateCookies(array('bar', 'bazinga')); return $response; } } Responses --------- Similar to how every controller receives a request object, every controller method has to return a Response. This can be in the form of a Response subclass or in the form of a value that can be handled by a registered responder. JSON ^^^^ Returning JSON is simple, just pass an array to a JSONResponse: .. code-block:: php 'hi'); return new JSONResponse($params); } } Because returning JSON is such a common task, there's even a shorter way to do this: .. code-block:: php 'hi'); } } Why does this work? Because the dispatcher sees that the controller did not return a subclass of a Response and asks the controller to turn the value into a Response. That's where responders come in. Responders ^^^^^^^^^^ Responders are short functions that take a value and return a response. They are used to return different kinds of responses based on a **format** parameter which is supplied by the client. Think of an API that is able to return both XML and JSON depending on if you call the URL with:: ?format=xml or:: ?format=json The appropriate responder is being chosen by the following criteria: * First the dispatcher checks the Request if there is a **format** parameter, e.g.:: ?format=xml or:: /index.php/apps/myapp/authors.{format} * If there is none, take the **Accept** header, use the first mimetype and cut off *application/*. In the following example the format would be *xml*:: Accept: application/xml, application/json * If there is no Accept header or the responder does not exist, format defaults to **json**. By default there is only a responder for JSON but more can be added easily: .. code-block:: php registerResponder('xml', function($value) { if ($value instanceof DataResponse) { return new XMLResponse( $value->getData(), $value->getStatus(), $value->getHeaders() ); } else { return new XMLResponse($value); } }); return array('test' => 'hi'); } } .. note:: The above example would only return XML if the **format** parameter was *xml*. If you want to return an XMLResponse regardless of the format parameter, extend the Response class and return a new instance of it from the controller method instead. Because returning values works fine in case of a success but not in case of failure that requires a custom HTTP error code, you can always wrap the value in a **DataResponse**. This works for both normal responses and error responses. .. code-block:: php 'not found!'), Http::STATUS_NOT_FOUND); } } } Templates ^^^^^^^^^ A :doc:`template ` can be rendered by returning a TemplateResponse. A TemplateResponse takes the following parameters: * **appName**: tells the template engine in which app the template should be located * **templateName**: the name of the template inside the templates/ folder without the .php extension * **parameters**: optional array parameters that are available in the template through $_, e.g.:: array('key' => 'something') can be accessed through:: $_['key'] * **renderAs**: defaults to *user*, tells Nextcloud if it should include it in the web interface, or in case *blank* is passed solely render the template .. code-block:: php 'hi'); return new TemplateResponse($this->appName, $templateName, $parameters); } } Public page templates ^^^^^^^^^^^^^^^^^^^^^ For public pages, that are rendered to users who are not logged in to the Nextcloud instance, a ``OCP\\AppFramework\\Http\\Template\\PublicTemplateResponse`` should be used, to load the correct base template. It also allows adding an optional set of actions that will be shown in the top right corner of the public page. .. code-block:: php appName, 'main', []); $template->setHeaderTitle('Public page'); $template->setHeaderDetails('some details'); $template->setHeaderActions([ new SimpleMenuAction('download', 'Label 1', 'icon-css-class1', 'link-url', 0), new SimpleMenuAction('share', 'Label 2', 'icon-css-class2', 'link-url', 10), ]); return $template; } } The header title and subtitle will be rendered in the header, next to the logo. The action with the highest priority (lowest number) will be used as the primary action, others will shown in the popover menu on demand. A ``OCP\\AppFramework\\Http\\Template\\SimpleMenuAction`` will be a link with an icon added to the menu. App developers can implement their own types of menu renderings by adding a custom class implementing the ``OCP\\AppFramework\\Http\\Template\\IMenuAction`` interface. Redirects ^^^^^^^^^ A redirect can be achieved by returning a RedirectResponse: .. code-block:: php addHeader('Content-Type', 'application/xml'); $this->xml = $xml; } public function render(): string { $root = new SimpleXMLElement(''); array_walk_recursive($this->xml, array ($root, 'addChild')); return $xml->asXML(); } } Streamed and lazily rendered responses ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ By default all responses are rendered at once and sent as a string through middleware. In certain cases this is not a desirable behavior, for instance if you want to stream a file in order to save memory. To do that use the now available **OCP\\AppFramework\\Http\\StreamResponse** class: .. code-block:: php `_. However if an app relies on third-party media or other features which are forbidden by the current policy the policy can be relaxed. .. note:: Double check your content and edge cases before you relax the policy! Also read the `documentation provided by MDN `_ To relax the policy pass an instance of the ContentSecurityPolicy class to your response. The methods on the class can be chained. The following methods turn off security features by passing in **true** as the **$isAllowed** parameter * **allowInlineScript** (bool $isAllowed) * **allowInlineStyle** (bool $isAllowed) * **allowEvalScript** (bool $isAllowed) * **useStrictDynamic** (bool $isAllowed) Trust all scripts that are loaded by a trusted script, see 'script-src' and 'strict-dynamic' * **useStrictDynamicOnScripts** (bool $isAllowed) Trust all scripts that are loaded by a trusted script which was loaded using a ``