BlueprintSchema.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. /**
  3. * @package Grav\Common\Data
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 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. $ignore = (bool) array_filter((array)($rules['validate']['ignore'] ?? [])) ?? false;
  117. if (!str_starts_with($type, '_') && !str_contains($key, '*') && $ignore !== true) {
  118. $list[$prefix . $key] = null;
  119. }
  120. }
  121. }
  122. $nested = $this->getNestedRules($name);
  123. return array_replace($list, $this->flattenArray($data, $nested, $prefix));
  124. }
  125. /**
  126. * @param array $data
  127. * @param array $rules
  128. * @param string $prefix
  129. * @return array
  130. */
  131. protected function flattenArray(array $data, array $rules, string $prefix)
  132. {
  133. $array = [];
  134. foreach ($data as $key => $field) {
  135. $val = $rules[$key] ?? $rules['*'] ?? null;
  136. $rule = is_string($val) ? $this->items[$val] : null;
  137. if ($rule || isset($val['*'])) {
  138. // Item has been defined in blueprints.
  139. $array[$prefix.$key] = $field;
  140. } elseif (is_array($field) && is_array($val)) {
  141. // Array has been defined in blueprints.
  142. $array += $this->flattenArray($field, $val, $prefix . $key . '.');
  143. } else {
  144. // Undefined/extra item.
  145. $array[$prefix.$key] = $field;
  146. }
  147. }
  148. return $array;
  149. }
  150. /**
  151. * @param array $data
  152. * @param array $rules
  153. * @param bool $strict
  154. * @param bool $xss
  155. * @return array
  156. * @throws RuntimeException
  157. */
  158. protected function validateArray(array $data, array $rules, bool $strict, bool $xss = true)
  159. {
  160. $messages = $this->checkRequired($data, $rules);
  161. foreach ($data as $key => $child) {
  162. $val = $rules[$key] ?? $rules['*'] ?? null;
  163. $rule = is_string($val) ? $this->items[$val] : null;
  164. $checkXss = $xss;
  165. if ($rule) {
  166. // Item has been defined in blueprints.
  167. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  168. // Skip validation in the ignored field.
  169. continue;
  170. }
  171. $messages += Validation::validate($child, $rule);
  172. } elseif (is_array($child) && is_array($val)) {
  173. // Array has been defined in blueprints.
  174. $messages += $this->validateArray($child, $val, $strict);
  175. $checkXss = false;
  176. } elseif ($strict) {
  177. // Undefined/extra item in strict mode.
  178. /** @var Config $config */
  179. $config = Grav::instance()['config'];
  180. if (!$config->get('system.strict_mode.blueprint_strict_compat', true)) {
  181. throw new RuntimeException(sprintf('%s is not defined in blueprints', $key), 400);
  182. }
  183. user_error(sprintf('Having extra key %s in your data is deprecated with blueprint having \'validation: strict\'', $key), E_USER_DEPRECATED);
  184. }
  185. if ($checkXss) {
  186. $messages += Validation::checkSafety($child, $rule ?: ['name' => $key]);
  187. }
  188. }
  189. return $messages;
  190. }
  191. /**
  192. * @param array $data
  193. * @param array $rules
  194. * @param string $parent
  195. * @param bool $missingValuesAsNull
  196. * @param bool $keepEmptyValues
  197. * @return array|null
  198. */
  199. protected function filterArray(array $data, array $rules, string $parent, bool $missingValuesAsNull, bool $keepEmptyValues)
  200. {
  201. $results = [];
  202. foreach ($data as $key => $field) {
  203. $val = $rules[$key] ?? $rules['*'] ?? null;
  204. $rule = is_string($val) ? $this->items[$val] : $this->items[$parent . $key] ?? null;
  205. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  206. // Skip any data in the ignored field.
  207. unset($results[$key]);
  208. continue;
  209. }
  210. if (null === $field) {
  211. if ($missingValuesAsNull) {
  212. $results[$key] = null;
  213. } else {
  214. unset($results[$key]);
  215. }
  216. continue;
  217. }
  218. $isParent = isset($val['*']);
  219. $type = $rule['type'] ?? null;
  220. if (!$isParent && $type && $type !== '_parent') {
  221. $field = Validation::filter($field, $rule);
  222. } elseif (is_array($field) && is_array($val)) {
  223. // Array has been defined in blueprints.
  224. $k = $isParent ? '*' : $key;
  225. $field = $this->filterArray($field, $val, $parent . $k . '.', $missingValuesAsNull, $keepEmptyValues);
  226. if (null === $field) {
  227. // Nested parent has no values.
  228. unset($results[$key]);
  229. continue;
  230. }
  231. } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
  232. // Skip any extra data.
  233. continue;
  234. }
  235. if ($keepEmptyValues || (null !== $field && (!is_array($field) || !empty($field)))) {
  236. $results[$key] = $field;
  237. }
  238. }
  239. return $results ?: null;
  240. }
  241. /**
  242. * @param array $nested
  243. * @param string $parent
  244. * @return bool
  245. */
  246. protected function buildIgnoreNested(array $nested, $parent = '')
  247. {
  248. $ignore = true;
  249. foreach ($nested as $key => $val) {
  250. $key = $parent . $key;
  251. if (is_array($val)) {
  252. $ignore = $this->buildIgnoreNested($val, $key . '.') && $ignore; // Keep the order!
  253. } else {
  254. $child = $this->items[$key] ?? null;
  255. $ignore = $ignore && (!$child || !empty($child['disabled']) || !empty($child['validate']['ignore']));
  256. }
  257. }
  258. if ($ignore) {
  259. $key = trim($parent, '.');
  260. $this->items[$key]['validate']['ignore'] = true;
  261. }
  262. return $ignore;
  263. }
  264. /**
  265. * @param array|null $data
  266. * @param array $toggles
  267. * @param array $nested
  268. * @return array|null
  269. */
  270. protected function processFormRecursive(?array $data, array $toggles, array $nested)
  271. {
  272. foreach ($nested as $key => $value) {
  273. if ($key === '') {
  274. continue;
  275. }
  276. if ($key === '*') {
  277. // TODO: Add support to collections.
  278. continue;
  279. }
  280. if (is_array($value)) {
  281. // Special toggle handling for all the nested data.
  282. $toggle = $toggles[$key] ?? [];
  283. if (!is_array($toggle)) {
  284. if (!$toggle) {
  285. $data[$key] = null;
  286. continue;
  287. }
  288. $toggle = [];
  289. }
  290. // Recursively fetch the items.
  291. $childData = $data[$key] ?? null;
  292. if (null !== $childData && !is_array($childData)) {
  293. throw new \RuntimeException(sprintf("Bad form data for field collection '%s': %s used instead of an array", $key, gettype($childData)));
  294. }
  295. $data[$key] = $this->processFormRecursive($data[$key] ?? null, $toggle, $value);
  296. } else {
  297. $field = $this->get($value);
  298. // Do not add the field if:
  299. if (
  300. // Not an input field
  301. !$field
  302. // Field has been disabled
  303. || !empty($field['disabled'])
  304. // Field validation is set to be ignored
  305. || !empty($field['validate']['ignore'])
  306. // Field is overridable and the toggle is turned off
  307. || (!empty($field['overridable']) && empty($toggles[$key]))
  308. ) {
  309. continue;
  310. }
  311. if (!isset($data[$key])) {
  312. $data[$key] = null;
  313. }
  314. }
  315. }
  316. return $data;
  317. }
  318. /**
  319. * @param array $data
  320. * @param array $fields
  321. * @return array
  322. */
  323. protected function checkRequired(array $data, array $fields)
  324. {
  325. $messages = [];
  326. foreach ($fields as $name => $field) {
  327. if (!is_string($field)) {
  328. continue;
  329. }
  330. $field = $this->items[$field];
  331. // Skip ignored field, it will not be required.
  332. if (!empty($field['disabled']) || !empty($field['validate']['ignore'])) {
  333. continue;
  334. }
  335. // Skip overridable fields without value.
  336. // TODO: We need better overridable support, which is not just ignoring required values but also looking if defaults are good.
  337. if (!empty($field['overridable']) && !isset($data[$name])) {
  338. continue;
  339. }
  340. // Check if required.
  341. if (isset($field['validate']['required'])
  342. && $field['validate']['required'] === true) {
  343. if (isset($data[$name])) {
  344. continue;
  345. }
  346. if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
  347. continue;
  348. }
  349. $value = $field['label'] ?? $field['name'];
  350. $language = Grav::instance()['language'];
  351. $message = sprintf($language->translate('GRAV.FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value));
  352. $messages[$field['name']][] = $message;
  353. }
  354. }
  355. return $messages;
  356. }
  357. /**
  358. * @param array $field
  359. * @param string $property
  360. * @param array $call
  361. * @return void
  362. */
  363. protected function dynamicConfig(array &$field, $property, array &$call)
  364. {
  365. $value = $call['params'];
  366. $default = $field[$property] ?? null;
  367. $config = Grav::instance()['config']->get($value, $default);
  368. if (null !== $config) {
  369. $field[$property] = $config;
  370. }
  371. }
  372. }