Form.php 25 KB

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