form.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. <?php
  2. namespace Grav\Plugin;
  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. $this->items = $form;
  76. } else {
  77. if (isset($header->form)) {
  78. $this->items = $header->form; // for backwards compatibility
  79. }
  80. }
  81. // Add form specific rules.
  82. if (!empty($this->items['rules']) && is_array($this->items['rules'])) {
  83. $this->rules += $this->items['rules'];
  84. }
  85. // Set form name if not set.
  86. if ($name && !is_int($name)) {
  87. $this->items['name'] = $name;
  88. } elseif (empty($this->items['name'])) {
  89. $this->items['name'] = $page->slug();
  90. }
  91. // Set form id if not set.
  92. if (empty($this->items['id'])) {
  93. $inflector = new Inflector();
  94. $this->items['id'] = $inflector->hyphenize($this->items['name']);
  95. }
  96. // Reset and initialize the form
  97. $this->reset();
  98. }
  99. /**
  100. * Custom serializer for this complex object
  101. *
  102. * @return string
  103. */
  104. public function serialize()
  105. {
  106. $data = [
  107. 'items' => $this->items,
  108. 'message' => $this->message,
  109. 'status' => $this->status,
  110. 'header_data' => $this->header_data,
  111. 'rules' => $this->rules,
  112. 'data' => $this->data->toArray(),
  113. 'values' => $this->values->toArray(),
  114. 'page' => $this->page
  115. ];
  116. return serialize($data);
  117. }
  118. /**
  119. * Custom unserializer for this complex object
  120. *
  121. * @param string $data
  122. */
  123. public function unserialize($data)
  124. {
  125. $data = unserialize($data);
  126. $this->items = $data['items'];
  127. $this->message = $data['message'];
  128. $this->status = $data['status'];
  129. $this->header_data = $data['header_data'];
  130. $this->rules = $data['rules'];
  131. $name = $this->items['name'];
  132. $items = $this->items;
  133. $rules = $this->rules;
  134. $blueprint = function () use ($name, $items, $rules) {
  135. $blueprint = new Blueprint($name, ['form' => $items, 'rules' => $rules]);
  136. return $blueprint->load()->init();
  137. };
  138. $this->data = new Data($data['data'], $blueprint);
  139. $this->values = new Data($data['values']);
  140. $this->page = $data['page'];
  141. }
  142. /**
  143. * Allow overriding of fields
  144. *
  145. * @param $fields
  146. */
  147. public function setFields($fields)
  148. {
  149. $this->fields = $fields;
  150. }
  151. /**
  152. * Get the name of this form
  153. *
  154. * @return String
  155. */
  156. public function name()
  157. {
  158. return $this->items['name'];
  159. }
  160. /**
  161. * Reset data.
  162. */
  163. public function reset()
  164. {
  165. $name = $this->items['name'];
  166. $grav = Grav::instance();
  167. // Fix naming for fields (supports nested fields now!)
  168. if (isset($this->items['fields'])) {
  169. $this->items['fields'] = $this->processFields($this->items['fields']);
  170. }
  171. $items = $this->items;
  172. $rules = $this->rules;
  173. $blueprint = function() use ($name, $items, $rules) {
  174. $blueprint = new Blueprint($name, ['form' => $items, 'rules' => $rules]);
  175. return $blueprint->load()->init();
  176. };
  177. $this->data = new Data($this->header_data, $blueprint);
  178. $this->values = new Data();
  179. // Reset fields to null before calling fields() -- Do not remove:
  180. $this->fields = null;
  181. $this->fields = $this->fields();
  182. // Fire event
  183. $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
  184. }
  185. protected function processFields($fields)
  186. {
  187. $types = Grav::instance()['plugins']->formFieldTypes;
  188. $return = array();
  189. foreach ($fields as $key => $value) {
  190. // default to text if not set
  191. if (!isset($value['type'])) {
  192. $value['type'] = 'text';
  193. }
  194. // manually merging the field types
  195. if ($types !== null && array_key_exists($value['type'], $types)) {
  196. $value += $types[$value['type']];
  197. }
  198. // Fix numeric indexes
  199. if (is_numeric($key) && isset($value['name'])) {
  200. $key = $value['name'];
  201. }
  202. if (isset($value['fields']) && is_array($value['fields'])) {
  203. $value['fields'] = $this->processFields($value['fields']);
  204. }
  205. $return[$key] = $value;
  206. }
  207. return $return;
  208. }
  209. public function fields()
  210. {
  211. if (null === $this->fields) {
  212. $blueprint = $this->data->blueprints();
  213. if (method_exists($blueprint, 'load')) {
  214. // init the form to process directives
  215. $blueprint->load()->init();
  216. // fields set to processed blueprint fields
  217. $this->fields = $blueprint->fields();
  218. }
  219. }
  220. return $this->fields;
  221. }
  222. /**
  223. * Return page object for the form.
  224. *
  225. * @return Page
  226. */
  227. public function page()
  228. {
  229. return Grav::instance()['pages']->dispatch($this->page);
  230. }
  231. /**
  232. * Get value of given variable (or all values).
  233. * First look in the $data array, fallback to the $values array
  234. *
  235. * @param string $name
  236. *
  237. * @return mixed
  238. */
  239. public function value($name = null, $fallback = false)
  240. {
  241. if (!$name) {
  242. return $this->data;
  243. }
  244. if ($this->data->get($name)) {
  245. return $this->data->get($name);
  246. }
  247. if ($fallback) {
  248. return $this->values->get($name);
  249. }
  250. return null;
  251. }
  252. /**
  253. * Set value of given variable in the values array
  254. *
  255. * @param string $name
  256. */
  257. public function setValue($name = null, $value = '')
  258. {
  259. if (!$name) {
  260. return;
  261. }
  262. $this->values->set($name, $value);
  263. }
  264. /**
  265. * Get a value from the form
  266. *
  267. * @param $name
  268. * @return mixed
  269. */
  270. public function getValue($name)
  271. {
  272. return $this->values->get($name);
  273. }
  274. /**
  275. * Get all data
  276. *
  277. * @return Data
  278. */
  279. public function getData()
  280. {
  281. return $this->data;
  282. }
  283. /**
  284. * Set value of given variable in the data array
  285. *
  286. * @param string $name
  287. * @param string $value
  288. *
  289. * @return bool
  290. */
  291. public function setData($name = null, $value = '')
  292. {
  293. if (!$name) {
  294. return false;
  295. }
  296. $this->data->set($name, $value);
  297. return true;
  298. }
  299. public function setAllData($array)
  300. {
  301. $this->data = new Data($array);
  302. }
  303. /**
  304. * Handles ajax upload for files.
  305. * Stores in a flash object the temporary file and deals with potential file errors.
  306. *
  307. * @return mixed True if the action was performed.
  308. */
  309. public function uploadFiles()
  310. {
  311. $post = $_POST;
  312. $grav = Grav::instance();
  313. $uri = $grav['uri']->url;
  314. $config = $grav['config'];
  315. $session = $grav['session'];
  316. $settings = $this->data->blueprints()->schema()->getProperty($post['name']);
  317. $settings = (object) array_merge(
  318. ['destination' => $config->get('plugins.form.files.destination', 'self@'),
  319. 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false),
  320. 'random_name' => $config->get('plugins.form.files.random_name', false),
  321. 'accept' => $config->get('plugins.form.files.accept', ['image/*']),
  322. 'limit' => $config->get('plugins.form.files.limit', 10),
  323. 'filesize' => $this->getMaxFilesize(),
  324. ],
  325. (array) $settings,
  326. ['name' => $post['name']]
  327. );
  328. $upload = $this->normalizeFiles($_FILES['data'], $settings->name);
  329. // Handle errors and breaks without proceeding further
  330. if ($upload->file->error != UPLOAD_ERR_OK) {
  331. // json_response
  332. return [
  333. 'status' => 'error',
  334. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $upload->file->name, $this->upload_errors[$upload->file->error])
  335. ];
  336. }
  337. // Handle bad filenames.
  338. $filename = $upload->file->name;
  339. if (strtr($filename, "\t\n\r\0\x0b", '_____') !== $filename || rtrim($filename, ". ") !== $filename || preg_match('|\.php|', $filename)) {
  340. $this->admin->json_response = [
  341. 'status' => 'error',
  342. 'message' => sprintf($this->admin->translate('PLUGIN_ADMIN.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
  343. $filename, 'Bad filename')
  344. ];
  345. return false;
  346. }
  347. // Remove the error object to avoid storing it
  348. unset($upload->file->error);
  349. // Handle Accepted file types
  350. // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
  351. $accepted = false;
  352. $errors = [];
  353. foreach ((array) $settings->accept as $type) {
  354. // Force acceptance of any file when star notation
  355. if ($type === '*') {
  356. $accepted = true;
  357. break;
  358. }
  359. $isMime = strstr($type, '/');
  360. $find = str_replace('*', '.*', $type);
  361. $match = preg_match('#'. $find .'$#', $isMime ? $upload->file->type : $upload->file->name);
  362. if (!$match) {
  363. $message = $isMime ? 'The MIME type "' . $upload->file->type . '"' : 'The File Extension';
  364. $errors[] = $message . ' for the file "' . $upload->file->name . '" is not an accepted.';
  365. $accepted |= false;
  366. } else {
  367. $accepted |= true;
  368. }
  369. }
  370. if (!$accepted) {
  371. // json_response
  372. return [
  373. 'status' => 'error',
  374. 'message' => implode('<br/>', $errors)
  375. ];
  376. }
  377. // Handle file size limits
  378. $settings->filesize *= self::BYTES_TO_MB; // 1024 * 1024 [MB in Bytes]
  379. if ($settings->filesize > 0 && $upload->file->size > $settings->filesize) {
  380. // json_response
  381. return [
  382. 'status' => 'error',
  383. 'message' => $grav['language']->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')
  384. ];
  385. }
  386. // we need to move the file at this stage or else
  387. // it won't be available upon save later on
  388. // since php removes it from the upload location
  389. $tmp_dir = $grav['locator']->findResource('tmp://', true, true);
  390. $tmp_file = $upload->file->tmp_name;
  391. $tmp = $tmp_dir . '/uploaded-files/' . basename($tmp_file);
  392. Folder::create(dirname($tmp));
  393. if (!move_uploaded_file($tmp_file, $tmp)) {
  394. // json_response
  395. return [
  396. 'status' => 'error',
  397. 'message' => sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $tmp)
  398. ];
  399. }
  400. $upload->file->tmp_name = $tmp;
  401. // Retrieve the current session of the uploaded files for the field
  402. // and initialize it if it doesn't exist
  403. $sessionField = base64_encode($uri);
  404. $flash = $session->getFlashObject('files-upload');
  405. if (!$flash) {
  406. $flash = [];
  407. }
  408. if (!isset($flash[$sessionField])) {
  409. $flash[$sessionField] = [];
  410. }
  411. if (!isset($flash[$sessionField][$upload->field])) {
  412. $flash[$sessionField][$upload->field] = [];
  413. }
  414. // Set destination
  415. $destination = Folder::getRelativePath(rtrim($settings->destination, '/'));
  416. $destination = $this->getPagePathFromToken($destination);
  417. // Create destination if needed
  418. if (!is_dir($destination)) {
  419. Folder::mkdir($destination);
  420. }
  421. // Generate random name if required
  422. if ($settings->random_name) {
  423. $extension = pathinfo($upload->file->name)['extension'];
  424. $upload->file->name = Utils::generateRandomString(15) . '.' . $extension;
  425. }
  426. // Handle conflicting name if needed
  427. if ($settings->avoid_overwriting) {
  428. if (file_exists($destination . '/' . $upload->file->name)) {
  429. $upload->file->name = date('YmdHis') . '-' . $upload->file->name;
  430. }
  431. }
  432. // Prepare object for later save
  433. $path = $destination . '/' . $upload->file->name;
  434. $upload->file->path = $path;
  435. // $upload->file->route = $page ? $path : null;
  436. // Prepare data to be saved later
  437. $flash[$sessionField][$upload->field][$path] = (array) $upload->file;
  438. // Finally store the new uploaded file in the field session
  439. $session->setFlashObject('files-upload', $flash);
  440. // json_response
  441. return [
  442. 'status' => 'success',
  443. 'session' => \json_encode([
  444. 'sessionField' => base64_encode($uri),
  445. 'path' => $upload->file->path,
  446. 'field' => $settings->name
  447. ])
  448. ];
  449. }
  450. /**
  451. * Handle form processing on POST action.
  452. */
  453. public function post()
  454. {
  455. $grav = Grav::instance();
  456. $uri = $grav['uri']->url;
  457. $session = $grav['session'];
  458. if (isset($_POST)) {
  459. $this->values = new Data(isset($_POST) ? (array)$_POST : []);
  460. $data = $this->values->get('data');
  461. // Add post data to form dataset
  462. if (!$data) {
  463. $data = $this->values->toArray();
  464. }
  465. if (!$this->values->get('form-nonce') || !Utils::verifyNonce($this->values->get('form-nonce'), 'form')) {
  466. $this->status = 'error';
  467. $event = new Event(['form' => $this,
  468. 'message' => $grav['language']->translate('PLUGIN_FORM.NONCE_NOT_VALIDATED')
  469. ]);
  470. $grav->fireEvent('onFormValidationError', $event);
  471. return;
  472. }
  473. $i = 0;
  474. foreach ($this->items['fields'] as $key => $field) {
  475. $name = isset($field['name']) ? $field['name'] : $key;
  476. if (!isset($field['name'])) {
  477. if (isset($data[$i])) { //Handle input@ false fields
  478. $data[$name] = $data[$i];
  479. unset($data[$i]);
  480. }
  481. }
  482. if ($field['type'] === 'checkbox') {
  483. $data[$name] = isset($data[$name]) ? true : false;
  484. }
  485. $i++;
  486. }
  487. $this->data->merge($data);
  488. }
  489. // Validate and filter data
  490. try {
  491. $this->data->validate();
  492. $this->data->filter();
  493. $grav->fireEvent('onFormValidationProcessed', new Event(['form' => $this]));
  494. } catch (ValidationException $e) {
  495. $this->status = 'error';
  496. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => $e->getMessages()]);
  497. $grav->fireEvent('onFormValidationError', $event);
  498. if ($event->isPropagationStopped()) {
  499. return;
  500. }
  501. } catch (\RuntimeException $e) {
  502. $this->status = 'error';
  503. $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => []]);
  504. $grav->fireEvent('onFormValidationError', $event);
  505. if ($event->isPropagationStopped()) {
  506. return;
  507. }
  508. }
  509. // Process previously uploaded files for the current URI
  510. // and finally store them. Everything else will get discarded
  511. $queue = $session->getFlashObject('files-upload');
  512. $queue = $queue[base64_encode($uri)];
  513. if (is_array($queue)) {
  514. foreach ($queue as $key => $files) {
  515. foreach ($files as $destination => $file) {
  516. if (!rename($file['tmp_name'], $destination)) {
  517. throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
  518. }
  519. unset($files[$destination]['tmp_name']);
  520. }
  521. $this->data->merge([$key => $files]);
  522. }
  523. }
  524. $process = isset($this->items['process']) ? $this->items['process'] : [];
  525. if (is_array($process)) {
  526. $event = null;
  527. foreach ($process as $action => $data) {
  528. if (is_numeric($action)) {
  529. $action = \key($data);
  530. $data = $data[$action];
  531. }
  532. $previousEvent = $event;
  533. $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
  534. if ($previousEvent) {
  535. if (!$previousEvent->isPropagationStopped()) {
  536. $grav->fireEvent('onFormProcessed', $event);
  537. } else {
  538. break;
  539. }
  540. } else {
  541. $grav->fireEvent('onFormProcessed', $event);
  542. }
  543. }
  544. }
  545. }
  546. public function getPagePathFromToken($path)
  547. {
  548. return Utils::getPagePathFromToken($path, $this->page());
  549. }
  550. /**
  551. * Internal method to normalize the $_FILES array
  552. *
  553. * @param array $data $_FILES starting point data
  554. * @param string $key
  555. * @return object a new Object with a normalized list of files
  556. */
  557. protected function normalizeFiles($data, $key = '')
  558. {
  559. $files = new \stdClass();
  560. $files->field = $key;
  561. $files->file = new \stdClass();
  562. foreach ($data as $fieldName => $fieldValue) {
  563. // Since Files Upload are always happening via Ajax
  564. // we are not interested in handling `multiple="true"`
  565. // because they are always handled one at a time.
  566. // For this reason we normalize the value to string,
  567. // in case it is arriving as an array.
  568. $value = (array) Utils::getDotNotation($fieldValue, $key);
  569. $files->file->{$fieldName} = array_shift($value);
  570. }
  571. return $files;
  572. }
  573. /**
  574. * Get the nonce for a form
  575. *
  576. * @return string
  577. */
  578. public static function getNonce()
  579. {
  580. $action = 'form-plugin';
  581. return Utils::getNonce($action);
  582. }
  583. /**
  584. * Get the configured max file size in bytes
  585. *
  586. * @param bool $mbytes return size in MB
  587. * @return int
  588. */
  589. public static function getMaxFilesize($mbytes = false)
  590. {
  591. $config = Grav::instance()['config'];
  592. $filesize_mb = (float)$config->get('plugins.form.files.filesize', 0) * static::BYTES_TO_MB;
  593. $system_filesize = $config->get('system.media.upload_limit', 0);
  594. if ($filesize_mb > $system_filesize || $filesize_mb === 0) {
  595. $filesize_mb = $system_filesize;
  596. }
  597. if ($mbytes) {
  598. return $filesize_mb;
  599. }
  600. return $filesize_mb / static::BYTES_TO_MB;
  601. }
  602. public function responseCode($code = null)
  603. {
  604. if ($code) {
  605. $this->response_code = $code;
  606. }
  607. return $this->response_code;
  608. }
  609. }