Form.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. <?php
  2. namespace Grav\Plugin\Form;
  3. use Grav\Common\Config\Config;
  4. use Grav\Common\Data\Data;
  5. use Grav\Common\Data\Blueprint;
  6. use Grav\Common\Data\ValidationException;
  7. use Grav\Common\Filesystem\Folder;
  8. use Grav\Common\Form\FormFlash;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Inflector;
  11. use Grav\Common\Language\Language;
  12. use Grav\Common\Page\Interfaces\PageInterface;
  13. use Grav\Common\Security;
  14. use Grav\Common\Uri;
  15. use Grav\Common\Utils;
  16. use Grav\Framework\Filesystem\Filesystem;
  17. use Grav\Framework\Form\FormFlashFile;
  18. use Grav\Framework\Form\Interfaces\FormInterface;
  19. use Grav\Framework\Form\Traits\FormTrait;
  20. use Grav\Framework\Route\Route;
  21. use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
  22. use RocketTheme\Toolbox\Event\Event;
  23. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  24. /**
  25. * Class Form
  26. * @package Grav\Plugin\Form
  27. *
  28. * @property string $id
  29. * @property string $uniqueid
  30. * @property-read string $name
  31. * @property-read string $noncename
  32. * @property-read $string nonceaction
  33. * @property-read string $action
  34. * @property-read Data $data
  35. * @property-read array $files
  36. * @property-read Data $value
  37. * @property array $errors
  38. * @property-read array $fields
  39. * @property-read Blueprint $blueprint
  40. * @property-read PageInterface $page
  41. */
  42. class Form implements FormInterface, \ArrayAccess
  43. {
  44. use NestedArrayAccessWithGetters {
  45. NestedArrayAccessWithGetters::get as private traitGet;
  46. NestedArrayAccessWithGetters::set as private traitSet;
  47. }
  48. use FormTrait {
  49. FormTrait::reset as private traitReset;
  50. FormTrait::doSerialize as private doTraitSerialize;
  51. FormTrait::doUnserialize as private doTraitUnserialize;
  52. }
  53. public const BYTES_TO_MB = 1048576;
  54. /**
  55. * @var string
  56. */
  57. public $message;
  58. /**
  59. * @var int
  60. */
  61. public $response_code;
  62. /**
  63. * @var string
  64. */
  65. public $status = 'success';
  66. /**
  67. * @var array
  68. */
  69. protected $header_data = [];
  70. /**
  71. * @var array
  72. */
  73. protected $rules = [];
  74. /**
  75. * Form header items
  76. *
  77. * @var array $items
  78. */
  79. protected $items = [];
  80. /**
  81. * All the form data values, including non-data
  82. *
  83. * @var Data $values
  84. */
  85. protected $values;
  86. /**
  87. * The form page route
  88. *
  89. * @var string $page
  90. */
  91. protected $page;
  92. /**
  93. * Create form for the given page.
  94. *
  95. * @param PageInterface $page
  96. * @param string|int|null $name
  97. * @param array|null $form
  98. */
  99. public function __construct(PageInterface $page, $name = null, $form = null)
  100. {
  101. $this->nestedSeparator = '/';
  102. $slug = $page->slug();
  103. $header = $page->header();
  104. $this->rules = $header->rules ?? [];
  105. $this->header_data = $header->data ?? [];
  106. if ($form) {
  107. // If form is given, use it.
  108. $this->items = $form;
  109. } else {
  110. // Otherwise get all forms in the page.
  111. $forms = $page->forms();
  112. if ($name) {
  113. // If form with given name was found, use that.
  114. $this->items = $forms[$name] ?? [];
  115. } else {
  116. // Otherwise pick up the first form.
  117. $this->items = reset($forms) ?: [];
  118. $name = key($forms);
  119. }
  120. }
  121. // If we're on a modular page, find the real page.
  122. while ($page && $page->modularTwig()) {
  123. $header = $page->header();
  124. $header->never_cache_twig = true;
  125. $page = $page->parent();
  126. }
  127. $this->page = $page ? $page->route() : '/';
  128. // Add form specific rules.
  129. if (!empty($this->items['rules']) && \is_array($this->items['rules'])) {
  130. $this->rules += $this->items['rules'];
  131. }
  132. // Set form name if not set.
  133. if ($name && !\is_int($name)) {
  134. $this->items['name'] = $name;
  135. } elseif (empty($this->items['name'])) {
  136. $this->items['name'] = $slug;
  137. }
  138. // Set form id if not set.
  139. if (empty($this->items['id'])) {
  140. $this->items['id'] = Inflector::hyphenize($this->items['name']);
  141. }
  142. if (empty($this->items['nonce']['name'])) {
  143. $this->items['nonce']['name'] = 'form-nonce';
  144. }
  145. if (empty($this->items['nonce']['action'])) {
  146. $this->items['nonce']['action'] = 'form';
  147. }
  148. // Initialize form properties.
  149. $this->name = $this->items['name'];
  150. $this->setId($this->items['id']);
  151. $uniqueid = $this->items['uniqueid'] ?? null;
  152. if (null === $uniqueid && !empty($this->items['remember_state'])) {
  153. $this->set('remember_redirect', true);
  154. }
  155. $this->setUniqueId($uniqueid ?? strtolower(Utils::generateRandomString($this->items['uniqueid_len'] ?? 20)));
  156. $this->initialize();
  157. }
  158. /**
  159. * @return $this
  160. */
  161. public function initialize()
  162. {
  163. // Reset and initialize the form
  164. $this->errors = [];
  165. $this->submitted = false;
  166. $this->unsetFlash();
  167. // Remember form state.
  168. $flash = $this->getFlash();
  169. if ($flash->exists()) {
  170. $data = $flash->getData() ?? $this->header_data;
  171. } else {
  172. $data = $this->header_data;
  173. }
  174. // Remember data and files.
  175. $this->setAllData($data);
  176. $this->setAllFiles($flash);
  177. $this->values = new Data();
  178. // Fire event
  179. $grav = Grav::instance();
  180. $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
  181. return $this;
  182. }
  183. protected function setAllFiles(FormFlash $flash)
  184. {
  185. if (!$flash->exists()) {
  186. return;
  187. }
  188. /** @var Uri $url */
  189. $url = Grav::instance()['uri'];
  190. $fields = $flash->getFilesByFields(true);
  191. foreach ($fields as $field => $files) {
  192. if (strpos($field, '/') !== false) {
  193. continue;
  194. }
  195. $list = [];
  196. /**
  197. * @var string $filename
  198. * @var FormFlashFile $file
  199. */
  200. foreach ($files as $filename => $file) {
  201. $original = $fields["{$field}/original"][$filename] ?? $file;
  202. $basename = basename($filename);
  203. if ($file) {
  204. $imagePath = $original->getTmpFile();
  205. $thumbPath = $file->getTmpFile();
  206. $list[$basename] = [
  207. 'name' => $file->getClientFilename(),
  208. 'type' => $file->getClientMediaType(),
  209. 'size' => $file->getSize(),
  210. 'image_url' => $url->rootUrl() . '/' . Folder::getRelativePath($imagePath) . '?' . filemtime($imagePath),
  211. 'thumb_url' => $url->rootUrl() . '/' . Folder::getRelativePath($thumbPath) . '?' . filemtime($thumbPath),
  212. 'cropData' => $original->getMetaData()['crop'] ?? []
  213. ];
  214. }
  215. }
  216. $this->setData($field, $list);
  217. }
  218. }
  219. /**
  220. * Reset form.
  221. */
  222. public function reset(): void
  223. {
  224. $this->traitReset();
  225. // Reset and initialize the form
  226. $this->blueprint = null;
  227. $this->setAllData($this->header_data);
  228. $this->values = new Data();
  229. // Reset unique id (allow multiple form submits)
  230. $uniqueid = $this->items['uniqueid'] ?? null;
  231. $this->set('remember_redirect', null === $uniqueid && !empty($this->items['remember_state']));
  232. $this->setUniqueId($uniqueid ?? strtolower(Utils::generateRandomString($this->items['uniqueid_len'] ?? 20)));
  233. // Fire event
  234. $grav = Grav::instance();
  235. $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
  236. }
  237. public function get($name, $default = null, $separator = null)
  238. {
  239. switch (strtolower($name)) {
  240. case 'id':
  241. case 'uniqueid':
  242. case 'name':
  243. case 'noncename':
  244. case 'nonceaction':
  245. case 'action':
  246. case 'data':
  247. case 'files':
  248. case 'errors';
  249. case 'fields':
  250. case 'blueprint':
  251. case 'page':
  252. $method = 'get' . $name;
  253. return $this->{$method}();
  254. }
  255. return $this->traitGet($name, $default, $separator);
  256. }
  257. public function getAction(): string
  258. {
  259. return $this->items['action'] ?? $this->page;
  260. }
  261. /**
  262. * @param $message
  263. * @param string $type
  264. * @todo Type not used
  265. */
  266. public function setMessage($message, $type = 'error')
  267. {
  268. $this->setError($message);
  269. }
  270. public function set($name, $value, $separator = null)
  271. {
  272. switch (strtolower($name)) {
  273. case 'id':
  274. case 'uniqueid':
  275. $method = 'set' . $name;
  276. return $this->{$method}();
  277. }
  278. return $this->traitSet($name, $value, $separator);
  279. }
  280. /**
  281. * Get the nonce value for a form
  282. *
  283. * @return string
  284. */
  285. public function getNonce(): string
  286. {
  287. return Utils::getNonce($this->getNonceAction());
  288. }
  289. /**
  290. * @inheritdoc
  291. */
  292. public function getNonceName(): string
  293. {
  294. return $this->items['nonce']['name'];
  295. }
  296. /**
  297. * @inheritdoc
  298. */
  299. public function getNonceAction(): string
  300. {
  301. return $this->items['nonce']['action'];
  302. }
  303. /**
  304. * @inheritdoc
  305. */
  306. public function getValue(string $name)
  307. {
  308. return $this->values->get($name);
  309. }
  310. /**
  311. * @return Data
  312. */
  313. public function getValues(): Data
  314. {
  315. return $this->values;
  316. }
  317. /**
  318. * @inheritdoc
  319. */
  320. public function getFields(): array
  321. {
  322. return $this->getBlueprint()->fields();
  323. }
  324. /**
  325. * Return page object for the form.
  326. *
  327. * @return PageInterface
  328. */
  329. public function getPage(): PageInterface
  330. {
  331. return Grav::instance()['pages']->dispatch($this->page);
  332. }
  333. /**
  334. * @inheritdoc
  335. */
  336. public function getBlueprint(): Blueprint
  337. {
  338. if (null === $this->blueprint) {
  339. // Fix naming for fields (supports nested fields now!)
  340. if (isset($this->items['fields'])) {
  341. $this->items['fields'] = $this->processFields($this->items['fields']);
  342. }
  343. $blueprint = new Blueprint($this->name, ['form' => $this->items, 'rules' => $this->rules]);
  344. $blueprint->load()->init();
  345. $this->blueprint = $blueprint;
  346. }
  347. return $this->blueprint;
  348. }
  349. /**
  350. * Allow overriding of fields.
  351. *
  352. * @param array $fields
  353. */
  354. public function setFields(array $fields = [])
  355. {
  356. $this->items['fields'] = $fields;
  357. unset($this->items['field']);
  358. // Reset blueprint.
  359. $this->blueprint = null;
  360. // Update data to contain the new blueprints.
  361. $this->setAllData($this->data->toArray());
  362. }
  363. /**
  364. * Get value of given variable (or all values).
  365. * First look in the $data array, fallback to the $values array
  366. *
  367. * @param string $name
  368. * @param bool $fallback
  369. * @return mixed
  370. */
  371. public function value($name = null, $fallback = false)
  372. {
  373. if (!$name) {
  374. return $this->data;
  375. }
  376. if (isset($this->data[$name])) {
  377. return $this->data[$name];
  378. }
  379. if ($fallback) {
  380. return $this->values[$name];
  381. }
  382. return null;
  383. }
  384. /**
  385. * Get value of given variable (or all values).
  386. *
  387. * @param string $name
  388. * @return mixed
  389. */
  390. public function data($name = null)
  391. {
  392. return $this->value($name);
  393. }
  394. /**
  395. * Set value of given variable in the values array
  396. *
  397. * @param string $name
  398. * @param mixed $value
  399. */
  400. public function setValue($name = null, $value = '')
  401. {
  402. if (!$name) {
  403. return;
  404. }
  405. $this->values->set($name, $value);
  406. }
  407. /**
  408. * Set value of given variable in the data array
  409. *
  410. * @param string $name
  411. * @param string $value
  412. *
  413. * @return bool
  414. */
  415. public function setData($name = null, $value = '')
  416. {
  417. if (!$name) {
  418. return false;
  419. }
  420. $this->data->set($name, $value);
  421. return true;
  422. }
  423. public function setAllData($array): void
  424. {
  425. $callable = function () {
  426. return $this->getBlueprint();
  427. };
  428. $this->data = new Data($array, $callable);
  429. }
  430. /**
  431. * Handles ajax upload for files.
  432. * Stores in a flash object the temporary file and deals with potential file errors.
  433. *
  434. * @return mixed True if the action was performed.
  435. */
  436. public function uploadFiles()
  437. {
  438. $grav = Grav::instance();
  439. /** @var Uri $uri */
  440. $uri = $grav['uri'];
  441. $url = $uri->url;
  442. $post = $uri->post();
  443. $name = $post['name'] ?? null;
  444. $task = $post['task'] ?? null;
  445. /** @var Language $language */
  446. $language = $grav['language'];
  447. /** @var Config $config */
  448. $config = $grav['config'];
  449. $settings = $this->getBlueprint()->schema()->getProperty($name);
  450. $settings = (object) array_merge(
  451. ['destination' => $config->get('plugins.form.files.destination', 'self@'),
  452. 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false),
  453. 'random_name' => $config->get('plugins.form.files.random_name', false),
  454. 'accept' => $config->get('plugins.form.files.accept', ['image/*']),
  455. 'limit' => $config->get('plugins.form.files.limit', 10),
  456. 'filesize' => static::getMaxFilesize(),
  457. ],
  458. (array) $settings,
  459. ['name' => $name]
  460. );
  461. // Allow plugins to adapt settings for a given post name
  462. // Useful if schema retrieval is not an option, e.g. dynamically created forms
  463. $grav->fireEvent('onFormUploadSettings', new Event(['settings' => &$settings, 'post' => $post]));
  464. $upload = json_decode(json_encode($this->normalizeFiles($_FILES['data'], $settings->name)), true);
  465. $filename = $post['filename'] ?? $upload['file']['name'];
  466. $field = $upload['field'];
  467. // Handle errors and breaks without proceeding further
  468. if ($upload['file']['error'] !== UPLOAD_ERR_OK) {
  469. // json_response
  470. return [
  471. 'status' => 'error',
  472. 'message' => sprintf(
  473. $language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true),
  474. $filename,
  475. $this->getFileUploadError($upload['file']['error'], $language)
  476. )
  477. ];
  478. }
  479. // Handle bad filenames.
  480. if (!Utils::checkFilename($filename)) {
  481. return [
  482. 'status' => 'error',
  483. 'message' => sprintf($language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  484. $filename, 'Bad filename')
  485. ];
  486. }
  487. if (!isset($settings->destination)) {
  488. return [
  489. 'status' => 'error',
  490. 'message' => $language->translate('PLUGIN_FORM.DESTINATION_NOT_SPECIFIED', null)
  491. ];
  492. }
  493. // Remove the error object to avoid storing it
  494. unset($upload['file']['error']);
  495. // Handle Accepted file types
  496. // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
  497. $accepted = false;
  498. $errors = [];
  499. // Do not trust mimetype sent by the browser
  500. $mime = Utils::getMimeByFilename($filename);
  501. foreach ((array)$settings->accept as $type) {
  502. // Force acceptance of any file when star notation
  503. if ($type === '*') {
  504. $accepted = true;
  505. break;
  506. }
  507. $isMime = strstr($type, '/');
  508. $find = str_replace(['.', '*', '+'], ['\.', '.*', '\+'], $type);
  509. if ($isMime) {
  510. $match = preg_match('#' . $find . '$#', $mime);
  511. if (!$match) {
  512. $errors[] = sprintf($language->translate('PLUGIN_FORM.INVALID_MIME_TYPE', null, true), $mime, $filename);
  513. } else {
  514. $accepted = true;
  515. break;
  516. }
  517. } else {
  518. $match = preg_match('#' . $find . '$#', $filename);
  519. if (!$match) {
  520. $errors[] = sprintf($language->translate('PLUGIN_FORM.INVALID_FILE_EXTENSION', null, true), $filename);
  521. } else {
  522. $accepted = true;
  523. break;
  524. }
  525. }
  526. }
  527. if (!$accepted) {
  528. // json_response
  529. return [
  530. 'status' => 'error',
  531. 'message' => implode('<br/>', $errors)
  532. ];
  533. }
  534. // Handle file size limits
  535. $settings->filesize *= self::BYTES_TO_MB; // 1024 * 1024 [MB in Bytes]
  536. if ($settings->filesize > 0 && $upload['file']['size'] > $settings->filesize) {
  537. // json_response
  538. return [
  539. 'status' => 'error',
  540. 'message' => $language->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')
  541. ];
  542. }
  543. // Generate random name if required
  544. if ($settings->random_name) {
  545. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  546. $filename = Utils::generateRandomString(15) . '.' . $extension;
  547. }
  548. // Look up for destination
  549. /** @var UniformResourceLocator $locator */
  550. $locator = $grav['locator'];
  551. $destination = $settings->destination;
  552. if (!$locator->isStream($destination)) {
  553. $destination = $this->getPagePathFromToken(Folder::getRelativePath(rtrim($settings->destination, '/')));
  554. }
  555. // Handle conflicting name if needed
  556. if ($settings->avoid_overwriting) {
  557. if (file_exists($destination . '/' . $filename)) {
  558. $filename = date('YmdHis') . '-' . $filename;
  559. }
  560. }
  561. // Prepare object for later save
  562. $path = $destination . '/' . $filename;
  563. $upload['file']['name'] = $filename;
  564. $upload['file']['path'] = $path;
  565. // Special Sanitization for SVG
  566. if (method_exists('Grav\Common\Security', 'sanitizeSVG') && Utils::contains($mime, 'svg', false)) {
  567. Security::sanitizeSVG($upload['file']['tmp_name']);
  568. }
  569. // We need to store the file into flash object or it will not be available upon save later on.
  570. $flash = $this->getFlash();
  571. $flash->setUrl($url)->setUser($grav['user'] ?? null);
  572. if ($task === 'cropupload') {
  573. $crop = $post['crop'];
  574. if (\is_string($crop)) {
  575. $crop = json_decode($crop, true);
  576. }
  577. $success = $flash->cropFile($field, $filename, $upload, $crop);
  578. } else {
  579. $success = $flash->uploadFile($field, $filename, $upload);
  580. }
  581. if (!$success) {
  582. // json_response
  583. return [
  584. 'status' => 'error',
  585. 'message' => sprintf($language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $flash->getTmpDir())
  586. ];
  587. }
  588. $flash->save();
  589. // json_response
  590. $json_response = [
  591. 'status' => 'success',
  592. 'session' => \json_encode([
  593. 'sessionField' => base64_encode($url),
  594. 'path' => $path,
  595. 'field' => $settings->name,
  596. 'uniqueid' => $this->uniqueid
  597. ])
  598. ];
  599. // Return JSON
  600. header('Content-Type: application/json');
  601. echo json_encode($json_response);
  602. exit;
  603. }
  604. /**
  605. * Return an error message for a PHP file upload error code
  606. * https://www.php.net/manual/en/features.file-upload.errors.php
  607. *
  608. * @param int $error PHP file upload error code
  609. * @param Language|null $language
  610. * @return string File upload error message
  611. */
  612. public function getFileUploadError(int $error, Language $language = null): string
  613. {
  614. if (!$language) {
  615. $grav = Grav::instance();
  616. /** @var Language $language */
  617. $language = $grav['language'];
  618. }
  619. switch ($error) {
  620. case UPLOAD_ERR_OK:
  621. $item = 'FILEUPLOAD_ERR_OK';
  622. break;
  623. case UPLOAD_ERR_INI_SIZE:
  624. $item = 'FILEUPLOAD_ERR_INI_SIZE';
  625. break;
  626. case UPLOAD_ERR_FORM_SIZE:
  627. $item = 'FILEUPLOAD_ERR_FORM_SIZE';
  628. break;
  629. case UPLOAD_ERR_PARTIAL:
  630. $item = 'FILEUPLOAD_ERR_PARTIAL';
  631. break;
  632. case UPLOAD_ERR_NO_FILE:
  633. $item = 'FILEUPLOAD_ERR_NO_FILE';
  634. break;
  635. case UPLOAD_ERR_NO_TMP_DIR:
  636. $item = 'FILEUPLOAD_ERR_NO_TMP_DIR';
  637. break;
  638. case UPLOAD_ERR_CANT_WRITE:
  639. $item = 'FILEUPLOAD_ERR_CANT_WRITE';
  640. break;
  641. case UPLOAD_ERR_EXTENSION:
  642. $item = 'FILEUPLOAD_ERR_EXTENSION';
  643. break;
  644. default:
  645. $item = 'FILEUPLOAD_ERR_UNKNOWN';
  646. }
  647. return $language->translate('PLUGIN_FORM.'.$item);
  648. }
  649. /**
  650. * Removes a file from the flash object session, before it gets saved.
  651. */
  652. public function filesSessionRemove(): void
  653. {
  654. $callable = function (): array {
  655. $field = $this->values->get('name');
  656. $filename = $this->values->get('filename');
  657. if (!isset($field, $filename)) {
  658. throw new \RuntimeException('Bad Request: name and/or filename are missing', 400);
  659. }
  660. $this->removeFlashUpload($filename, $field);
  661. return ['status' => 'success'];
  662. };
  663. $this->sendJsonResponse($callable);
  664. }
  665. public function storeState(): void
  666. {
  667. $callable = function (): array {
  668. $this->updateFlashData($this->values->get('data') ?? []);
  669. return ['status' => 'success'];
  670. };
  671. $this->sendJsonResponse($callable);
  672. }
  673. public function clearState(): void
  674. {
  675. $callable = function (): array {
  676. $this->getFlash()->delete();
  677. return ['status' => 'success'];
  678. };
  679. $this->sendJsonResponse($callable);
  680. }
  681. /**
  682. * Handle form processing on POST action.
  683. */
  684. public function post()
  685. {
  686. $grav = Grav::instance();
  687. /** @var Uri $uri */
  688. $uri = $grav['uri'];
  689. // Get POST data and decode JSON fields into arrays
  690. $post = $uri->post();
  691. $post['data'] = $this->decodeData($post['data'] ?? []);
  692. if ($post) {
  693. $this->values = new Data((array)$post);
  694. $data = $this->values->get('data');
  695. // Add post data to form dataset
  696. if (!$data) {
  697. $data = $this->values->toArray();
  698. }
  699. if (!$this->values->get('form-nonce') || !Utils::verifyNonce($this->values->get('form-nonce'), 'form')) {
  700. $this->status = 'error';
  701. $event = new Event(['form' => $this,
  702. 'message' => $grav['language']->translate('PLUGIN_FORM.NONCE_NOT_VALIDATED')
  703. ]);
  704. $grav->fireEvent('onFormValidationError', $event);
  705. return;
  706. }
  707. $i = 0;
  708. foreach ($this->items['fields'] as $key => $field) {
  709. $name = $field['name'] ?? $key;
  710. if (!isset($field['name'])) {
  711. if (isset($data[$i])) { //Handle input@ false fields
  712. $data[$name] = $data[$i];
  713. unset($data[$i]);
  714. }
  715. }
  716. if ($field['type'] === 'checkbox' || $field['type'] === 'switch') {
  717. $data[$name] = isset($data[$name]) ? true : false;
  718. }
  719. $i++;
  720. }
  721. $this->data->merge($data);
  722. }
  723. // Validate and filter data
  724. try {
  725. $grav->fireEvent('onFormPrepareValidation', new Event(['form' => $this]));
  726. $this->data->validate();
  727. $this->data->filter();
  728. $grav->fireEvent('onFormValidationProcessed', new Event(['form' => $this]));
  729. } catch (ValidationException $e) {
  730. $this->status = 'error';
  731. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => $e->getMessages()]);
  732. $grav->fireEvent('onFormValidationError', $event);
  733. if ($event->isPropagationStopped()) {
  734. return;
  735. }
  736. } catch (\RuntimeException $e) {
  737. $this->status = 'error';
  738. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => []]);
  739. $grav->fireEvent('onFormValidationError', $event);
  740. if ($event->isPropagationStopped()) {
  741. return;
  742. }
  743. }
  744. $redirect = $redirect_code = null;
  745. $process = $this->items['process'] ?? [];
  746. $legacyUploads = !isset($process['upload']) || $process['upload'] !== false;
  747. if ($legacyUploads) {
  748. $this->legacyUploads();
  749. }
  750. if (\is_array($process)) {
  751. foreach ($process as $action => $data) {
  752. if (is_numeric($action)) {
  753. $action = \key($data);
  754. $data = $data[$action];
  755. }
  756. $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
  757. $grav->fireEvent('onFormProcessed', $event);
  758. if ($event['redirect']) {
  759. $redirect = $event['redirect'];
  760. $redirect_code = $event['redirect_code'];
  761. }
  762. if ($event->isPropagationStopped()) {
  763. break;
  764. }
  765. }
  766. }
  767. if ($legacyUploads) {
  768. $this->copyFiles();
  769. }
  770. $this->getFlash()->delete();
  771. if ($redirect) {
  772. $grav->redirect($redirect, $redirect_code);
  773. }
  774. }
  775. /**
  776. * @return string
  777. * @deprecated 3.0 Use $form->getName() instead
  778. */
  779. public function name(): string
  780. {
  781. return $this->getName();
  782. }
  783. /**
  784. * @return array
  785. * @deprecated 3.0 Use $form->getFields() instead
  786. */
  787. public function fields(): array
  788. {
  789. return $this->getFields();
  790. }
  791. /**
  792. * @return PageInterface
  793. * @deprecated 3.0 Use $form->getPage() instead
  794. */
  795. public function page(): PageInterface
  796. {
  797. return $this->getPage();
  798. }
  799. /**
  800. * Backwards compatibility
  801. *
  802. * @deprecated 3.0 Calling $form->filter() is not needed anymore (does nothing)
  803. */
  804. public function filter(): void
  805. {
  806. }
  807. /**
  808. * Store form uploads to the final location.
  809. */
  810. public function copyFiles()
  811. {
  812. // Get flash object in order to save the files.
  813. $flash = $this->getFlash();
  814. $fields = $flash->getFilesByFields();
  815. foreach ($fields as $key => $uploads) {
  816. /** @var FormFlashFile $upload */
  817. foreach ($uploads as $upload) {
  818. if (null === $upload || $upload->isMoved()) {
  819. continue;
  820. }
  821. $destination = $upload->getDestination();
  822. $filesystem = Filesystem::getInstance();
  823. $folder = $filesystem->dirname($destination);
  824. if (!is_dir($folder) && !@mkdir($folder, 0777, true) && !is_dir($folder)) {
  825. $grav = Grav::instance();
  826. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $upload->getClientFilename() . '"', $destination));
  827. }
  828. try {
  829. $upload->moveTo($destination);
  830. } catch (\RuntimeException $e) {
  831. $grav = Grav::instance();
  832. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $upload->getClientFilename() . '"', $destination));
  833. }
  834. }
  835. }
  836. $flash->clearFiles();
  837. }
  838. public function legacyUploads()
  839. {
  840. // Get flash object in order to save the files.
  841. $flash = $this->getFlash();
  842. $queue = $verify = $flash->getLegacyFiles();
  843. if (!$queue) {
  844. return;
  845. }
  846. $grav = Grav::instance();
  847. /** @var Uri $uri */
  848. $uri = $grav['uri'];
  849. // Get POST data and decode JSON fields into arrays
  850. $post = $uri->post();
  851. $post['data'] = $this->decodeData($post['data'] ?? []);
  852. // Allow plugins to implement additional / alternative logic
  853. $grav->fireEvent('onFormStoreUploads', new Event(['form' => $this, 'queue' => &$queue, 'post' => $post]));
  854. $modified = $queue !== $verify;
  855. if (!$modified) {
  856. // Fill file fields just like before.
  857. foreach ($queue as $key => $files) {
  858. foreach ($files as $destination => $file) {
  859. unset($files[$destination]['tmp_name']);
  860. }
  861. $this->setImageField($key, $files);
  862. }
  863. } else {
  864. user_error('Event onFormStoreUploads is deprecated.', E_USER_DEPRECATED);
  865. if (\is_array($queue)) {
  866. foreach ($queue as $key => $files) {
  867. foreach ($files as $destination => $file) {
  868. $filesystem = Filesystem::getInstance();
  869. $folder = $filesystem->dirname($destination);
  870. if (!is_dir($folder) && !@mkdir($folder, 0777, true) && !is_dir($folder)) {
  871. $grav = Grav::instance();
  872. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
  873. }
  874. if (!rename($file['tmp_name'], $destination)) {
  875. $grav = Grav::instance();
  876. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
  877. }
  878. if (file_exists($file['tmp_name'] . '.yaml')) {
  879. unlink($file['tmp_name'] . '.yaml');
  880. }
  881. unset($files[$destination]['tmp_name']);
  882. }
  883. $this->setImageField($key, $files);
  884. }
  885. }
  886. $flash->clearFiles();
  887. }
  888. }
  889. public function getPagePathFromToken($path)
  890. {
  891. return Utils::getPagePathFromToken($path, $this->getPage());
  892. }
  893. /**
  894. * @return Route|null
  895. */
  896. public function getFileUploadAjaxRoute(): ?Route
  897. {
  898. $route = Uri::getCurrentRoute()->withExtension('json')->withGravParam('task', 'file-upload');
  899. return $route;
  900. }
  901. /**
  902. * @param $field
  903. * @param $filename
  904. * @return Route|null
  905. */
  906. public function getFileDeleteAjaxRoute($field, $filename): ?Route
  907. {
  908. $route = Uri::getCurrentRoute()->withExtension('json')->withGravParam('task', 'file-remove');
  909. return $route;
  910. }
  911. public function responseCode($code = null)
  912. {
  913. if ($code) {
  914. $this->response_code = $code;
  915. }
  916. return $this->response_code;
  917. }
  918. public function doSerialize()
  919. {
  920. return $this->doTraitSerialize() + [
  921. 'items' => $this->items,
  922. 'message' => $this->message,
  923. 'status' => $this->status,
  924. 'header_data' => $this->header_data,
  925. 'rules' => $this->rules,
  926. 'values' => $this->values->toArray(),
  927. 'page' => $this->page
  928. ];
  929. }
  930. public function doUnserialize(array $data)
  931. {
  932. $this->items = $data['items'];
  933. $this->message = $data['message'];
  934. $this->status = $data['status'];
  935. $this->header_data = $data['header_data'];
  936. $this->rules = $data['rules'];
  937. $this->values = new Data($data['values']);
  938. $this->page = $data['page'];
  939. // Backwards compatibility.
  940. $defaults = [
  941. 'name' => $this->items['name'],
  942. 'id' => $this->items['id'],
  943. 'uniqueid' => $this->items['uniqueid'] ?? null,
  944. 'data' => []
  945. ];
  946. $this->doTraitUnserialize($data + $defaults);
  947. }
  948. /**
  949. * Get the configured max file size in bytes
  950. *
  951. * @param bool $mbytes return size in MB
  952. * @return int
  953. */
  954. public static function getMaxFilesize($mbytes = false)
  955. {
  956. $config = Grav::instance()['config'];
  957. $system_filesize = 0;
  958. $form_filesize = $config->get('plugins.form.files.filesize', 0);
  959. $upload_limit = (int) Utils::getUploadLimit();
  960. if ($upload_limit > 0) {
  961. $system_filesize = intval($upload_limit / static::BYTES_TO_MB);
  962. }
  963. if ($form_filesize > $system_filesize || $form_filesize == 0) {
  964. $form_filesize = $system_filesize;
  965. }
  966. if ($mbytes) {
  967. return $form_filesize * static::BYTES_TO_MB;
  968. }
  969. return $form_filesize;
  970. }
  971. protected function sendJsonResponse(callable $callable)
  972. {
  973. $grav = Grav::instance();
  974. /** @var Uri $uri */
  975. $uri = $grav['uri'];
  976. // Get POST data and decode JSON fields into arrays
  977. $post = $uri->post();
  978. $post['data'] = $this->decodeData($post['data'] ?? []);
  979. if (empty($post['form-nonce']) || !Utils::verifyNonce($post['form-nonce'], 'form')) {
  980. throw new \RuntimeException('Bad Request: Nonce is missing or invalid', 400);
  981. }
  982. $this->values = new Data($post);
  983. $json_response = $callable($post);
  984. // Return JSON
  985. header('Content-Type: application/json');
  986. echo json_encode($json_response);
  987. exit;
  988. }
  989. /**
  990. * Remove uploaded file from flash object.
  991. *
  992. * @param string $filename
  993. * @param string|null $field
  994. */
  995. protected function removeFlashUpload(string $filename, string $field = null)
  996. {
  997. $flash = $this->getFlash();
  998. $flash->removeFile($filename, $field);
  999. $flash->save();
  1000. }
  1001. /**
  1002. * Store updated data into flash object.
  1003. *
  1004. * @param array $data
  1005. */
  1006. protected function updateFlashData(array $data)
  1007. {
  1008. // Store updated data into flash.
  1009. $flash = $this->getFlash();
  1010. // Check special case where there are no changes made to the form.
  1011. if (!$flash->exists() && $data === $this->header_data) {
  1012. return;
  1013. }
  1014. $this->setAllData($flash->getData() ?? []);
  1015. $this->data->merge($data);
  1016. $flash->setData($this->data->toArray());
  1017. $flash->save();
  1018. }
  1019. protected function doSubmit(array $data, array $files)
  1020. {
  1021. return;
  1022. }
  1023. protected function processFields($fields)
  1024. {
  1025. $types = Grav::instance()['plugins']->formFieldTypes;
  1026. $return = [];
  1027. foreach ($fields as $key => $value) {
  1028. // Default to text if not set
  1029. if (!isset($value['type'])) {
  1030. $value['type'] = 'text';
  1031. }
  1032. // Manually merging the field types
  1033. if ($types !== null && array_key_exists($value['type'], $types)) {
  1034. $value += $types[$value['type']];
  1035. }
  1036. // Fix numeric indexes
  1037. if (is_numeric($key) && isset($value['name'])) {
  1038. $key = $value['name'];
  1039. }
  1040. // Recursively process children
  1041. if (isset($value['fields']) && \is_array($value['fields'])) {
  1042. $value['fields'] = $this->processFields($value['fields']);
  1043. }
  1044. $return[$key] = $value;
  1045. }
  1046. return $return;
  1047. }
  1048. protected function setImageField($key, $files)
  1049. {
  1050. $field = $this->data->blueprints()->schema()->get($key);
  1051. if (isset($field['type']) && !empty($field['array'])) {
  1052. $this->data->set($key, $files);
  1053. }
  1054. }
  1055. /**
  1056. * Decode data
  1057. *
  1058. * @param array $data
  1059. * @return array
  1060. */
  1061. protected function decodeData($data)
  1062. {
  1063. if (!\is_array($data)) {
  1064. return [];
  1065. }
  1066. // Decode JSON encoded fields and merge them to data.
  1067. if (isset($data['_json'])) {
  1068. $data = array_replace_recursive($data, $this->jsonDecode($data['_json']));
  1069. unset($data['_json']);
  1070. }
  1071. $data = $this->cleanDataKeys($data);
  1072. return $data;
  1073. }
  1074. /**
  1075. * Decode [] in the data keys
  1076. *
  1077. * @param array $source
  1078. * @return array
  1079. */
  1080. protected function cleanDataKeys($source = [])
  1081. {
  1082. $out = [];
  1083. if (\is_array($source)) {
  1084. foreach ($source as $key => $value) {
  1085. $key = str_replace(['%5B', '%5D'], ['[', ']'], $key);
  1086. if (\is_array($value)) {
  1087. $out[$key] = $this->cleanDataKeys($value);
  1088. } else {
  1089. $out[$key] = $value;
  1090. }
  1091. }
  1092. }
  1093. return $out;
  1094. }
  1095. /**
  1096. * Internal method to normalize the $_FILES array
  1097. *
  1098. * @param array $data $_FILES starting point data
  1099. * @param string $key
  1100. * @return object a new Object with a normalized list of files
  1101. */
  1102. protected function normalizeFiles($data, $key = '')
  1103. {
  1104. $files = new \stdClass();
  1105. $files->field = $key;
  1106. $files->file = new \stdClass();
  1107. foreach ($data as $fieldName => $fieldValue) {
  1108. // Since Files Upload are always happening via Ajax
  1109. // we are not interested in handling `multiple="true"`
  1110. // because they are always handled one at a time.
  1111. // For this reason we normalize the value to string,
  1112. // in case it is arriving as an array.
  1113. $value = (array) Utils::getDotNotation($fieldValue, $key);
  1114. $files->file->{$fieldName} = array_shift($value);
  1115. }
  1116. return $files;
  1117. }
  1118. }