1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.1.2
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\View\Helper;
16:
17: use Cake\Utility\Security;
18:
19: /**
20: * Provides methods for building token data that is
21: * compatible with SecurityComponent.
22: */
23: trait SecureFieldTokenTrait
24: {
25: /**
26: * Generate the token data for the provided inputs.
27: *
28: * @param string $url The URL the form is being submitted to.
29: * @param array $fields If set specifies the list of fields to use when
30: * generating the hash.
31: * @param array $unlockedFields The list of fields that are excluded from
32: * field validation.
33: * @return array The token data.
34: */
35: protected function _buildFieldToken($url, $fields, $unlockedFields = [])
36: {
37: $locked = [];
38: foreach ($fields as $key => $value) {
39: if (is_numeric($value)) {
40: $value = (string)$value;
41: }
42: if (!is_int($key)) {
43: $locked[$key] = $value;
44: unset($fields[$key]);
45: }
46: }
47:
48: sort($unlockedFields, SORT_STRING);
49: sort($fields, SORT_STRING);
50: ksort($locked, SORT_STRING);
51: $fields += $locked;
52:
53: $locked = implode(array_keys($locked), '|');
54: $unlocked = implode($unlockedFields, '|');
55: $hashParts = [
56: $url,
57: serialize($fields),
58: $unlocked,
59: session_id(),
60: ];
61: $fields = hash_hmac('sha1', implode('', $hashParts), Security::getSalt());
62:
63: return [
64: 'fields' => urlencode($fields . ':' . $locked),
65: 'unlocked' => urlencode($unlocked),
66: ];
67: }
68: }
69: