Form.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. <?php
  2. namespace Grav\Plugin\Form;
  3. use Grav\Common\Data\Data;
  4. use Grav\Common\Data\Blueprint;
  5. use Grav\Common\Data\ValidationException;
  6. use Grav\Common\Filesystem\Folder;
  7. use Grav\Common\Grav;
  8. use Grav\Common\Inflector;
  9. use Grav\Common\Iterator;
  10. use Grav\Common\Page\Page;
  11. use Grav\Common\Utils;
  12. use RocketTheme\Toolbox\Event\Event;
  13. class Form extends Iterator implements \Serializable
  14. {
  15. const BYTES_TO_MB = 1048576;
  16. /**
  17. * @var string
  18. */
  19. public $message;
  20. /**
  21. * @var int
  22. */
  23. public $response_code;
  24. /**
  25. * @var string
  26. */
  27. public $status = 'success';
  28. /**
  29. * @var array
  30. */
  31. protected $header_data = [];
  32. /**
  33. * @var array
  34. */
  35. protected $rules = [];
  36. /**
  37. * Data values of the form (values to be stored)
  38. *
  39. * @var Data $data
  40. */
  41. protected $data;
  42. /**
  43. * Form header items
  44. *
  45. * @var Data $items
  46. */
  47. protected $items = [];
  48. /**
  49. * All the form data values, including non-data
  50. *
  51. * @var Data $values
  52. */
  53. protected $values;
  54. /**
  55. * The form page object
  56. *
  57. * @var Page $page
  58. */
  59. protected $page;
  60. /**
  61. * Create form for the given page.
  62. *
  63. * @param Page $page
  64. * @param string|int|null $name
  65. * @param null $form
  66. */
  67. public function __construct(Page $page, $name = null, $form = null)
  68. {
  69. parent::__construct();
  70. $this->page = $page->route();
  71. $header = $page->header();
  72. $this->rules = isset($header->rules) ? $header->rules : [];
  73. $this->header_data = isset($header->data) ? $header->data : [];
  74. if ($form) {
  75. // If form is given, use it.
  76. $this->items = $form;
  77. } elseif ($name && isset($header->forms[$name])) {
  78. // If form with that name was found, use that.
  79. $this->items = $header->forms[$name];
  80. } elseif (isset($header->form)) {
  81. // For backwards compatibility.
  82. $this->items = $header->form;
  83. } elseif (!empty($header->forms)) {
  84. // Pick up the first form.
  85. $form = reset($header->forms);
  86. $name = key($header->forms);
  87. $this->items = $form;
  88. }
  89. // Add form specific rules.
  90. if (!empty($this->items['rules']) && is_array($this->items['rules'])) {
  91. $this->rules += $this->items['rules'];
  92. }
  93. // Set form name if not set.
  94. if ($name && !is_int($name)) {
  95. $this->items['name'] = $name;
  96. } elseif (empty($this->items['name'])) {
  97. $this->items['name'] = $page->slug();
  98. }
  99. // Set form id if not set.
  100. if (empty($this->items['id'])) {
  101. $inflector = new Inflector();
  102. $this->items['id'] = $inflector->hyphenize($this->items['name']);
  103. }
  104. // Reset and initialize the form
  105. $this->reset();
  106. }
  107. /**
  108. * Custom serializer for this complex object
  109. *
  110. * @return string
  111. */
  112. public function serialize()
  113. {
  114. $data = [
  115. 'items' => $this->items,
  116. 'message' => $this->message,
  117. 'status' => $this->status,
  118. 'header_data' => $this->header_data,
  119. 'rules' => $this->rules,
  120. 'data' => $this->data->toArray(),
  121. 'values' => $this->values->toArray(),
  122. 'page' => $this->page
  123. ];
  124. return serialize($data);
  125. }
  126. /**
  127. * Custom unserializer for this complex object
  128. *
  129. * @param string $data
  130. */
  131. public function unserialize($data)
  132. {
  133. $data = unserialize($data);
  134. $this->items = $data['items'];
  135. $this->message = $data['message'];
  136. $this->status = $data['status'];
  137. $this->header_data = $data['header_data'];
  138. $this->rules = $data['rules'];
  139. $name = $this->items['name'];
  140. $items = $this->items;
  141. $rules = $this->rules;
  142. $blueprint = function () use ($name, $items, $rules) {
  143. $blueprint = new Blueprint($name, ['form' => $items, 'rules' => $rules]);
  144. return $blueprint->load()->init();
  145. };
  146. $this->data = new Data($data['data'], $blueprint);
  147. $this->values = new Data($data['values']);
  148. $this->page = $data['page'];
  149. }
  150. /**
  151. * Allow overriding of fields.
  152. *
  153. * @param array $fields
  154. */
  155. public function setFields(array $fields = [])
  156. {
  157. // Make sure blueprints are updated, otherwise validation may fail.
  158. $blueprint = $this->data->blueprints();
  159. $blueprint->set('form/fields', $fields);
  160. $blueprint->undef('form/field');
  161. $this->fields = $fields;
  162. }
  163. /**
  164. * Get the name of this form.
  165. *
  166. * @return String
  167. */
  168. public function name()
  169. {
  170. return $this->items['name'];
  171. }
  172. /**
  173. * Reset data.
  174. */
  175. public function reset()
  176. {
  177. $name = $this->items['name'];
  178. $grav = Grav::instance();
  179. // Fix naming for fields (supports nested fields now!)
  180. if (isset($this->items['fields'])) {
  181. $this->items['fields'] = $this->processFields($this->items['fields']);
  182. }
  183. $items = $this->items;
  184. $rules = $this->rules;
  185. $blueprint = function() use ($name, $items, $rules) {
  186. $blueprint = new Blueprint($name, ['form' => $items, 'rules' => $rules]);
  187. return $blueprint->load()->init();
  188. };
  189. $this->data = new Data($this->header_data, $blueprint);
  190. $this->values = new Data();
  191. $this->fields = $this->fields(true);
  192. // Fire event
  193. $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
  194. }
  195. protected function processFields($fields)
  196. {
  197. $types = Grav::instance()['plugins']->formFieldTypes;
  198. $return = array();
  199. foreach ($fields as $key => $value) {
  200. // default to text if not set
  201. if (!isset($value['type'])) {
  202. $value['type'] = 'text';
  203. }
  204. // manually merging the field types
  205. if ($types !== null && array_key_exists($value['type'], $types)) {
  206. $value += $types[$value['type']];
  207. }
  208. // Fix numeric indexes
  209. if (is_numeric($key) && isset($value['name'])) {
  210. $key = $value['name'];
  211. }
  212. if (isset($value['fields']) && is_array($value['fields'])) {
  213. $value['fields'] = $this->processFields($value['fields']);
  214. }
  215. $return[$key] = $value;
  216. }
  217. return $return;
  218. }
  219. public function fields($reset = false)
  220. {
  221. if ($reset || null === $this->fields) {
  222. $blueprint = $this->data->blueprints();
  223. if (method_exists($blueprint, 'load')) {
  224. // init the form to process directives
  225. $blueprint->load()->init();
  226. // fields set to processed blueprint fields
  227. $this->fields = $blueprint->fields();
  228. }
  229. }
  230. return $this->fields;
  231. }
  232. /**
  233. * Return page object for the form.
  234. *
  235. * @return Page
  236. */
  237. public function page()
  238. {
  239. return Grav::instance()['pages']->dispatch($this->page);
  240. }
  241. /**
  242. * Get value of given variable (or all values).
  243. * First look in the $data array, fallback to the $values array
  244. *
  245. * @param string $name
  246. *
  247. * @return mixed
  248. */
  249. public function value($name = null, $fallback = false)
  250. {
  251. if (!$name) {
  252. return $this->data;
  253. }
  254. if ($this->data->get($name)) {
  255. return $this->data->get($name);
  256. }
  257. if ($fallback) {
  258. return $this->values->get($name);
  259. }
  260. return null;
  261. }
  262. /**
  263. * Set value of given variable in the values array
  264. *
  265. * @param string $name
  266. */
  267. public function setValue($name = null, $value = '')
  268. {
  269. if (!$name) {
  270. return;
  271. }
  272. $this->values->set($name, $value);
  273. }
  274. /**
  275. * Get a value from the form
  276. *
  277. * @param $name
  278. * @return mixed
  279. */
  280. public function getValue($name)
  281. {
  282. return $this->values->get($name);
  283. }
  284. /**
  285. * @return Data
  286. */
  287. public function getValues()
  288. {
  289. return $this->values;
  290. }
  291. /**
  292. * Get all data
  293. *
  294. * @return Data
  295. */
  296. public function getData()
  297. {
  298. return $this->data;
  299. }
  300. /**
  301. * Set value of given variable in the data array
  302. *
  303. * @param string $name
  304. * @param string $value
  305. *
  306. * @return bool
  307. */
  308. public function setData($name = null, $value = '')
  309. {
  310. if (!$name) {
  311. return false;
  312. }
  313. $this->data->set($name, $value);
  314. return true;
  315. }
  316. public function setAllData($array)
  317. {
  318. $this->data = new Data($array);
  319. }
  320. /**
  321. * Handles ajax upload for files.
  322. * Stores in a flash object the temporary file and deals with potential file errors.
  323. *
  324. * @return mixed True if the action was performed.
  325. */
  326. public function uploadFiles()
  327. {
  328. $grav = Grav::instance();
  329. $config = $grav['config'];
  330. $session = $grav['session'];
  331. $uri = $grav['uri'];
  332. $url = $uri->url;
  333. $post = $uri->post();
  334. $settings = $this->data->blueprints()->schema()->getProperty($post['name']);
  335. $settings = (object) array_merge(
  336. ['destination' => $config->get('plugins.form.files.destination', 'self@'),
  337. 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false),
  338. 'random_name' => $config->get('plugins.form.files.random_name', false),
  339. 'accept' => $config->get('plugins.form.files.accept', ['image/*']),
  340. 'limit' => $config->get('plugins.form.files.limit', 10),
  341. 'filesize' => $this->getMaxFilesize(),
  342. ],
  343. (array) $settings,
  344. ['name' => $post['name']]
  345. );
  346. // Allow plugins to adapt settings for a given post name
  347. // Useful if schema retrieval is not an option, e.g. dynamically created forms
  348. $grav->fireEvent('onFormUploadSettings', new Event(['settings' => &$settings, 'post' => $post]));
  349. $upload = $this->normalizeFiles($_FILES['data'], $settings->name);
  350. // Handle errors and breaks without proceeding further
  351. if ($upload->file->error != UPLOAD_ERR_OK) {
  352. // json_response
  353. return [
  354. 'status' => 'error',
  355. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $upload->file->name, $this->upload_errors[$upload->file->error])
  356. ];
  357. }
  358. // Handle bad filenames.
  359. $filename = $upload->file->name;
  360. if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, ". ") !== $filename || preg_match('|\.php|', $filename)) {
  361. $this->admin->json_response = [
  362. 'status' => 'error',
  363. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  364. $filename, 'Bad filename')
  365. ];
  366. return false;
  367. }
  368. // Remove the error object to avoid storing it
  369. unset($upload->file->error);
  370. // Handle Accepted file types
  371. // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
  372. $accepted = false;
  373. $errors = [];
  374. foreach ((array) $settings->accept as $type) {
  375. // Force acceptance of any file when star notation
  376. if ($type === '*') {
  377. $accepted = true;
  378. break;
  379. }
  380. $isMime = strstr($type, '/');
  381. $find = str_replace('*', '.*', $type);
  382. $match = preg_match('#'. $find .'$#', $isMime ? $upload->file->type : $upload->file->name);
  383. if (!$match) {
  384. $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
  385. $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
  386. $accepted |= false;
  387. } else {
  388. $accepted |= true;
  389. }
  390. }
  391. if (!$accepted) {
  392. // json_response
  393. return [
  394. 'status' => 'error',
  395. 'message' => implode('<br/>', $errors)
  396. ];
  397. }
  398. // Handle file size limits
  399. $settings->filesize *= self::BYTES_TO_MB; // 1024 * 1024 [MB in Bytes]
  400. if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) {
  401. // json_response
  402. return [
  403. 'status' => 'error',
  404. 'message' => $grav['language']->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')
  405. ];
  406. }
  407. // we need to move the file at this stage or else
  408. // it won't be available upon save later on
  409. // since php removes it from the upload location
  410. $tmp_dir = $grav['locator']->findResource('tmp://', true, true);
  411. $tmp_file = $upload->file->tmp_name;
  412. $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file);
  413. Folder::create(dirname($tmp));
  414. if (!move_uploaded_file($tmp_file, $tmp)) {
  415. // json_response
  416. return [
  417. 'status' => 'error',
  418. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $tmp)
  419. ];
  420. }
  421. $upload->file->tmp_name = $tmp;
  422. // Retrieve the current session of the uploaded files for the field
  423. // and initialize it if it doesn't exist
  424. $sessionField = base64_encode($url);
  425. $flash = $session->getFlashObject('files-upload');
  426. if (!$flash) {
  427. $flash = [];
  428. }
  429. if (!isset($flash[$sessionField])) {
  430. $flash[$sessionField] = [];
  431. }
  432. if (!isset($flash[$sessionField][$upload->field])) {
  433. $flash[$sessionField][$upload->field] = [];
  434. }
  435. // Set destination
  436. $destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
  437. $destination = $this->getPagePathFromToken($destination);
  438. // Create destination if needed
  439. if (!is_dir($destination)) {
  440. Folder::mkdir($destination);
  441. }
  442. // Generate random name if required
  443. if ($settings->random_name) {
  444. $extension = pathinfo($upload->file->name)['extension'];
  445. $upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
  446. }
  447. // Handle conflicting name if needed
  448. if ($settings->avoid_overwriting) {
  449. if (file_exists($destination . '/' . $upload->file->name)) {
  450. $upload->file->name = date('YmdHis') . '-' . $upload->file->name;
  451. }
  452. }
  453. // Prepare object for later save
  454. $path = $destination . '/' . $upload->file->name;
  455. $upload->file->path = $path;
  456. // $upload->file->route = $page ? $path : null;
  457. // Prepare data to be saved later
  458. $flash[$sessionField][$upload->field][$path] = (array) $upload->file;
  459. // Finally store the new uploaded file in the field session
  460. $session->setFlashObject('files-upload', $flash);
  461. // json_response
  462. $json_response = [
  463. 'status' => 'success',
  464. 'session' => \json_encode([
  465. 'sessionField' => base64_encode($url),
  466. 'path' => $upload->file->path,
  467. 'field' => $settings->name
  468. ])
  469. ];
  470. // Return JSON
  471. header('Content-Type: application/json');
  472. echo json_encode($json_response);
  473. exit;
  474. }
  475. /**
  476. * Removes a file from the flash object session, before it gets saved
  477. *
  478. * @return bool True if the action was performed.
  479. */
  480. public function filesSessionRemove()
  481. {
  482. $grav = Grav::instance();
  483. $session = $grav['session'];
  484. $uri = $grav['uri'];
  485. $post = $uri->post();
  486. // Retrieve the current session of the uploaded files for the field
  487. // and initialize it if it doesn't exist
  488. $sessionField = base64_encode($grav['uri']->url(true));
  489. $request = \json_decode($post['session']);
  490. // Ensure the URI requested matches the current one, otherwise fail
  491. if ($request->sessionField !== $sessionField) {
  492. return false;
  493. }
  494. // Retrieve the flash object and remove the requested file from it
  495. $flash = $session->getFlashObject('files-upload');
  496. $endpoint = $flash[$request->sessionField][$request->field][$request->path];
  497. if (isset($endpoint)) {
  498. if (file_exists($endpoint['tmp_name'])) {
  499. unlink($endpoint['tmp_name']);
  500. }
  501. unset($endpoint);
  502. }
  503. // Walk backward to cleanup any empty field that's left
  504. // Field
  505. if (isset($flash[$request->sessionField][$request->field][$request->path])) {
  506. unset($flash[$request->sessionField][$request->field][$request->path]);
  507. }
  508. // Field
  509. if (isset($flash[$request->sessionField][$request->field]) && empty($flash[$request->sessionField][$request->field])) {
  510. unset($flash[$request->sessionField][$request->field]);
  511. }
  512. // Session Field
  513. if (isset($flash[$request->sessionField]) && empty($flash[$request->sessionField])) {
  514. unset($flash[$request->sessionField]);
  515. }
  516. // If there's anything left to restore in the flash object, do so
  517. if (count($flash)) {
  518. $session->setFlashObject('files-upload', $flash);
  519. }
  520. // json_response
  521. $json_response = ['status' => 'success'];
  522. // Return JSON
  523. header('Content-Type: application/json');
  524. echo json_encode($json_response);
  525. exit;
  526. }
  527. /**
  528. * Handle form processing on POST action.
  529. */
  530. public function post()
  531. {
  532. $grav = Grav::instance();
  533. $session = $grav['session'];
  534. $uri = $grav['uri'];
  535. $url = $uri->url;
  536. $post = $uri->post();
  537. if ($post) {
  538. $this->values = new Data((array)$post);
  539. $data = $this->values->get('data');
  540. // Add post data to form dataset
  541. if (!$data) {
  542. $data = $this->values->toArray();
  543. }
  544. if (!$this->values->get('form-nonce') || !Utils::verifyNonce($this->values->get('form-nonce'), 'form')) {
  545. $this->status = 'error';
  546. $event = new Event(['form' => $this,
  547. 'message' => $grav['language']->translate('PLUGIN_FORM.NONCE_NOT_VALIDATED')
  548. ]);
  549. $grav->fireEvent('onFormValidationError', $event);
  550. return;
  551. }
  552. $i = 0;
  553. foreach ($this->items['fields'] as $key => $field) {
  554. $name = isset($field['name']) ? $field['name'] : $key;
  555. if (!isset($field['name'])) {
  556. if (isset($data[$i])) { //Handle input@ false fields
  557. $data[$name] = $data[$i];
  558. unset($data[$i]);
  559. }
  560. }
  561. if ($field['type'] === 'checkbox' || $field['type'] === 'switch') {
  562. $data[$name] = isset($data[$name]) ? true : false;
  563. }
  564. $i++;
  565. }
  566. $this->data->merge($data);
  567. }
  568. // Validate and filter data
  569. try {
  570. $grav->fireEvent('onFormPrepareValidation', new Event(['form' => $this]));
  571. $this->data->validate();
  572. $this->data->filter();
  573. $grav->fireEvent('onFormValidationProcessed', new Event(['form' => $this]));
  574. } catch (ValidationException $e) {
  575. $this->status = 'error';
  576. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => $e->getMessages()]);
  577. $grav->fireEvent('onFormValidationError', $event);
  578. if ($event->isPropagationStopped()) {
  579. return;
  580. }
  581. } catch (\RuntimeException $e) {
  582. $this->status = 'error';
  583. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => []]);
  584. $grav->fireEvent('onFormValidationError', $event);
  585. if ($event->isPropagationStopped()) {
  586. return;
  587. }
  588. }
  589. // Process previously uploaded files for the current URI
  590. // and finally store them. Everything else will get discarded
  591. $queue = $session->getFlashObject('files-upload');
  592. $queue = $queue[base64_encode($url)];
  593. if (is_array($queue)) {
  594. // Allow plugins to implement additional / alternative logic
  595. // Add post to event data
  596. $grav->fireEvent('onFormStoreUploads', new Event(['queue' => &$queue, 'form' => $this, 'post' => $post]));
  597. foreach ($queue as $key => $files) {
  598. foreach ($files as $destination => $file) {
  599. if (!rename($file['tmp_name'], $destination)) {
  600. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
  601. }
  602. unset($files[$destination]['tmp_name']);
  603. }
  604. $this->data->merge([$key => $files]);
  605. }
  606. }
  607. $process = isset($this->items['process']) ? $this->items['process'] : [];
  608. if (is_array($process)) {
  609. $event = null;
  610. foreach ($process as $action => $data) {
  611. if (is_numeric($action)) {
  612. $action = \key($data);
  613. $data = $data[$action];
  614. }
  615. $previousEvent = $event;
  616. $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
  617. if ($previousEvent) {
  618. if (!$previousEvent->isPropagationStopped()) {
  619. $grav->fireEvent('onFormProcessed', $event);
  620. } else {
  621. break;
  622. }
  623. } else {
  624. $grav->fireEvent('onFormProcessed', $event);
  625. }
  626. }
  627. }
  628. }
  629. public function getPagePathFromToken($path)
  630. {
  631. return Utils::getPagePathFromToken($path, $this->page());
  632. }
  633. /**
  634. * Internal method to normalize the $_FILES array
  635. *
  636. * @param array $data $_FILES starting point data
  637. * @param string $key
  638. * @return object a new Object with a normalized list of files
  639. */
  640. protected function normalizeFiles($data, $key = '')
  641. {
  642. $files = new \stdClass();
  643. $files->field = $key;
  644. $files->file = new \stdClass();
  645. foreach ($data as $fieldName => $fieldValue) {
  646. // Since Files Upload are always happening via Ajax
  647. // we are not interested in handling `multiple="true"`
  648. // because they are always handled one at a time.
  649. // For this reason we normalize the value to string,
  650. // in case it is arriving as an array.
  651. $value = (array) Utils::getDotNotation($fieldValue, $key);
  652. $files->file->{$fieldName} = array_shift($value);
  653. }
  654. return $files;
  655. }
  656. /**
  657. * Get the nonce for a form
  658. *
  659. * @return string
  660. */
  661. public static function getNonce()
  662. {
  663. $action = 'form-plugin';
  664. return Utils::getNonce($action);
  665. }
  666. /**
  667. * Get the configured max file size in bytes
  668. *
  669. * @param bool $mbytes return size in MB
  670. * @return int
  671. */
  672. public static function getMaxFilesize($mbytes = false)
  673. {
  674. $config = Grav::instance()['config'];
  675. $filesize_mb = (int)($config->get('plugins.form.files.filesize', 0) * static::BYTES_TO_MB);
  676. $system_filesize = $config->get('system.media.upload_limit', 0);
  677. if ($filesize_mb > $system_filesize || $filesize_mb === 0) {
  678. $filesize_mb = $system_filesize;
  679. }
  680. if ($mbytes) {
  681. return $filesize_mb;
  682. }
  683. return $filesize_mb / static::BYTES_TO_MB;
  684. }
  685. public function responseCode($code = null)
  686. {
  687. if ($code) {
  688. $this->response_code = $code;
  689. }
  690. return $this->response_code;
  691. }
  692. }