form.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. <?php
  2. namespace Grav\Plugin;
  3. use Composer\Autoload\ClassLoader;
  4. use Grav\Common\Data\ValidationException;
  5. use Grav\Common\Debugger;
  6. use Grav\Common\Filesystem\Folder;
  7. use Grav\Common\Grav;
  8. use Grav\Common\Page\Interfaces\PageInterface;
  9. use Grav\Common\Page\Pages;
  10. use Grav\Common\Page\Types;
  11. use Grav\Common\Plugin;
  12. use Grav\Common\Twig\Twig;
  13. use Grav\Common\Utils;
  14. use Grav\Common\Uri;
  15. use Grav\Common\Yaml;
  16. use Grav\Framework\Form\Interfaces\FormInterface;
  17. use Grav\Framework\Route\Route;
  18. use Grav\Plugin\Form\Form;
  19. use Grav\Plugin\Form\Forms;
  20. use ReCaptcha\ReCaptcha;
  21. use ReCaptcha\RequestMethod\CurlPost;
  22. use RocketTheme\Toolbox\File\JsonFile;
  23. use RocketTheme\Toolbox\File\YamlFile;
  24. use RocketTheme\Toolbox\File\File;
  25. use RocketTheme\Toolbox\Event\Event;
  26. /**
  27. * Class FormPlugin
  28. * @package Grav\Plugin
  29. */
  30. class FormPlugin extends Plugin
  31. {
  32. /** @var array */
  33. public $features = [
  34. 'blueprints' => 1000
  35. ];
  36. /** @var Form */
  37. protected $form;
  38. /** @var array */
  39. protected $forms = [];
  40. /** @var array */
  41. protected $flat_forms = [];
  42. /** @var array */
  43. protected $active_forms = [];
  44. /** @var array */
  45. protected $json_response = [];
  46. /** @var bool */
  47. protected $recache_forms = false;
  48. /**
  49. * @return bool
  50. */
  51. public static function checkRequirements(): bool
  52. {
  53. return version_compare(GRAV_VERSION, '1.6', '>');
  54. }
  55. /**
  56. * @return array
  57. */
  58. public static function getSubscribedEvents()
  59. {
  60. if (!static::checkRequirements()) {
  61. return [];
  62. }
  63. return [
  64. 'onPluginsInitialized' => [
  65. ['autoload', 100000],
  66. ['onPluginsInitialized', 0]
  67. ],
  68. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0]
  69. ];
  70. }
  71. /**
  72. * [onPluginsInitialized:100000] Composer autoload.
  73. *
  74. * @return ClassLoader
  75. */
  76. public function autoload()
  77. {
  78. return require __DIR__ . '/vendor/autoload.php';
  79. }
  80. /**
  81. * Initialize forms from cache if possible
  82. */
  83. public function onPluginsInitialized()
  84. {
  85. // Backwards compatibility for plugins that use forms.
  86. class_alias(Form::class, 'Grav\Plugin\Form');
  87. $this->grav['forms'] = function () {
  88. $forms = new Forms();
  89. $grav = Grav::instance();
  90. $event = new Event(['forms' => $forms]);
  91. $grav->fireEvent('onFormRegisterTypes', $event);
  92. return $forms;
  93. };
  94. if ($this->isAdmin()) {
  95. $this->enable([
  96. 'onPageInitialized' => ['onPageInitialized', 0],
  97. 'onGetPageTemplates' => ['onGetPageTemplates', 0],
  98. ]);
  99. return;
  100. }
  101. // Mini Keep-Alive Logic
  102. $task = $this->grav['uri']->param('task');
  103. if ($task && $task === 'keep-alive') {
  104. exit;
  105. }
  106. $this->enable([
  107. 'onPageProcessed' => ['onPageProcessed', 0],
  108. 'onPagesInitialized' => ['onPagesInitialized', 0],
  109. 'onPageInitialized' => ['onPageInitialized', 0],
  110. 'onTwigInitialized' => ['onTwigInitialized', 0],
  111. 'onTwigPageVariables' => ['onTwigVariables', 0],
  112. 'onTwigSiteVariables' => ['onTwigVariables', 0],
  113. 'onFormValidationProcessed' => ['onFormValidationProcessed', 0],
  114. ]);
  115. }
  116. public function onGetPageTemplates(Event $event)
  117. {
  118. /** @var Types $types */
  119. $types = $event->types;
  120. $types->register('form');
  121. }
  122. /**
  123. * Process forms after page header processing, but before caching
  124. *
  125. * @param Event $e
  126. */
  127. public function onPageProcessed(Event $e)
  128. {
  129. /** @var PageInterface $page */
  130. $page = $e['page'];
  131. $pageForms = $page->forms();
  132. if (!$pageForms) {
  133. return;
  134. }
  135. // Force never_cache_twig if modular form (recursively up)
  136. $current = $page;
  137. while ($current && $current->modularTwig()) {
  138. $header = $current->header();
  139. $header->never_cache_twig = true;
  140. $current = $current->parent();
  141. }
  142. $parent = $current && $current !== $page ? $current : null;
  143. $page_route = $page->home() ? '/' : $page->route();
  144. // If the form was in the modular page, we need to add the form into the parent page as well.
  145. if ($parent) {
  146. $parent->addForms($pageForms);
  147. $parent_route = $parent->home() ? '/' : $parent->route();
  148. }
  149. /** @var Forms $forms */
  150. $forms = $this->grav['forms'];
  151. // Store the page forms in the forms instance
  152. foreach ($pageForms as $name => $form) {
  153. if (isset($parent, $parent_route)) {
  154. $this->addForm($parent_route, $forms->createPageForm($parent, $name, $form));
  155. }
  156. $this->addForm($page_route, $forms->createPageForm($page, $name, $form));
  157. }
  158. }
  159. /**
  160. * Initialize all the forms
  161. */
  162. public function onPagesInitialized()
  163. {
  164. $this->loadCachedForms();
  165. }
  166. /**
  167. * Catches form processing if user posts the form.
  168. */
  169. public function onPageInitialized()
  170. {
  171. $submitted = false;
  172. $this->json_response = [];
  173. // Save cached forms.
  174. if ($this->recache_forms) {
  175. $this->saveCachedForms();
  176. }
  177. /** @var PageInterface $page */
  178. $page = $this->grav['page'];
  179. // Force rebuild form when form has not been built and form cache expired.
  180. // This happens when form cache expires before the page cache
  181. // and then does not trigger 'onPageProcessed' event.
  182. if (!$this->forms) {
  183. $this->onPageProcessed(new Event(['page' => $page]));
  184. }
  185. // Enable form events if there's a POST
  186. if ($this->shouldProcessForm()) {
  187. $this->enable([
  188. 'onFormProcessed' => ['onFormProcessed', 0],
  189. 'onFormValidationError' => ['onFormValidationError', 0],
  190. 'onFormFieldTypes' => ['onFormFieldTypes', 0],
  191. ]);
  192. /** @var Uri $uri */
  193. $uri = $this->grav['uri'];
  194. /** @var Forms $forms */
  195. $forms = $this->grav['forms'];
  196. $form = $forms->getActiveForm();
  197. if ($form instanceof Form) {
  198. // Post the form
  199. $isJson = $uri->extension() === 'json';
  200. $task = $uri->post('task') ?? $uri->param('task');
  201. if ($isJson) {
  202. if ($task === 'store-state') {
  203. $this->json_response = $form->storeState();
  204. } elseif ($task === 'clear-state') {
  205. $this->json_response = $form->clearState();
  206. } elseif ($task === 'file-remove' || $uri->post('__form-file-remover__')) {
  207. $this->json_response = $form->filesSessionRemove();
  208. } elseif ($task === 'file-upload' || $uri->post('__form-file-uploader__')) {
  209. $this->json_response = $form->uploadFiles();
  210. }
  211. }
  212. if (empty($this->json_response)) {
  213. if ($task === 'clear-state') {
  214. $form->getFlash()->delete();
  215. $redirect = $form->getBlueprint()->get('form/clear_redirect_url') ?? $page->route();
  216. $this->grav->redirect($redirect, 303);
  217. } else {
  218. $form->post();
  219. $submitted = true;
  220. }
  221. }
  222. // Return JSON if we're not in form template.
  223. if ($this->json_response && $page->template() !== 'form') {
  224. $status = $this->json_response['status'] ?? null;
  225. header('Content-Type: application/json');
  226. http_response_code($status === 'error' ? 400 : 200);
  227. echo json_encode($this->json_response);
  228. exit;
  229. }
  230. }
  231. // Clear flash objects for previously uploaded files
  232. // whenever the user switches page / reloads
  233. // ignoring any JSON / extension call
  234. if (!$submitted && null === $uri->extension()) {
  235. // Discard any previously uploaded files session.
  236. // and if there were any uploaded file, remove them from the filesystem
  237. if ($flash = $this->grav['session']->getFlashObject('files-upload')) {
  238. $flash = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($flash));
  239. foreach ($flash as $key => $value) {
  240. if ($key !== 'tmp_name') {
  241. continue;
  242. }
  243. @unlink($value);
  244. }
  245. }
  246. }
  247. } else {
  248. // There is no active form to be posted.
  249. // Check all the forms for the current page; we are looking for forms with remember state turned on with random unique id.
  250. /** @var Route $route */
  251. $route = $this->grav['route'];
  252. $pageForms = $this->forms[$route->getRoute()] ?? [];
  253. foreach ($pageForms as $formName => $form) {
  254. if ($form->get('remember_redirect')) {
  255. // Found one; we need to check if unique id is set.
  256. $formParam = $form->get('uniqueid_param', 'fid');
  257. $uniqueId = $route->getGravParam($formParam);
  258. if ($uniqueId && preg_match('/[a-z\d]+/', $uniqueId)) {
  259. // URL contains unique id, initialize the current form.
  260. $form->setUniqueId($uniqueId);
  261. $form->initialize();
  262. /** @var Forms $forms */
  263. $forms = $this->grav['forms'];
  264. $forms->setActiveForm($form);
  265. break;
  266. }
  267. // Append unique id to the URL and redirect.
  268. $route = $route->withGravParam($formParam, $form->getUniqueId());
  269. $page->redirect((string)$route->toString());
  270. // TODO: Do we want to add support for multiple forms with remembered state?
  271. break;
  272. }
  273. }
  274. }
  275. }
  276. /**
  277. * Add simple `forms()` Twig function
  278. */
  279. public function onTwigInitialized()
  280. {
  281. $this->grav['twig']->twig()->addFunction(
  282. new \Twig_SimpleFunction('forms', [$this, 'getForm'])
  283. );
  284. $this->grav['twig']->twig()->getExtension('Twig_Extension_Core')->setEscaper('yaml', function ($twig, $string, $charset) {
  285. return Yaml::dump($string);
  286. }
  287. );
  288. }
  289. /**
  290. * Add current directory to twig lookup paths.
  291. */
  292. public function onTwigTemplatePaths()
  293. {
  294. $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
  295. }
  296. /**
  297. * Make form accessible from twig.
  298. *
  299. * @param Event $event
  300. */
  301. public function onTwigVariables(Event $event = null)
  302. {
  303. if ($event && isset($event['page'])) {
  304. $page = $event['page'];
  305. } else {
  306. $page = $this->grav['page'];
  307. }
  308. $twig = $this->grav['twig'];
  309. if (!isset($twig->twig_vars['form'])) {
  310. $twig->twig_vars['form'] = $this->form($page);
  311. }
  312. if ($this->config->get('plugins.form.built_in_css')) {
  313. $this->grav['assets']->addCss('plugin://form/assets/form-styles.css');
  314. }
  315. $twig->twig_vars['form_max_filesize'] = Form::getMaxFilesize();
  316. $twig->twig_vars['form_json_response'] = $this->json_response;
  317. }
  318. /**
  319. * Handle form processing instructions.
  320. *
  321. * @param Event $event
  322. * @throws \Exception
  323. */
  324. public function onFormProcessed(Event $event)
  325. {
  326. /** @var Form $form */
  327. $form = $event['form'];
  328. $action = $event['action'];
  329. $params = $event['params'];
  330. $this->process($form);
  331. switch ($action) {
  332. case 'captcha':
  333. $captcha_config = $this->config->get('plugins.form.recaptcha');
  334. $secret = $params['recaptcha_secret'] ?? $params['recatpcha_secret'] ?? $captcha_config['secret_key'];
  335. /** @var Uri $uri */
  336. $uri = $this->grav['uri'];
  337. $action = $form->value('action');
  338. $hostname = $uri->host();
  339. $ip = Uri::ip();
  340. $recaptcha = new ReCaptcha($secret);
  341. if (extension_loaded('curl')) {
  342. $recaptcha = new ReCaptcha($secret, new CurlPost());
  343. }
  344. // get captcha version
  345. $captcha_version = $captcha_config['version'] ?? 2;
  346. // Add version 3 specific options
  347. if ($captcha_version == 3) {
  348. $token = $form->value('token');
  349. $resp = $recaptcha
  350. ->setExpectedHostname($hostname)
  351. ->setExpectedAction($action)
  352. ->setScoreThreshold(0.5)
  353. ->verify($token, $ip);
  354. } else {
  355. $token = $form->value('g-recaptcha-response', true);
  356. $resp = $recaptcha
  357. ->setExpectedHostname($hostname)
  358. ->verify($token, $ip);
  359. }
  360. if (!$resp->isSuccess()) {
  361. $errors = $resp->getErrorCodes();
  362. $message = $this->grav['language']->translate('PLUGIN_FORM.ERROR_VALIDATING_CAPTCHA');
  363. $fields = $form->value()->blueprints()->get('form/fields');
  364. foreach ($fields as $field) {
  365. $type = $field['type'] ?? 'text';
  366. $field_message = $field['recaptcha_not_validated'] ?? null;
  367. if ($type === 'captcha' && $field_message) {
  368. $message = $field_message;
  369. break;
  370. }
  371. }
  372. $this->grav->fireEvent('onFormValidationError', new Event([
  373. 'form' => $form,
  374. 'message' => $message
  375. ]));
  376. $this->grav['log']->addWarning('Form reCAPTCHA Errors: [' . $uri->route() . '] ' . json_encode($errors));
  377. $event->stopPropagation();
  378. return;
  379. }
  380. break;
  381. case 'timestamp':
  382. $label = $params['label'] ?? 'Timestamp';
  383. $format = $params['format'] ?? 'Y-m-d H:i:s';
  384. $blueprint = $form->value()->blueprints();
  385. $blueprint->set('form/fields/timestamp', ['name' => 'timestamp', 'label' => $label, 'type' => 'hidden']);
  386. $now = new \DateTime('now');
  387. $date_string = $now->format($format);
  388. $form->setFields($blueprint->fields());
  389. $form->setData('timestamp', $date_string);
  390. break;
  391. case 'ip':
  392. $label = $params['label'] ?? 'User IP';
  393. $blueprint = $form->value()->blueprints();
  394. $blueprint->set('form/fields/ip', ['name' => 'ip', 'label' => $label, 'type' => 'hidden']);
  395. $form->setFields($blueprint->fields());
  396. $form->setData('ip', Uri::ip());
  397. break;
  398. case 'message':
  399. $translated_string = $this->grav['language']->translate($params);
  400. $vars = array(
  401. 'form' => $form
  402. );
  403. /** @var Twig $twig */
  404. $twig = $this->grav['twig'];
  405. $processed_string = $twig->processString($translated_string, $vars);
  406. $form->message = $processed_string;
  407. break;
  408. case 'redirect':
  409. $this->grav['session']->setFlashObject('form', $form);
  410. $url = ((string)$params);
  411. $vars = array(
  412. 'form' => $form
  413. );
  414. /** @var Twig $twig */
  415. $twig = $this->grav['twig'];
  416. $url = $twig->processString($url, $vars);
  417. $message = $form->message;
  418. if ($message) {
  419. $this->grav['messages']->add($form->message, 'success');
  420. }
  421. $event['redirect'] = $url;
  422. $event->stopPropagation();
  423. break;
  424. case 'reset':
  425. if (Utils::isPositive($params)) {
  426. $message = $form->message;
  427. $form->reset();
  428. $form->message = $message;
  429. }
  430. break;
  431. case 'display':
  432. $route = (string)$params;
  433. if (!$route || $route[0] !== '/') {
  434. /** @var Uri $uri */
  435. $uri = $this->grav['uri'];
  436. $route = rtrim($uri->route(), '/') . '/' . ($route ?: '');
  437. }
  438. /** @var Twig $twig */
  439. $twig = $this->grav['twig'];
  440. $twig->twig_vars['form'] = $form;
  441. /** @var Pages $pages */
  442. $pages = $this->grav['pages'];
  443. $page = $pages->dispatch($route, true);
  444. if (!$page) {
  445. throw new \RuntimeException('Display page not found. Please check the page exists.', 400);
  446. }
  447. unset($this->grav['page']);
  448. $this->grav['page'] = $page;
  449. break;
  450. case 'remember':
  451. foreach ($params as $remember_field) {
  452. $field_cookie = 'forms-' . $form['name'] . '-' . $remember_field;
  453. setcookie($field_cookie, $form->value($remember_field), time() + 60 * 60 * 24 * 60);
  454. }
  455. break;
  456. case 'upload':
  457. if ($params !== false) {
  458. $form->copyFiles();
  459. }
  460. break;
  461. case 'save':
  462. $prefix = $params['fileprefix'] ?? '';
  463. $format = $params['dateformat'] ?? 'Ymd-His-u';
  464. $raw_format = (bool)($params['dateraw'] ?? false);
  465. $postfix = $params['filepostfix'] ?? '';
  466. $ext = !empty($params['extension']) ? '.' . trim($params['extension'], '.') : '.txt';
  467. $filename = $params['filename'] ?? '';
  468. $folder = !empty($params['folder']) ? $params['folder'] : $form->getName();
  469. $operation = $params['operation'] ?? 'create';
  470. if (!$filename) {
  471. if ($operation === 'add') {
  472. throw new \RuntimeException('Form save: \'operation: add\' is only supported with a static filename');
  473. }
  474. $filename = $prefix . $this->udate($format, $raw_format) . $postfix . $ext;
  475. }
  476. /** @var Twig $twig */
  477. $twig = $this->grav['twig'];
  478. $vars = [
  479. 'form' => $form
  480. ];
  481. // Process with Twig
  482. $filename = $twig->processString($filename, $vars);
  483. $locator = $this->grav['locator'];
  484. $path = $locator->findResource('user-data://', true);
  485. $dir = $path . DS . $folder;
  486. $fullFileName = $dir . DS . $filename;
  487. if (!empty($params['raw']) || !empty($params['template'])) {
  488. // Save data as it comes from the form.
  489. if ($operation === 'add') {
  490. throw new \RuntimeException('Form save: \'operation: add\' is not supported for raw files');
  491. }
  492. switch ($ext) {
  493. case '.yaml':
  494. $file = YamlFile::instance($fullFileName);
  495. break;
  496. case '.json':
  497. $file = JsonFile::instance($fullFileName);
  498. break;
  499. default:
  500. throw new \RuntimeException('Form save: Unsupported RAW file format, please use either yaml or json');
  501. }
  502. $content = $form->getData();
  503. $data = [
  504. '_data_type' => 'form',
  505. 'template' => !empty($params['template']) ? $params['template'] : null,
  506. 'name' => $form->getName(),
  507. 'timestamp' => date('Y-m-d H:i:s'),
  508. 'content' => $content ? $content->toArray() : []
  509. ];
  510. $file->lock();
  511. $form->copyFiles();
  512. $file->save(array_filter($data));
  513. break;
  514. }
  515. $file = File::instance($fullFileName);
  516. $file->lock();
  517. $form->copyFiles();
  518. if ($operation === 'create') {
  519. $body = $twig->processString($params['body'] ?? '{% include "forms/data.txt.twig" %}', $vars);
  520. $file->save($body);
  521. } elseif ($operation === 'add') {
  522. if (!empty($params['body'])) {
  523. // use body similar to 'create' action and append to file as a log
  524. $body = $twig->processString($params['body'], $vars);
  525. // create folder if it doesn't exist
  526. if (!file_exists($dir)) {
  527. Folder::create($dir);
  528. }
  529. // append data to existing file
  530. $file->unlock();
  531. file_put_contents($fullFileName, $body, FILE_APPEND | LOCK_EX);
  532. } else {
  533. // serialize YAML out to file for easier parsing as data sets
  534. $vars = $vars['form']->value()->toArray();
  535. foreach ($form->fields as $field) {
  536. if (!empty($field['process']['ignore'])) {
  537. unset($vars[$field['name']]);
  538. }
  539. }
  540. if (file_exists($fullFileName)) {
  541. $data = Yaml::parse($file->content());
  542. if (\count($data) > 0) {
  543. array_unshift($data, $vars);
  544. } else {
  545. $data[] = $vars;
  546. }
  547. } else {
  548. $data[] = $vars;
  549. }
  550. $file->save(Yaml::dump($data));
  551. }
  552. }
  553. break;
  554. case 'call':
  555. $callable = $params;
  556. if (\is_array($callable) && !method_exists($callable[0], $callable[1])) {
  557. throw new \RuntimeException('Form cannot be processed (method does not exist)');
  558. }
  559. if (\is_string($callable) && !\function_exists($callable)) {
  560. throw new \RuntimeException('Form cannot be processed (function does not exist)');
  561. }
  562. $callable($form);
  563. break;
  564. }
  565. }
  566. /**
  567. * Custom field logic can go in here
  568. *
  569. * @param Event $event
  570. */
  571. public function onFormValidationProcessed(Event $event)
  572. {
  573. // special check for honeypot field
  574. foreach ($event['form']->fields() as $field) {
  575. if ($field['type'] === 'honeypot' && !empty($event['form']->value($field['name']))) {
  576. throw new ValidationException('Are you a bot?');
  577. }
  578. }
  579. }
  580. /**
  581. * Handle form validation error
  582. *
  583. * @param Event $event An event object
  584. * @throws \Exception
  585. */
  586. public function onFormValidationError(Event $event)
  587. {
  588. $form = $event['form'];
  589. if (isset($event['message'])) {
  590. $form->status = 'error';
  591. $form->message = $event['message'];
  592. $form->messages = $event['messages'];
  593. }
  594. $uri = $this->grav['uri'];
  595. $route = $uri->route();
  596. /** @var Twig $twig */
  597. $twig = $this->grav['twig'];
  598. $twig->twig_vars['form'] = $form;
  599. /** @var Pages $pages */
  600. $pages = $this->grav['pages'];
  601. $page = $pages->dispatch($route, true);
  602. if ($page) {
  603. unset($this->grav['page']);
  604. $this->grav['page'] = $page;
  605. }
  606. $event->stopPropagation();
  607. }
  608. /**
  609. * Add a form to the forms plugin
  610. *
  611. * @param string|null $page_route
  612. * @param FormInterface|null $form
  613. */
  614. public function addForm(?string $page_route, ?FormInterface $form)
  615. {
  616. if (null === $form) {
  617. return;
  618. }
  619. $name = $form->getName();
  620. if (!isset($this->forms[$page_route][$name])) {
  621. $this->forms[$page_route][$name] = $form;
  622. $this->flattenForms();
  623. $this->recache_forms = true;
  624. }
  625. }
  626. /**
  627. * function to get a specific form
  628. *
  629. * @param null|array|string $data optional form `name`
  630. *
  631. * @return FormInterface|null
  632. */
  633. public function getForm($data = null)
  634. {
  635. if (\is_array($data)) {
  636. $form_name = $data['name'] ?? null;
  637. $page_route = $data['route'] ?? null;
  638. } elseif (\is_string($data)) {
  639. $form_name = $data;
  640. $page_route = null;
  641. } else {
  642. $form_name = null;
  643. $page_route = null;
  644. }
  645. // if no form name, use the first form found in the page
  646. if (!$form_name) {
  647. // If page route not provided, use the current page
  648. if (!$page_route) {
  649. // Get page route with a fallback using current URI if page not initialized yet
  650. $page_route = $this->grav['page']->route() ?: $this->getCurrentPageRoute();
  651. }
  652. if (!empty($this->forms[$page_route])) {
  653. $forms = $this->forms[$page_route];
  654. $first_form = reset($forms) ?: null;
  655. return $first_form;
  656. } else {
  657. //No form on this route. Try looking up in the current page first
  658. /** @var Forms $forms */
  659. $forms = $this->grav['forms'];
  660. return $forms->createPageForm($this->grav['page']);
  661. }
  662. }
  663. // return the form you are looking for if available
  664. return $this->getFormByName($form_name);
  665. }
  666. /**
  667. * Get list of form field types specified in this plugin. Only special types needs to be listed.
  668. *
  669. * @return array
  670. */
  671. public function getFormFieldTypes()
  672. {
  673. return [
  674. 'avatar' => [
  675. 'input@' => false
  676. ],
  677. 'captcha' => [
  678. 'input@' => false
  679. ],
  680. 'columns' => [
  681. 'input@' => false
  682. ],
  683. 'column' => [
  684. 'input@' => false
  685. ],
  686. 'conditional' => [
  687. 'input@' => false
  688. ],
  689. 'display' => [
  690. 'input@' => false
  691. ],
  692. 'fieldset' => [
  693. 'input@' => false
  694. ],
  695. 'file' => [
  696. 'array' => true,
  697. 'validate' => [
  698. 'type' => 'ignore'
  699. ]
  700. ],
  701. 'formname' => [
  702. 'input@' => false
  703. ],
  704. 'honeypot' => [
  705. 'input@' => false
  706. ],
  707. 'ignore' => [
  708. 'input@' => false
  709. ],
  710. 'key' => [
  711. 'input@' => false
  712. ],
  713. 'section' => [
  714. 'input@' => false
  715. ],
  716. 'spacer' => [
  717. 'input@' => false
  718. ],
  719. 'tabs' => [
  720. 'input@' => false
  721. ],
  722. 'tab' => [
  723. 'input@' => false
  724. ],
  725. 'uniqueid' => [
  726. 'input@' => false
  727. ],
  728. 'value' => [
  729. 'input@' => false
  730. ]
  731. ];
  732. }
  733. /**
  734. * Process a form
  735. *
  736. * Currently available processing tasks:
  737. *
  738. * - fillWithCurrentDateTime
  739. *
  740. * @param Form $form
  741. */
  742. protected function process($form)
  743. {
  744. foreach ($form->fields as $field) {
  745. if (!empty($field['process']['fillWithCurrentDateTime'])) {
  746. $form->setData($field['name'], gmdate('D, d M Y H:i:s', time()));
  747. }
  748. }
  749. }
  750. /**
  751. * Get current page's route
  752. *
  753. * @return mixed
  754. */
  755. protected function getCurrentPageRoute()
  756. {
  757. $path = $this->grav['uri']->route();
  758. $path = $path ?: '/';
  759. return $path;
  760. }
  761. /**
  762. * Retrieve a form based on the form name
  763. *
  764. * @param $form_name
  765. * @return mixed
  766. */
  767. protected function getFormByName($form_name)
  768. {
  769. $form = $this->active_forms[$form_name] ?? null;
  770. if (!$form) {
  771. $form = $this->flat_forms[$form_name] ?? null;
  772. if (!$form) {
  773. return null;
  774. }
  775. // Reset form to change the cached unique id and to fire onFormInitialized event.
  776. $form->setUniqueId('');
  777. $form->reset();
  778. // Register form to the active forms to get the same instance back next time.
  779. $this->active_forms[$form_name] = $form;
  780. }
  781. return $form;
  782. }
  783. /**
  784. * Determine if the page has a form submission that should be processed
  785. *
  786. * @return bool
  787. */
  788. protected function shouldProcessForm()
  789. {
  790. $uri = $this->grav['uri'];
  791. $nonce = $uri->post('form-nonce');
  792. $status = $nonce ? true : false; // php72 quirk?
  793. $refresh_prevention = null;
  794. if ($status && $form = $this->form()) {
  795. // Make sure form is something we recognize.
  796. if (!$form instanceof Form) {
  797. return false;
  798. }
  799. // Set page template if passed by form
  800. if (isset($form->template)) {
  801. $this->grav['page']->template($form->template);
  802. }
  803. if (isset($form->refresh_prevention)) {
  804. $refresh_prevention = (bool)$form->refresh_prevention;
  805. } else {
  806. $refresh_prevention = $this->config->get('plugins.form.refresh_prevention', false);
  807. }
  808. $unique_form_id = $form->getUniqueId();
  809. if ($refresh_prevention && $unique_form_id) {
  810. if ($this->grav['session']->unique_form_id !== $unique_form_id) {
  811. $isJson = $uri->extension() === 'json';
  812. // AJAX tasks aren't submitting
  813. if (!$isJson || !($uri->post('__form-file-uploader__') || $uri->post('__form-file-remover__'))) {
  814. $this->grav['session']->unique_form_id = $unique_form_id;
  815. }
  816. } else {
  817. $status = false;
  818. $form->message = $this->grav['language']->translate('PLUGIN_FORM.FORM_ALREADY_SUBMITTED');
  819. $form->status = 'error';
  820. }
  821. }
  822. }
  823. return $status;
  824. }
  825. /**
  826. * Flatten the forms array into something that can be more easily searched
  827. */
  828. protected function flattenForms()
  829. {
  830. $this->flat_forms = Utils::arrayFlatten($this->forms);
  831. }
  832. /**
  833. * Get the current form, should already be processed but can get it directly from the page if necessary
  834. *
  835. * @param PageInterface|null $page
  836. * @return Form|null
  837. */
  838. protected function form(PageInterface $page = null)
  839. {
  840. // Regenerate list of flat_forms if not already populated
  841. if (empty($this->flat_forms)) {
  842. $this->flattenForms();
  843. }
  844. /** @var Forms $forms */
  845. $forms = $this->grav['forms'];
  846. $form = $forms->getActiveForm();
  847. if (null === $form) {
  848. // try to get the page if possible
  849. if (null === $page) {
  850. $page = $this->grav['page'];
  851. }
  852. // Try to find the posted form if available.
  853. $form_name = $this->grav['uri']->post('__form-name__', FILTER_SANITIZE_STRING);
  854. $unique_id = $this->grav['uri']->post('__unique_form_id__', FILTER_SANITIZE_STRING);
  855. if (!$form_name) {
  856. $form_name = $page ? $page->slug() : null;
  857. }
  858. $form = $this->getFormByName($form_name);
  859. // last attempt using current page's form
  860. if (!$form && $page) {
  861. $form = $forms->createPageForm($page);
  862. }
  863. if ($form) {
  864. // Only set posted unique id if the form name matches to the one that was posted.
  865. if ($unique_id && $form_name === $form->getFormName()) {
  866. $form->setUniqueId($unique_id);
  867. $form->initialize();
  868. }
  869. $forms->setActiveForm($form);
  870. }
  871. }
  872. return $form;
  873. }
  874. /**
  875. * @param PageInterface $page
  876. * @param string|int|null $name
  877. * @param array $form
  878. * @return Form|null
  879. * @deprecated
  880. */
  881. protected function createForm(PageInterface $page, $name = null, $form = null)
  882. {
  883. $header = $page->header();
  884. if (isset($header->form) || isset($header->forms)) {
  885. return new Form($page, $name, $form);
  886. }
  887. return null;
  888. }
  889. /**
  890. * Load cached forms and merge with any currently found forms
  891. */
  892. protected function loadCachedForms()
  893. {
  894. // Get and set the cache of forms if it exists
  895. try {
  896. [$forms] = $this->grav['cache']->fetch($this->getFormCacheId());
  897. } catch (\Exception $e) {
  898. // Couldn't fetch cached forms.
  899. $forms = null;
  900. /** @var Debugger $debugger */
  901. $debugger = Grav::instance()['debugger'];
  902. $debugger->addMessage(sprintf('Unserializing cached forms failed: %s', $e->getMessage()), 'error');
  903. }
  904. if (!\is_array($forms)) {
  905. return;
  906. }
  907. // Only update the forms if it's not empty
  908. if (!empty($forms)) {
  909. $this->forms = array_merge($this->forms, $forms);
  910. $this->flattenForms();
  911. }
  912. }
  913. /**
  914. * Save the current state of the forms
  915. */
  916. protected function saveCachedForms()
  917. {
  918. // Save the current state of the forms to cache
  919. if ($this->recache_forms) {
  920. $this->recache_forms = false;
  921. $this->grav['cache']->save($this->getFormCacheId(), [$this->forms]);
  922. }
  923. }
  924. /**
  925. * Get the current page cache based id for the forms cache
  926. *
  927. * @return string
  928. */
  929. protected function getFormCacheId()
  930. {
  931. return $this->grav['pages']->getPagesCacheId() . '-form-plugin';
  932. }
  933. /**
  934. * Create unix timestamp for storing the data into the filesystem.
  935. *
  936. * @param string $format
  937. * @param bool $raw
  938. *
  939. * @return string
  940. */
  941. protected function udate($format = 'u', $raw = false)
  942. {
  943. $utimestamp = microtime(true);
  944. if ($raw) {
  945. return date($format);
  946. }
  947. $timestamp = floor($utimestamp);
  948. $milliseconds = round(($utimestamp - $timestamp) * 1000000);
  949. return date(preg_replace('`(?<!\\\\)u`', \sprintf('%06d', $milliseconds), $format), $timestamp);
  950. }
  951. }