form.php 42 KB

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