form.php 35 KB

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