Form.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. $post = $_POST;
  329. $grav = Grav::instance();
  330. $uri = $grav['uri']->url;
  331. $config = $grav['config'];
  332. $session = $grav['session'];
  333. $settings = $this->data->blueprints()->schema()->getProperty($post['name']);
  334. $settings = (object) array_merge(
  335. ['destination' => $config->get('plugins.form.files.destination', 'self@'),
  336. 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false),
  337. 'random_name' => $config->get('plugins.form.files.random_name', false),
  338. 'accept' => $config->get('plugins.form.files.accept', ['image/*']),
  339. 'limit' => $config->get('plugins.form.files.limit', 10),
  340. 'filesize' => $this->getMaxFilesize(),
  341. ],
  342. (array) $settings,
  343. ['name' => $post['name']]
  344. );
  345. // Allow plugins to adapt settings for a given post name
  346. // Useful if schema retrieval is not an option, e.g. dynamically created forms
  347. $grav->fireEvent('onFormUploadSettings', new Event(['settings' => &$settings, 'post' => $post]));
  348. $upload = $this->normalizeFiles($_FILES['data'], $settings->name);
  349. // Handle errors and breaks without proceeding further
  350. if ($upload->file->error != UPLOAD_ERR_OK) {
  351. // json_response
  352. return [
  353. 'status' => 'error',
  354. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $upload->file->name, $this->upload_errors[$upload->file->error])
  355. ];
  356. }
  357. // Handle bad filenames.
  358. $filename = $upload->file->name;
  359. if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, ". ") !== $filename || preg_match('|\.php|', $filename)) {
  360. $this->admin->json_response = [
  361. 'status' => 'error',
  362. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  363. $filename, 'Bad filename')
  364. ];
  365. return false;
  366. }
  367. // Remove the error object to avoid storing it
  368. unset($upload->file->error);
  369. // Handle Accepted file types
  370. // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
  371. $accepted = false;
  372. $errors = [];
  373. foreach ((array) $settings->accept as $type) {
  374. // Force acceptance of any file when star notation
  375. if ($type === '*') {
  376. $accepted = true;
  377. break;
  378. }
  379. $isMime = strstr($type, '/');
  380. $find = str_replace('*', '.*', $type);
  381. $match = preg_match('#'. $find .'$#', $isMime ? $upload->file->type : $upload->file->name);
  382. if (!$match) {
  383. $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
  384. $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
  385. $accepted |= false;
  386. } else {
  387. $accepted |= true;
  388. }
  389. }
  390. if (!$accepted) {
  391. // json_response
  392. return [
  393. 'status' => 'error',
  394. 'message' => implode('<br/>', $errors)
  395. ];
  396. }
  397. // Handle file size limits
  398. $settings->filesize *= self::BYTES_TO_MB; // 1024 * 1024 [MB in Bytes]
  399. if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) {
  400. // json_response
  401. return [
  402. 'status' => 'error',
  403. 'message' => $grav['language']->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')
  404. ];
  405. }
  406. // we need to move the file at this stage or else
  407. // it won't be available upon save later on
  408. // since php removes it from the upload location
  409. $tmp_dir = $grav['locator']->findResource('tmp://', true, true);
  410. $tmp_file = $upload->file->tmp_name;
  411. $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file);
  412. Folder::create(dirname($tmp));
  413. if (!move_uploaded_file($tmp_file, $tmp)) {
  414. // json_response
  415. return [
  416. 'status' => 'error',
  417. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $tmp)
  418. ];
  419. }
  420. $upload->file->tmp_name = $tmp;
  421. // Retrieve the current session of the uploaded files for the field
  422. // and initialize it if it doesn't exist
  423. $sessionField = base64_encode($uri);
  424. $flash = $session->getFlashObject('files-upload');
  425. if (!$flash) {
  426. $flash = [];
  427. }
  428. if (!isset($flash[$sessionField])) {
  429. $flash[$sessionField] = [];
  430. }
  431. if (!isset($flash[$sessionField][$upload->field])) {
  432. $flash[$sessionField][$upload->field] = [];
  433. }
  434. // Set destination
  435. $destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
  436. $destination = $this->getPagePathFromToken($destination);
  437. // Create destination if needed
  438. if (!is_dir($destination)) {
  439. Folder::mkdir($destination);
  440. }
  441. // Generate random name if required
  442. if ($settings->random_name) {
  443. $extension = pathinfo($upload->file->name)['extension'];
  444. $upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
  445. }
  446. // Handle conflicting name if needed
  447. if ($settings->avoid_overwriting) {
  448. if (file_exists($destination . '/' . $upload->file->name)) {
  449. $upload->file->name = date('YmdHis') . '-' . $upload->file->name;
  450. }
  451. }
  452. // Prepare object for later save
  453. $path = $destination . '/' . $upload->file->name;
  454. $upload->file->path = $path;
  455. // $upload->file->route = $page ? $path : null;
  456. // Prepare data to be saved later
  457. $flash[$sessionField][$upload->field][$path] = (array) $upload->file;
  458. // Finally store the new uploaded file in the field session
  459. $session->setFlashObject('files-upload', $flash);
  460. // json_response
  461. $json_response = [
  462. 'status' => 'success',
  463. 'session' => \json_encode([
  464. 'sessionField' => base64_encode($uri),
  465. 'path' => $upload->file->path,
  466. 'field' => $settings->name
  467. ])
  468. ];
  469. // Return JSON
  470. header('Content-Type: application/json');
  471. echo json_encode($json_response);
  472. exit;
  473. }
  474. /**
  475. * Removes a file from the flash object session, before it gets saved
  476. *
  477. * @return bool True if the action was performed.
  478. */
  479. public function filesSessionRemove()
  480. {
  481. $grav = Grav::instance();
  482. $post = $_POST;
  483. $session = $grav['session'];
  484. // Retrieve the current session of the uploaded files for the field
  485. // and initialize it if it doesn't exist
  486. $sessionField = base64_encode($grav['uri']->url(true));
  487. $request = \json_decode($post['session']);
  488. // Ensure the URI requested matches the current one, otherwise fail
  489. if ($request->sessionField !== $sessionField) {
  490. return false;
  491. }
  492. // Retrieve the flash object and remove the requested file from it
  493. $flash = $session->getFlashObject('files-upload');
  494. $endpoint = $flash[$request->sessionField][$request->field][$request->path];
  495. if (isset($endpoint)) {
  496. if (file_exists($endpoint['tmp_name'])) {
  497. unlink($endpoint['tmp_name']);
  498. }
  499. unset($endpoint);
  500. }
  501. // Walk backward to cleanup any empty field that's left
  502. // Field
  503. if (isset($flash[$request->sessionField][$request->field][$request->path])) {
  504. unset($flash[$request->sessionField][$request->field][$request->path]);
  505. }
  506. // Field
  507. if (isset($flash[$request->sessionField][$request->field]) && empty($flash[$request->sessionField][$request->field])) {
  508. unset($flash[$request->sessionField][$request->field]);
  509. }
  510. // Session Field
  511. if (isset($flash[$request->sessionField]) && empty($flash[$request->sessionField])) {
  512. unset($flash[$request->sessionField]);
  513. }
  514. // If there's anything left to restore in the flash object, do so
  515. if (count($flash)) {
  516. $session->setFlashObject('files-upload', $flash);
  517. }
  518. // json_response
  519. $json_response = ['status' => 'success'];
  520. // Return JSON
  521. header('Content-Type: application/json');
  522. echo json_encode($json_response);
  523. exit;
  524. }
  525. /**
  526. * Handle form processing on POST action.
  527. */
  528. public function post()
  529. {
  530. $grav = Grav::instance();
  531. $uri = $grav['uri'];
  532. $url = $uri->url;
  533. $session = $grav['session'];
  534. $post = $uri->post();
  535. if ($post) {
  536. $this->values = new Data((array)$post);
  537. $data = $this->values->get('data');
  538. // Add post data to form dataset
  539. if (!$data) {
  540. $data = $this->values->toArray();
  541. }
  542. if (!$this->values->get('form-nonce') || !Utils::verifyNonce($this->values->get('form-nonce'), 'form')) {
  543. $this->status = 'error';
  544. $event = new Event(['form' => $this,
  545. 'message' => $grav['language']->translate('PLUGIN_FORM.NONCE_NOT_VALIDATED')
  546. ]);
  547. $grav->fireEvent('onFormValidationError', $event);
  548. return;
  549. }
  550. $i = 0;
  551. foreach ($this->items['fields'] as $key => $field) {
  552. $name = isset($field['name']) ? $field['name'] : $key;
  553. if (!isset($field['name'])) {
  554. if (isset($data[$i])) { //Handle input@ false fields
  555. $data[$name] = $data[$i];
  556. unset($data[$i]);
  557. }
  558. }
  559. if ($field['type'] === 'checkbox' || $field['type'] === 'switch') {
  560. $data[$name] = isset($data[$name]) ? true : false;
  561. }
  562. $i++;
  563. }
  564. $this->data->merge($data);
  565. }
  566. // Validate and filter data
  567. try {
  568. $grav->fireEvent('onFormPrepareValidation', new Event(['form' => $this]));
  569. $this->data->validate();
  570. $this->data->filter();
  571. $grav->fireEvent('onFormValidationProcessed', new Event(['form' => $this]));
  572. } catch (ValidationException $e) {
  573. $this->status = 'error';
  574. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => $e->getMessages()]);
  575. $grav->fireEvent('onFormValidationError', $event);
  576. if ($event->isPropagationStopped()) {
  577. return;
  578. }
  579. } catch (\RuntimeException $e) {
  580. $this->status = 'error';
  581. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => []]);
  582. $grav->fireEvent('onFormValidationError', $event);
  583. if ($event->isPropagationStopped()) {
  584. return;
  585. }
  586. }
  587. // Process previously uploaded files for the current URI
  588. // and finally store them. Everything else will get discarded
  589. $queue = $session->getFlashObject('files-upload');
  590. $queue = $queue[base64_encode($url)];
  591. if (is_array($queue)) {
  592. // Allow plugins to implement additional / alternative logic
  593. // Add post to event data
  594. $grav->fireEvent('onFormStoreUploads', new Event(['queue' => &$queue, 'form' => $this, 'post' => $post]));
  595. foreach ($queue as $key => $files) {
  596. foreach ($files as $destination => $file) {
  597. if (!rename($file['tmp_name'], $destination)) {
  598. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
  599. }
  600. unset($files[$destination]['tmp_name']);
  601. }
  602. $this->data->merge([$key => $files]);
  603. }
  604. }
  605. $process = isset($this->items['process']) ? $this->items['process'] : [];
  606. if (is_array($process)) {
  607. $event = null;
  608. foreach ($process as $action => $data) {
  609. if (is_numeric($action)) {
  610. $action = \key($data);
  611. $data = $data[$action];
  612. }
  613. $previousEvent = $event;
  614. $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
  615. if ($previousEvent) {
  616. if (!$previousEvent->isPropagationStopped()) {
  617. $grav->fireEvent('onFormProcessed', $event);
  618. } else {
  619. break;
  620. }
  621. } else {
  622. $grav->fireEvent('onFormProcessed', $event);
  623. }
  624. }
  625. }
  626. }
  627. public function getPagePathFromToken($path)
  628. {
  629. return Utils::getPagePathFromToken($path, $this->page());
  630. }
  631. /**
  632. * Internal method to normalize the $_FILES array
  633. *
  634. * @param array $data $_FILES starting point data
  635. * @param string $key
  636. * @return object a new Object with a normalized list of files
  637. */
  638. protected function normalizeFiles($data, $key = '')
  639. {
  640. $files = new \stdClass();
  641. $files->field = $key;
  642. $files->file = new \stdClass();
  643. foreach ($data as $fieldName => $fieldValue) {
  644. // Since Files Upload are always happening via Ajax
  645. // we are not interested in handling `multiple="true"`
  646. // because they are always handled one at a time.
  647. // For this reason we normalize the value to string,
  648. // in case it is arriving as an array.
  649. $value = (array) Utils::getDotNotation($fieldValue, $key);
  650. $files->file->{$fieldName} = array_shift($value);
  651. }
  652. return $files;
  653. }
  654. /**
  655. * Get the nonce for a form
  656. *
  657. * @return string
  658. */
  659. public static function getNonce()
  660. {
  661. $action = 'form-plugin';
  662. return Utils::getNonce($action);
  663. }
  664. /**
  665. * Get the configured max file size in bytes
  666. *
  667. * @param bool $mbytes return size in MB
  668. * @return int
  669. */
  670. public static function getMaxFilesize($mbytes = false)
  671. {
  672. $config = Grav::instance()['config'];
  673. $filesize_mb = (int)($config->get('plugins.form.files.filesize', 0) * static::BYTES_TO_MB);
  674. $system_filesize = $config->get('system.media.upload_limit', 0);
  675. if ($filesize_mb > $system_filesize || $filesize_mb === 0) {
  676. $filesize_mb = $system_filesize;
  677. }
  678. if ($mbytes) {
  679. return $filesize_mb;
  680. }
  681. return $filesize_mb / static::BYTES_TO_MB;
  682. }
  683. public function responseCode($code = null)
  684. {
  685. if ($code) {
  686. $this->response_code = $code;
  687. }
  688. return $this->response_code;
  689. }
  690. }