BlueprintSchema.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. /**
  3. * @package Grav\Common\Data
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Data;
  9. use Grav\Common\Config\Config;
  10. use Grav\Common\Grav;
  11. use RocketTheme\Toolbox\ArrayTraits\Export;
  12. use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
  13. use RocketTheme\Toolbox\Blueprints\BlueprintSchema as BlueprintSchemaBase;
  14. use RuntimeException;
  15. use function is_array;
  16. use function is_string;
  17. /**
  18. * Class BlueprintSchema
  19. * @package Grav\Common\Data
  20. */
  21. class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
  22. {
  23. use Export;
  24. /** @var array */
  25. protected $filter = ['validation' => true, 'xss_check' => true];
  26. /** @var array */
  27. protected $ignoreFormKeys = [
  28. 'title' => true,
  29. 'help' => true,
  30. 'placeholder' => true,
  31. 'placeholder_key' => true,
  32. 'placeholder_value' => true,
  33. 'fields' => true
  34. ];
  35. /**
  36. * @return array
  37. */
  38. public function getTypes()
  39. {
  40. return $this->types;
  41. }
  42. /**
  43. * @param string $name
  44. * @return array
  45. */
  46. public function getType($name)
  47. {
  48. return $this->types[$name] ?? [];
  49. }
  50. /**
  51. * @param string $name
  52. * @return array|null
  53. */
  54. public function getNestedRules(string $name)
  55. {
  56. return $this->getNested($name);
  57. }
  58. /**
  59. * Validate data against blueprints.
  60. *
  61. * @param array $data
  62. * @param array $options
  63. * @return void
  64. * @throws RuntimeException
  65. */
  66. public function validate(array $data, array $options = [])
  67. {
  68. try {
  69. $validation = $this->items['']['form']['validation'] ?? 'loose';
  70. $messages = $this->validateArray($data, $this->nested, $validation === 'strict', $options['xss_check'] ?? true);
  71. } catch (RuntimeException $e) {
  72. throw (new ValidationException($e->getMessage(), $e->getCode(), $e))->setMessages();
  73. }
  74. if (!empty($messages)) {
  75. throw (new ValidationException('', 400))->setMessages($messages);
  76. }
  77. }
  78. /**
  79. * @param array $data
  80. * @param array $toggles
  81. * @return array
  82. */
  83. public function processForm(array $data, array $toggles = [])
  84. {
  85. return $this->processFormRecursive($data, $toggles, $this->nested) ?? [];
  86. }
  87. /**
  88. * Filter data by using blueprints.
  89. *
  90. * @param array $data Incoming data, for example from a form.
  91. * @param bool $missingValuesAsNull Include missing values as nulls.
  92. * @param bool $keepEmptyValues Include empty values.
  93. * @return array
  94. */
  95. public function filter(array $data, $missingValuesAsNull = false, $keepEmptyValues = false)
  96. {
  97. $this->buildIgnoreNested($this->nested);
  98. return $this->filterArray($data, $this->nested, '', $missingValuesAsNull, $keepEmptyValues) ?? [];
  99. }
  100. /**
  101. * Flatten data by using blueprints.
  102. *
  103. * @param array $data Data to be flattened.
  104. * @param bool $includeAll True if undefined properties should also be included.
  105. * @param string $name Property which will be flattened, useful for flattening repeating data.
  106. * @return array
  107. */
  108. public function flattenData(array $data, bool $includeAll = false, string $name = '')
  109. {
  110. $prefix = $name !== '' ? $name . '.' : '';
  111. $list = [];
  112. if ($includeAll) {
  113. $items = $name !== '' ? $this->getProperty($name)['fields'] ?? [] : $this->items;
  114. foreach ($items as $key => $rules) {
  115. $type = $rules['type'] ?? '';
  116. if (!str_starts_with($type, '_') && !str_contains($key, '*')) {
  117. $list[$prefix . $key] = null;
  118. }
  119. }
  120. }
  121. $nested = $this->getNestedRules($name);
  122. return array_replace($list, $this->flattenArray($data, $nested, $prefix));
  123. }
  124. /**
  125. * @param array $data
  126. * @param array $rules
  127. * @param string $prefix
  128. * @return array
  129. */
  130. protected function flattenArray(array $data, array $rules, string $prefix)
  131. {
  132. $array = [];
  133. foreach ($data as $key => $field) {
  134. $val = $rules[$key] ?? $rules['*'] ?? null;
  135. $rule = is_string($val) ? $this->items[$val] : null;
  136. if ($rule || isset($val['*'])) {
  137. // Item has been defined in blueprints.
  138. $array[$prefix.$key] = $field;
  139. } elseif (is_array($field) && is_array($val)) {
  140. // Array has been defined in blueprints.
  141. $array += $this->flattenArray($field, $val, $prefix . $key . '.');
  142. } else {
  143. // Undefined/extra item.
  144. $array[$prefix.$key] = $field;
  145. }
  146. }
  147. return $array;
  148. }
  149. /**
  150. * @param array $data
  151. * @param array $rules
  152. * @param bool $strict
  153. * @param bool $xss
  154. * @return array
  155. * @throws RuntimeException
  156. */
  157. protected function validateArray(array $data, array $rules, bool $strict, bool $xss = true)
  158. {
  159. $messages = $this->checkRequired($data, $rules);
  160. foreach ($data as $key => $child) {
  161. $val = $rules[$key] ?? $rules['*'] ?? null;
  162. $rule = is_string($val) ? $this->items[$val] : null;
  163. $checkXss = $xss;
  164. if ($rule) {
  165. // Item has been defined in blueprints.
  166. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  167. // Skip validation in the ignored field.
  168. continue;
  169. }
  170. $messages += Validation::validate($child, $rule);
  171. } elseif (is_array($child) && is_array($val)) {
  172. // Array has been defined in blueprints.
  173. $messages += $this->validateArray($child, $val, $strict);
  174. $checkXss = false;
  175. } elseif ($strict) {
  176. // Undefined/extra item in strict mode.
  177. /** @var Config $config */
  178. $config = Grav::instance()['config'];
  179. if (!$config->get('system.strict_mode.blueprint_strict_compat', true)) {
  180. throw new RuntimeException(sprintf('%s is not defined in blueprints', $key), 400);
  181. }
  182. user_error(sprintf('Having extra key %s in your data is deprecated with blueprint having \'validation: strict\'', $key), E_USER_DEPRECATED);
  183. }
  184. if ($checkXss) {
  185. $messages += Validation::checkSafety($child, $rule ?: ['name' => $key]);
  186. }
  187. }
  188. return $messages;
  189. }
  190. /**
  191. * @param array $data
  192. * @param array $rules
  193. * @param string $parent
  194. * @param bool $missingValuesAsNull
  195. * @param bool $keepEmptyValues
  196. * @return array|null
  197. */
  198. protected function filterArray(array $data, array $rules, string $parent, bool $missingValuesAsNull, bool $keepEmptyValues)
  199. {
  200. $results = [];
  201. foreach ($data as $key => $field) {
  202. $val = $rules[$key] ?? $rules['*'] ?? null;
  203. $rule = is_string($val) ? $this->items[$val] : $this->items[$parent . $key] ?? null;
  204. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  205. // Skip any data in the ignored field.
  206. unset($results[$key]);
  207. continue;
  208. }
  209. if (null === $field) {
  210. if ($missingValuesAsNull) {
  211. $results[$key] = null;
  212. } else {
  213. unset($results[$key]);
  214. }
  215. continue;
  216. }
  217. $isParent = isset($val['*']);
  218. $type = $rule['type'] ?? null;
  219. if (!$isParent && $type && $type !== '_parent') {
  220. $field = Validation::filter($field, $rule);
  221. } elseif (is_array($field) && is_array($val)) {
  222. // Array has been defined in blueprints.
  223. $k = $isParent ? '*' : $key;
  224. $field = $this->filterArray($field, $val, $parent . $k . '.', $missingValuesAsNull, $keepEmptyValues);
  225. if (null === $field) {
  226. // Nested parent has no values.
  227. unset($results[$key]);
  228. continue;
  229. }
  230. } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
  231. // Skip any extra data.
  232. continue;
  233. }
  234. if ($keepEmptyValues || (null !== $field && (!is_array($field) || !empty($field)))) {
  235. $results[$key] = $field;
  236. }
  237. }
  238. return $results ?: null;
  239. }
  240. /**
  241. * @param array $nested
  242. * @param string $parent
  243. * @return bool
  244. */
  245. protected function buildIgnoreNested(array $nested, $parent = '')
  246. {
  247. $ignore = true;
  248. foreach ($nested as $key => $val) {
  249. $key = $parent . $key;
  250. if (is_array($val)) {
  251. $ignore = $this->buildIgnoreNested($val, $key . '.') && $ignore; // Keep the order!
  252. } else {
  253. $child = $this->items[$key] ?? null;
  254. $ignore = $ignore && (!$child || !empty($child['disabled']) || !empty($child['validate']['ignore']));
  255. }
  256. }
  257. if ($ignore) {
  258. $key = trim($parent, '.');
  259. $this->items[$key]['validate']['ignore'] = true;
  260. }
  261. return $ignore;
  262. }
  263. /**
  264. * @param array|null $data
  265. * @param array $toggles
  266. * @param array $nested
  267. * @return array|null
  268. */
  269. protected function processFormRecursive(?array $data, array $toggles, array $nested)
  270. {
  271. foreach ($nested as $key => $value) {
  272. if ($key === '') {
  273. continue;
  274. }
  275. if ($key === '*') {
  276. // TODO: Add support to collections.
  277. continue;
  278. }
  279. if (is_array($value)) {
  280. // Special toggle handling for all the nested data.
  281. $toggle = $toggles[$key] ?? [];
  282. if (!is_array($toggle)) {
  283. if (!$toggle) {
  284. $data[$key] = null;
  285. continue;
  286. }
  287. $toggle = [];
  288. }
  289. // Recursively fetch the items.
  290. $childData = $data[$key] ?? null;
  291. if (null !== $childData && !is_array($childData)) {
  292. throw new \RuntimeException(sprintf("Bad form data for field collection '%s': %s used instead of an array", $key, gettype($childData)));
  293. }
  294. $data[$key] = $this->processFormRecursive($data[$key] ?? null, $toggle, $value);
  295. } else {
  296. $field = $this->get($value);
  297. // Do not add the field if:
  298. if (
  299. // Not an input field
  300. !$field
  301. // Field has been disabled
  302. || !empty($field['disabled'])
  303. // Field validation is set to be ignored
  304. || !empty($field['validate']['ignore'])
  305. // Field is overridable and the toggle is turned off
  306. || (!empty($field['overridable']) && empty($toggles[$key]))
  307. ) {
  308. continue;
  309. }
  310. if (!isset($data[$key])) {
  311. $data[$key] = null;
  312. }
  313. }
  314. }
  315. return $data;
  316. }
  317. /**
  318. * @param array $data
  319. * @param array $fields
  320. * @return array
  321. */
  322. protected function checkRequired(array $data, array $fields)
  323. {
  324. $messages = [];
  325. foreach ($fields as $name => $field) {
  326. if (!is_string($field)) {
  327. continue;
  328. }
  329. $field = $this->items[$field];
  330. // Skip ignored field, it will not be required.
  331. if (!empty($field['disabled']) || !empty($field['validate']['ignore'])) {
  332. continue;
  333. }
  334. // Skip overridable fields without value.
  335. // TODO: We need better overridable support, which is not just ignoring required values but also looking if defaults are good.
  336. if (!empty($field['overridable']) && !isset($data[$name])) {
  337. continue;
  338. }
  339. // Check if required.
  340. if (isset($field['validate']['required'])
  341. && $field['validate']['required'] === true) {
  342. if (isset($data[$name])) {
  343. continue;
  344. }
  345. if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
  346. continue;
  347. }
  348. $value = $field['label'] ?? $field['name'];
  349. $language = Grav::instance()['language'];
  350. $message = sprintf($language->translate('GRAV.FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value));
  351. $messages[$field['name']][] = $message;
  352. }
  353. }
  354. return $messages;
  355. }
  356. /**
  357. * @param array $field
  358. * @param string $property
  359. * @param array $call
  360. * @return void
  361. */
  362. protected function dynamicConfig(array &$field, $property, array &$call)
  363. {
  364. $value = $call['params'];
  365. $default = $field[$property] ?? null;
  366. $config = Grav::instance()['config']->get($value, $default);
  367. if (null !== $config) {
  368. $field[$property] = $config;
  369. }
  370. }
  371. }