1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273 |
- <?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\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-read 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->modular()) {
- $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->upload_errors[$upload['file']['error']])
- ];
- }
- // 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;
- // 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;
- }
- /**
- * 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 $this->getName() instead
- */
- public function name(): string
- {
- return $this->getName();
- }
- /**
- * @return array
- * @deprecated 3.0 Use $this->getFields() instead
- */
- public function fields(): array
- {
- return $this->getFields();
- }
- /**
- * @return PageInterface
- * @deprecated 3.0 Use $this->getPage() instead
- */
- public function page(): PageInterface
- {
- return $this->getPage();
- }
- /**
- * Backwards compatibility
- *
- * @deprecated 3.0
- */
- 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->page());
- }
- /**
- * @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;
- }
- }
|