form.php 37 KB

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