12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331 |
- <?php
- namespace Grav\Plugin\Form;
- use Grav\Common\Config\Config;
- use Grav\Common\Data\Data;
- use Grav\Common\Data\Blueprint;
- use Grav\Common\Data\ValidationException;
- use Grav\Common\Filesystem\Folder;
- use Grav\Common\Form\FormFlash;
- use Grav\Common\Grav;
- use Grav\Common\Inflector;
- use Grav\Common\Language\Language;
- use Grav\Common\Page\Interfaces\PageInterface;
- use Grav\Common\Security;
- use Grav\Common\Uri;
- use Grav\Common\Utils;
- use Grav\Framework\Filesystem\Filesystem;
- use Grav\Framework\Form\FormFlashFile;
- use Grav\Framework\Form\Interfaces\FormInterface;
- use Grav\Framework\Form\Traits\FormTrait;
- use Grav\Framework\Route\Route;
- use RocketTheme\Toolbox\ArrayTraits\NestedArrayAccessWithGetters;
- use RocketTheme\Toolbox\Event\Event;
- use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
- /**
- * Class Form
- * @package Grav\Plugin\Form
- *
- * @property string $id
- * @property string $uniqueid
- * @property-read string $name
- * @property-read string $noncename
- * @property-read $string nonceaction
- * @property-read string $action
- * @property-read Data $data
- * @property-read array $files
- * @property-read Data $value
- * @property array $errors
- * @property-read array $fields
- * @property-read Blueprint $blueprint
- * @property-read PageInterface $page
- */
- class Form implements FormInterface, \ArrayAccess
- {
- use NestedArrayAccessWithGetters {
- NestedArrayAccessWithGetters::get as private traitGet;
- NestedArrayAccessWithGetters::set as private traitSet;
- }
- use FormTrait {
- FormTrait::reset as private traitReset;
- FormTrait::doSerialize as private doTraitSerialize;
- FormTrait::doUnserialize as private doTraitUnserialize;
- }
- public const BYTES_TO_MB = 1048576;
- /**
- * @var string
- */
- public $message;
- /**
- * @var int
- */
- public $response_code;
- /**
- * @var string
- */
- public $status = 'success';
- /**
- * @var array
- */
- protected $header_data = [];
- /**
- * @var array
- */
- protected $rules = [];
- /**
- * Form header items
- *
- * @var array $items
- */
- protected $items = [];
- /**
- * All the form data values, including non-data
- *
- * @var Data $values
- */
- protected $values;
- /**
- * The form page route
- *
- * @var string $page
- */
- protected $page;
- /**
- * Create form for the given page.
- *
- * @param PageInterface $page
- * @param string|int|null $name
- * @param array|null $form
- */
- public function __construct(PageInterface $page, $name = null, $form = null)
- {
- $this->nestedSeparator = '/';
- $slug = $page->slug();
- $header = $page->header();
- $this->rules = $header->rules ?? [];
- $this->header_data = $header->data ?? [];
- if ($form) {
- // If form is given, use it.
- $this->items = $form;
- } else {
- // Otherwise get all forms in the page.
- $forms = $page->forms();
- if ($name) {
- // If form with given name was found, use that.
- $this->items = $forms[$name] ?? [];
- } else {
- // Otherwise pick up the first form.
- $this->items = reset($forms) ?: [];
- $name = key($forms);
- }
- }
- // If we're on a modular page, find the real page.
- while ($page && $page->modularTwig()) {
- $header = $page->header();
- $header->never_cache_twig = true;
- $page = $page->parent();
- }
- $this->page = $page ? $page->route() : '/';
- // Add form specific rules.
- if (!empty($this->items['rules']) && \is_array($this->items['rules'])) {
- $this->rules += $this->items['rules'];
- }
- // Set form name if not set.
- if ($name && !\is_int($name)) {
- $this->items['name'] = $name;
- } elseif (empty($this->items['name'])) {
- $this->items['name'] = $slug;
- }
- // Set form id if not set.
- if (empty($this->items['id'])) {
- $this->items['id'] = Inflector::hyphenize($this->items['name']);
- }
- if (empty($this->items['nonce']['name'])) {
- $this->items['nonce']['name'] = 'form-nonce';
- }
- if (empty($this->items['nonce']['action'])) {
- $this->items['nonce']['action'] = 'form';
- }
- // Initialize form properties.
- $this->name = $this->items['name'];
- $this->setId($this->items['id']);
- $uniqueid = $this->items['uniqueid'] ?? null;
- if (null === $uniqueid && !empty($this->items['remember_state'])) {
- $this->set('remember_redirect', true);
- }
- $this->setUniqueId($uniqueid ?? strtolower(Utils::generateRandomString($this->items['uniqueid_len'] ?? 20)));
- $this->initialize();
- }
- /**
- * @return $this
- */
- public function initialize()
- {
- // Reset and initialize the form
- $this->errors = [];
- $this->submitted = false;
- $this->unsetFlash();
- // Remember form state.
- $flash = $this->getFlash();
- if ($flash->exists()) {
- $data = $flash->getData() ?? $this->header_data;
- } else {
- $data = $this->header_data;
- }
- // Remember data and files.
- $this->setAllData($data);
- $this->setAllFiles($flash);
- $this->values = new Data();
- // Fire event
- $grav = Grav::instance();
- $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
- return $this;
- }
- protected function setAllFiles(FormFlash $flash)
- {
- if (!$flash->exists()) {
- return;
- }
- /** @var Uri $url */
- $url = Grav::instance()['uri'];
- $fields = $flash->getFilesByFields(true);
- foreach ($fields as $field => $files) {
- if (strpos($field, '/') !== false) {
- continue;
- }
- $list = [];
- /**
- * @var string $filename
- * @var FormFlashFile $file
- */
- foreach ($files as $filename => $file) {
- $original = $fields["{$field}/original"][$filename] ?? $file;
- $basename = basename($filename);
- if ($file) {
- $imagePath = $original->getTmpFile();
- $thumbPath = $file->getTmpFile();
- $list[$basename] = [
- 'name' => $file->getClientFilename(),
- 'type' => $file->getClientMediaType(),
- 'size' => $file->getSize(),
- 'image_url' => $url->rootUrl() . '/' . Folder::getRelativePath($imagePath) . '?' . filemtime($imagePath),
- 'thumb_url' => $url->rootUrl() . '/' . Folder::getRelativePath($thumbPath) . '?' . filemtime($thumbPath),
- 'cropData' => $original->getMetaData()['crop'] ?? []
- ];
- }
- }
- $this->setData($field, $list);
- }
- }
- /**
- * Reset form.
- */
- public function reset(): void
- {
- $this->traitReset();
- // Reset and initialize the form
- $this->blueprint = null;
- $this->setAllData($this->header_data);
- $this->values = new Data();
- // Reset unique id (allow multiple form submits)
- $uniqueid = $this->items['uniqueid'] ?? null;
- $this->set('remember_redirect', null === $uniqueid && !empty($this->items['remember_state']));
- $this->setUniqueId($uniqueid ?? strtolower(Utils::generateRandomString($this->items['uniqueid_len'] ?? 20)));
- // Fire event
- $grav = Grav::instance();
- $grav->fireEvent('onFormInitialized', new Event(['form' => $this]));
- }
- public function get($name, $default = null, $separator = null)
- {
- switch (strtolower($name)) {
- case 'id':
- case 'uniqueid':
- case 'name':
- case 'noncename':
- case 'nonceaction':
- case 'action':
- case 'data':
- case 'files':
- case 'errors';
- case 'fields':
- case 'blueprint':
- case 'page':
- $method = 'get' . $name;
- return $this->{$method}();
- }
- return $this->traitGet($name, $default, $separator);
- }
- public function getAction(): string
- {
- return $this->items['action'] ?? $this->page;
- }
- /**
- * @param $message
- * @param string $type
- * @todo Type not used
- */
- public function setMessage($message, $type = 'error')
- {
- $this->setError($message);
- }
- public function set($name, $value, $separator = null)
- {
- switch (strtolower($name)) {
- case 'id':
- case 'uniqueid':
- $method = 'set' . $name;
- return $this->{$method}();
- }
- return $this->traitSet($name, $value, $separator);
- }
- /**
- * Get the nonce value for a form
- *
- * @return string
- */
- public function getNonce(): string
- {
- return Utils::getNonce($this->getNonceAction());
- }
- /**
- * @inheritdoc
- */
- public function getNonceName(): string
- {
- return $this->items['nonce']['name'];
- }
- /**
- * @inheritdoc
- */
- public function getNonceAction(): string
- {
- return $this->items['nonce']['action'];
- }
- /**
- * @inheritdoc
- */
- public function getValue(string $name)
- {
- return $this->values->get($name);
- }
- /**
- * @return Data
- */
- public function getValues(): Data
- {
- return $this->values;
- }
- /**
- * @inheritdoc
- */
- public function getFields(): array
- {
- return $this->getBlueprint()->fields();
- }
- /**
- * Return page object for the form.
- *
- * @return PageInterface
- */
- public function getPage(): PageInterface
- {
- return Grav::instance()['pages']->dispatch($this->page);
- }
- /**
- * @inheritdoc
- */
- public function getBlueprint(): Blueprint
- {
- if (null === $this->blueprint) {
- // Fix naming for fields (supports nested fields now!)
- if (isset($this->items['fields'])) {
- $this->items['fields'] = $this->processFields($this->items['fields']);
- }
- $blueprint = new Blueprint($this->name, ['form' => $this->items, 'rules' => $this->rules]);
- $blueprint->load()->init();
- $this->blueprint = $blueprint;
- }
- return $this->blueprint;
- }
- /**
- * Allow overriding of fields.
- *
- * @param array $fields
- */
- public function setFields(array $fields = [])
- {
- $this->items['fields'] = $fields;
- unset($this->items['field']);
- // Reset blueprint.
- $this->blueprint = null;
- // Update data to contain the new blueprints.
- $this->setAllData($this->data->toArray());
- }
- /**
- * Get value of given variable (or all values).
- * First look in the $data array, fallback to the $values array
- *
- * @param string $name
- * @param bool $fallback
- * @return mixed
- */
- public function value($name = null, $fallback = false)
- {
- if (!$name) {
- return $this->data;
- }
- if (isset($this->data[$name])) {
- return $this->data[$name];
- }
- if ($fallback) {
- return $this->values[$name];
- }
- return null;
- }
- /**
- * Get value of given variable (or all values).
- *
- * @param string $name
- * @return mixed
- */
- public function data($name = null)
- {
- return $this->value($name);
- }
- /**
- * Set value of given variable in the values array
- *
- * @param string $name
- * @param mixed $value
- */
- public function setValue($name = null, $value = '')
- {
- if (!$name) {
- return;
- }
- $this->values->set($name, $value);
- }
- /**
- * Set value of given variable in the data array
- *
- * @param string $name
- * @param string $value
- *
- * @return bool
- */
- public function setData($name = null, $value = '')
- {
- if (!$name) {
- return false;
- }
- $this->data->set($name, $value);
- return true;
- }
- public function setAllData($array): void
- {
- $callable = function () {
- return $this->getBlueprint();
- };
- $this->data = new Data($array, $callable);
- }
- /**
- * Handles ajax upload for files.
- * Stores in a flash object the temporary file and deals with potential file errors.
- *
- * @return mixed True if the action was performed.
- */
- public function uploadFiles()
- {
- $grav = Grav::instance();
- /** @var Uri $uri */
- $uri = $grav['uri'];
- $url = $uri->url;
- $post = $uri->post();
- $name = $post['name'] ?? null;
- $task = $post['task'] ?? null;
- /** @var Language $language */
- $language = $grav['language'];
- /** @var Config $config */
- $config = $grav['config'];
- $settings = $this->getBlueprint()->schema()->getProperty($name);
- $settings = (object) array_merge(
- ['destination' => $config->get('plugins.form.files.destination', 'self@'),
- 'avoid_overwriting' => $config->get('plugins.form.files.avoid_overwriting', false),
- 'random_name' => $config->get('plugins.form.files.random_name', false),
- 'accept' => $config->get('plugins.form.files.accept', ['image/*']),
- 'limit' => $config->get('plugins.form.files.limit', 10),
- 'filesize' => static::getMaxFilesize(),
- ],
- (array) $settings,
- ['name' => $name]
- );
- // Allow plugins to adapt settings for a given post name
- // Useful if schema retrieval is not an option, e.g. dynamically created forms
- $grav->fireEvent('onFormUploadSettings', new Event(['settings' => &$settings, 'post' => $post]));
- $upload = json_decode(json_encode($this->normalizeFiles($_FILES['data'], $settings->name)), true);
- $filename = $post['filename'] ?? $upload['file']['name'];
- $field = $upload['field'];
- // Handle errors and breaks without proceeding further
- if ($upload['file']['error'] !== UPLOAD_ERR_OK) {
- // json_response
- return [
- 'status' => 'error',
- 'message' => sprintf(
- $language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true),
- $filename,
- $this->getFileUploadError($upload['file']['error'], $language)
- )
- ];
- }
- // Handle bad filenames.
- if (!Utils::checkFilename($filename)) {
- return [
- 'status' => 'error',
- 'message' => sprintf($language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null),
- $filename, 'Bad filename')
- ];
- }
- if (!isset($settings->destination)) {
- return [
- 'status' => 'error',
- 'message' => $language->translate('PLUGIN_FORM.DESTINATION_NOT_SPECIFIED', null)
- ];
- }
- // Remove the error object to avoid storing it
- unset($upload['file']['error']);
- // Handle Accepted file types
- // Accept can only be mime types (image/png | image/*) or file extensions (.pdf|.jpg)
- $accepted = false;
- $errors = [];
- // Do not trust mimetype sent by the browser
- $mime = Utils::getMimeByFilename($filename);
- foreach ((array)$settings->accept as $type) {
- // Force acceptance of any file when star notation
- if ($type === '*') {
- $accepted = true;
- break;
- }
- $isMime = strstr($type, '/');
- $find = str_replace(['.', '*', '+'], ['\.', '.*', '\+'], $type);
- if ($isMime) {
- $match = preg_match('#' . $find . '$#', $mime);
- if (!$match) {
- $errors[] = sprintf($language->translate('PLUGIN_FORM.INVALID_MIME_TYPE', null, true), $mime, $filename);
- } else {
- $accepted = true;
- break;
- }
- } else {
- $match = preg_match('#' . $find . '$#', $filename);
- if (!$match) {
- $errors[] = sprintf($language->translate('PLUGIN_FORM.INVALID_FILE_EXTENSION', null, true), $filename);
- } else {
- $accepted = true;
- break;
- }
- }
- }
- if (!$accepted) {
- // json_response
- return [
- 'status' => 'error',
- 'message' => implode('<br/>', $errors)
- ];
- }
- // Handle file size limits
- $settings->filesize *= self::BYTES_TO_MB; // 1024 * 1024 [MB in Bytes]
- if ($settings->filesize > 0 && $upload['file']['size'] > $settings->filesize) {
- // json_response
- return [
- 'status' => 'error',
- 'message' => $language->translate('PLUGIN_FORM.EXCEEDED_GRAV_FILESIZE_LIMIT')
- ];
- }
- // Generate random name if required
- if ($settings->random_name) {
- $extension = pathinfo($filename, PATHINFO_EXTENSION);
- $filename = Utils::generateRandomString(15) . '.' . $extension;
- }
- // Look up for destination
- /** @var UniformResourceLocator $locator */
- $locator = $grav['locator'];
- $destination = $settings->destination;
- if (!$locator->isStream($destination)) {
- $destination = $this->getPagePathFromToken(Folder::getRelativePath(rtrim($settings->destination, '/')));
- }
- // Handle conflicting name if needed
- if ($settings->avoid_overwriting) {
- if (file_exists($destination . '/' . $filename)) {
- $filename = date('YmdHis') . '-' . $filename;
- }
- }
- // Prepare object for later save
- $path = $destination . '/' . $filename;
- $upload['file']['name'] = $filename;
- $upload['file']['path'] = $path;
- // Special Sanitization for SVG
- if (method_exists('Grav\Common\Security', 'sanitizeSVG') && Utils::contains($mime, 'svg', false)) {
- Security::sanitizeSVG($upload['file']['tmp_name']);
- }
- // We need to store the file into flash object or it will not be available upon save later on.
- $flash = $this->getFlash();
- $flash->setUrl($url)->setUser($grav['user'] ?? null);
- if ($task === 'cropupload') {
- $crop = $post['crop'];
- if (\is_string($crop)) {
- $crop = json_decode($crop, true);
- }
- $success = $flash->cropFile($field, $filename, $upload, $crop);
- } else {
- $success = $flash->uploadFile($field, $filename, $upload);
- }
- if (!$success) {
- // json_response
- return [
- 'status' => 'error',
- 'message' => sprintf($language->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '', $flash->getTmpDir())
- ];
- }
- $flash->save();
- // json_response
- $json_response = [
- 'status' => 'success',
- 'session' => \json_encode([
- 'sessionField' => base64_encode($url),
- 'path' => $path,
- 'field' => $settings->name,
- 'uniqueid' => $this->uniqueid
- ])
- ];
- // Return JSON
- header('Content-Type: application/json');
- echo json_encode($json_response);
- exit;
- }
- /**
- * Return an error message for a PHP file upload error code
- * https://www.php.net/manual/en/features.file-upload.errors.php
- *
- * @param int $error PHP file upload error code
- * @param Language|null $language
- * @return string File upload error message
- */
- public function getFileUploadError(int $error, Language $language = null): string
- {
- if (!$language) {
- $grav = Grav::instance();
- /** @var Language $language */
- $language = $grav['language'];
- }
- switch ($error) {
- case UPLOAD_ERR_OK:
- $item = 'FILEUPLOAD_ERR_OK';
- break;
- case UPLOAD_ERR_INI_SIZE:
- $item = 'FILEUPLOAD_ERR_INI_SIZE';
- break;
- case UPLOAD_ERR_FORM_SIZE:
- $item = 'FILEUPLOAD_ERR_FORM_SIZE';
- break;
- case UPLOAD_ERR_PARTIAL:
- $item = 'FILEUPLOAD_ERR_PARTIAL';
- break;
- case UPLOAD_ERR_NO_FILE:
- $item = 'FILEUPLOAD_ERR_NO_FILE';
- break;
- case UPLOAD_ERR_NO_TMP_DIR:
- $item = 'FILEUPLOAD_ERR_NO_TMP_DIR';
- break;
- case UPLOAD_ERR_CANT_WRITE:
- $item = 'FILEUPLOAD_ERR_CANT_WRITE';
- break;
- case UPLOAD_ERR_EXTENSION:
- $item = 'FILEUPLOAD_ERR_EXTENSION';
- break;
- default:
- $item = 'FILEUPLOAD_ERR_UNKNOWN';
- }
- return $language->translate('PLUGIN_FORM.'.$item);
- }
- /**
- * Removes a file from the flash object session, before it gets saved.
- */
- public function filesSessionRemove(): void
- {
- $callable = function (): array {
- $field = $this->values->get('name');
- $filename = $this->values->get('filename');
- if (!isset($field, $filename)) {
- throw new \RuntimeException('Bad Request: name and/or filename are missing', 400);
- }
- $this->removeFlashUpload($filename, $field);
- return ['status' => 'success'];
- };
- $this->sendJsonResponse($callable);
- }
- public function storeState(): void
- {
- $callable = function (): array {
- $this->updateFlashData($this->values->get('data') ?? []);
- return ['status' => 'success'];
- };
- $this->sendJsonResponse($callable);
- }
- public function clearState(): void
- {
- $callable = function (): array {
- $this->getFlash()->delete();
- return ['status' => 'success'];
- };
- $this->sendJsonResponse($callable);
- }
- /**
- * Handle form processing on POST action.
- */
- public function post()
- {
- $grav = Grav::instance();
- /** @var Uri $uri */
- $uri = $grav['uri'];
- // Get POST data and decode JSON fields into arrays
- $post = $uri->post();
- $post['data'] = $this->decodeData($post['data'] ?? []);
- if ($post) {
- $this->values = new Data((array)$post);
- $data = $this->values->get('data');
- // Add post data to form dataset
- if (!$data) {
- $data = $this->values->toArray();
- }
- if (!$this->values->get('form-nonce') || !Utils::verifyNonce($this->values->get('form-nonce'), 'form')) {
- $this->status = 'error';
- $event = new Event(['form' => $this,
- 'message' => $grav['language']->translate('PLUGIN_FORM.NONCE_NOT_VALIDATED')
- ]);
- $grav->fireEvent('onFormValidationError', $event);
- return;
- }
- $i = 0;
- foreach ($this->items['fields'] as $key => $field) {
- $name = $field['name'] ?? $key;
- if (!isset($field['name'])) {
- if (isset($data[$i])) { //Handle input@ false fields
- $data[$name] = $data[$i];
- unset($data[$i]);
- }
- }
- if ($field['type'] === 'checkbox' || $field['type'] === 'switch') {
- $data[$name] = isset($data[$name]) ? true : false;
- }
- $i++;
- }
- $this->data->merge($data);
- }
- // Validate and filter data
- try {
- $grav->fireEvent('onFormPrepareValidation', new Event(['form' => $this]));
- $this->data->validate();
- $this->data->filter();
- $grav->fireEvent('onFormValidationProcessed', new Event(['form' => $this]));
- } catch (ValidationException $e) {
- $this->status = 'error';
- $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => $e->getMessages()]);
- $grav->fireEvent('onFormValidationError', $event);
- if ($event->isPropagationStopped()) {
- return;
- }
- } catch (\RuntimeException $e) {
- $this->status = 'error';
- $event = new Event(['form' => $this, 'message' => $e->getMessage(), 'messages' => []]);
- $grav->fireEvent('onFormValidationError', $event);
- if ($event->isPropagationStopped()) {
- return;
- }
- }
- $redirect = $redirect_code = null;
- $process = $this->items['process'] ?? [];
- $legacyUploads = !isset($process['upload']) || $process['upload'] !== false;
- if ($legacyUploads) {
- $this->legacyUploads();
- }
- if (\is_array($process)) {
- foreach ($process as $action => $data) {
- if (is_numeric($action)) {
- $action = \key($data);
- $data = $data[$action];
- }
- $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
- $grav->fireEvent('onFormProcessed', $event);
- if ($event['redirect']) {
- $redirect = $event['redirect'];
- $redirect_code = $event['redirect_code'];
- }
- if ($event->isPropagationStopped()) {
- break;
- }
- }
- }
- if ($legacyUploads) {
- $this->copyFiles();
- }
- $this->getFlash()->delete();
- if ($redirect) {
- $grav->redirect($redirect, $redirect_code);
- }
- }
- /**
- * @return string
- * @deprecated 3.0 Use $form->getName() instead
- */
- public function name(): string
- {
- return $this->getName();
- }
- /**
- * @return array
- * @deprecated 3.0 Use $form->getFields() instead
- */
- public function fields(): array
- {
- return $this->getFields();
- }
- /**
- * @return PageInterface
- * @deprecated 3.0 Use $form->getPage() instead
- */
- public function page(): PageInterface
- {
- return $this->getPage();
- }
- /**
- * Backwards compatibility
- *
- * @deprecated 3.0 Calling $form->filter() is not needed anymore (does nothing)
- */
- public function filter(): void
- {
- }
- /**
- * Store form uploads to the final location.
- */
- public function copyFiles()
- {
- // Get flash object in order to save the files.
- $flash = $this->getFlash();
- $fields = $flash->getFilesByFields();
- foreach ($fields as $key => $uploads) {
- /** @var FormFlashFile $upload */
- foreach ($uploads as $upload) {
- if (null === $upload || $upload->isMoved()) {
- continue;
- }
- $destination = $upload->getDestination();
- $filesystem = Filesystem::getInstance();
- $folder = $filesystem->dirname($destination);
- if (!is_dir($folder) && !@mkdir($folder, 0777, true) && !is_dir($folder)) {
- $grav = Grav::instance();
- throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $upload->getClientFilename() . '"', $destination));
- }
- try {
- $upload->moveTo($destination);
- } catch (\RuntimeException $e) {
- $grav = Grav::instance();
- throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $upload->getClientFilename() . '"', $destination));
- }
- }
- }
- $flash->clearFiles();
- }
- public function legacyUploads()
- {
- // Get flash object in order to save the files.
- $flash = $this->getFlash();
- $queue = $verify = $flash->getLegacyFiles();
- if (!$queue) {
- return;
- }
- $grav = Grav::instance();
- /** @var Uri $uri */
- $uri = $grav['uri'];
- // Get POST data and decode JSON fields into arrays
- $post = $uri->post();
- $post['data'] = $this->decodeData($post['data'] ?? []);
- // Allow plugins to implement additional / alternative logic
- $grav->fireEvent('onFormStoreUploads', new Event(['form' => $this, 'queue' => &$queue, 'post' => $post]));
- $modified = $queue !== $verify;
- if (!$modified) {
- // Fill file fields just like before.
- foreach ($queue as $key => $files) {
- foreach ($files as $destination => $file) {
- unset($files[$destination]['tmp_name']);
- }
- $this->setImageField($key, $files);
- }
- } else {
- user_error('Event onFormStoreUploads is deprecated.', E_USER_DEPRECATED);
- if (\is_array($queue)) {
- foreach ($queue as $key => $files) {
- foreach ($files as $destination => $file) {
- $filesystem = Filesystem::getInstance();
- $folder = $filesystem->dirname($destination);
- if (!is_dir($folder) && !@mkdir($folder, 0777, true) && !is_dir($folder)) {
- $grav = Grav::instance();
- throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
- }
- if (!rename($file['tmp_name'], $destination)) {
- $grav = Grav::instance();
- throw new \RuntimeException(sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_MOVE', null, true), '"' . $file['tmp_name'] . '"', $destination));
- }
- if (file_exists($file['tmp_name'] . '.yaml')) {
- unlink($file['tmp_name'] . '.yaml');
- }
- unset($files[$destination]['tmp_name']);
- }
- $this->setImageField($key, $files);
- }
- }
- $flash->clearFiles();
- }
- }
- public function getPagePathFromToken($path)
- {
- return Utils::getPagePathFromToken($path, $this->getPage());
- }
- /**
- * @return Route|null
- */
- public function getFileUploadAjaxRoute(): ?Route
- {
- $route = Uri::getCurrentRoute()->withExtension('json')->withGravParam('task', 'file-upload');
- return $route;
- }
- /**
- * @param $field
- * @param $filename
- * @return Route|null
- */
- public function getFileDeleteAjaxRoute($field, $filename): ?Route
- {
- $route = Uri::getCurrentRoute()->withExtension('json')->withGravParam('task', 'file-remove');
- return $route;
- }
- public function responseCode($code = null)
- {
- if ($code) {
- $this->response_code = $code;
- }
- return $this->response_code;
- }
- public function doSerialize()
- {
- return $this->doTraitSerialize() + [
- 'items' => $this->items,
- 'message' => $this->message,
- 'status' => $this->status,
- 'header_data' => $this->header_data,
- 'rules' => $this->rules,
- 'values' => $this->values->toArray(),
- 'page' => $this->page
- ];
- }
- public function doUnserialize(array $data)
- {
- $this->items = $data['items'];
- $this->message = $data['message'];
- $this->status = $data['status'];
- $this->header_data = $data['header_data'];
- $this->rules = $data['rules'];
- $this->values = new Data($data['values']);
- $this->page = $data['page'];
- // Backwards compatibility.
- $defaults = [
- 'name' => $this->items['name'],
- 'id' => $this->items['id'],
- 'uniqueid' => $this->items['uniqueid'] ?? null,
- 'data' => []
- ];
- $this->doTraitUnserialize($data + $defaults);
- }
- /**
- * Get the configured max file size in bytes
- *
- * @param bool $mbytes return size in MB
- * @return int
- */
- public static function getMaxFilesize($mbytes = false)
- {
- $config = Grav::instance()['config'];
- $system_filesize = 0;
- $form_filesize = $config->get('plugins.form.files.filesize', 0);
- $upload_limit = (int) Utils::getUploadLimit();
- if ($upload_limit > 0) {
- $system_filesize = intval($upload_limit / static::BYTES_TO_MB);
- }
- if ($form_filesize > $system_filesize || $form_filesize == 0) {
- $form_filesize = $system_filesize;
- }
- if ($mbytes) {
- return $form_filesize * static::BYTES_TO_MB;
- }
- return $form_filesize;
- }
- protected function sendJsonResponse(callable $callable)
- {
- $grav = Grav::instance();
- /** @var Uri $uri */
- $uri = $grav['uri'];
- // Get POST data and decode JSON fields into arrays
- $post = $uri->post();
- $post['data'] = $this->decodeData($post['data'] ?? []);
- if (empty($post['form-nonce']) || !Utils::verifyNonce($post['form-nonce'], 'form')) {
- throw new \RuntimeException('Bad Request: Nonce is missing or invalid', 400);
- }
- $this->values = new Data($post);
- $json_response = $callable($post);
- // Return JSON
- header('Content-Type: application/json');
- echo json_encode($json_response);
- exit;
- }
- /**
- * Remove uploaded file from flash object.
- *
- * @param string $filename
- * @param string|null $field
- */
- protected function removeFlashUpload(string $filename, string $field = null)
- {
- $flash = $this->getFlash();
- $flash->removeFile($filename, $field);
- $flash->save();
- }
- /**
- * Store updated data into flash object.
- *
- * @param array $data
- */
- protected function updateFlashData(array $data)
- {
- // Store updated data into flash.
- $flash = $this->getFlash();
- // Check special case where there are no changes made to the form.
- if (!$flash->exists() && $data === $this->header_data) {
- return;
- }
- $this->setAllData($flash->getData() ?? []);
- $this->data->merge($data);
- $flash->setData($this->data->toArray());
- $flash->save();
- }
- protected function doSubmit(array $data, array $files)
- {
- return;
- }
- protected function processFields($fields)
- {
- $types = Grav::instance()['plugins']->formFieldTypes;
- $return = [];
- foreach ($fields as $key => $value) {
- // Default to text if not set
- if (!isset($value['type'])) {
- $value['type'] = 'text';
- }
- // Manually merging the field types
- if ($types !== null && array_key_exists($value['type'], $types)) {
- $value += $types[$value['type']];
- }
- // Fix numeric indexes
- if (is_numeric($key) && isset($value['name'])) {
- $key = $value['name'];
- }
- // Recursively process children
- if (isset($value['fields']) && \is_array($value['fields'])) {
- $value['fields'] = $this->processFields($value['fields']);
- }
- $return[$key] = $value;
- }
- return $return;
- }
- protected function setImageField($key, $files)
- {
- $field = $this->data->blueprints()->schema()->get($key);
- if (isset($field['type']) && !empty($field['array'])) {
- $this->data->set($key, $files);
- }
- }
- /**
- * Decode data
- *
- * @param array $data
- * @return array
- */
- protected function decodeData($data)
- {
- if (!\is_array($data)) {
- return [];
- }
- // Decode JSON encoded fields and merge them to data.
- if (isset($data['_json'])) {
- $data = array_replace_recursive($data, $this->jsonDecode($data['_json']));
- unset($data['_json']);
- }
- $data = $this->cleanDataKeys($data);
- return $data;
- }
- /**
- * Decode [] in the data keys
- *
- * @param array $source
- * @return array
- */
- protected function cleanDataKeys($source = [])
- {
- $out = [];
- if (\is_array($source)) {
- foreach ($source as $key => $value) {
- $key = str_replace(['%5B', '%5D'], ['[', ']'], $key);
- if (\is_array($value)) {
- $out[$key] = $this->cleanDataKeys($value);
- } else {
- $out[$key] = $value;
- }
- }
- }
- return $out;
- }
- /**
- * Internal method to normalize the $_FILES array
- *
- * @param array $data $_FILES starting point data
- * @param string $key
- * @return object a new Object with a normalized list of files
- */
- protected function normalizeFiles($data, $key = '')
- {
- $files = new \stdClass();
- $files->field = $key;
- $files->file = new \stdClass();
- foreach ($data as $fieldName => $fieldValue) {
- // Since Files Upload are always happening via Ajax
- // we are not interested in handling `multiple="true"`
- // because they are always handled one at a time.
- // For this reason we normalize the value to string,
- // in case it is arriving as an array.
- $value = (array) Utils::getDotNotation($fieldValue, $key);
- $files->file->{$fieldName} = array_shift($value);
- }
- return $files;
- }
- }
|