3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 public static $_key = NULL;
22 public static $_sessionID = NULL;
25 * Generate a private key per session and store in session.
28 * private key for this session
30 public static function privateKey() {
32 $session = CRM_Core_Session
::singleton();
33 self
::$_key = $session->get('qfPrivateKey');
35 self
::$_key = md5(uniqid(mt_rand(), TRUE)) . md5(uniqid(mt_rand(), TRUE));
36 $session->set('qfPrivateKey', self
::$_key);
43 * @return mixed|null|string
45 public static function sessionID() {
46 if (!self
::$_sessionID) {
47 $session = CRM_Core_Session
::singleton();
48 self
::$_sessionID = $session->get('qfSessionID');
49 if (!self
::$_sessionID) {
50 self
::$_sessionID = session_id();
51 $session->set('qfSessionID', self
::$_sessionID);
54 return self
::$_sessionID;
58 * Generate a form key based on form name, the current user session
59 * and a private key. Modelled after drupal's form API
62 * @param bool $addSequence
63 * Should we add a unique sequence number to the end of the key.
68 public static function get($name, $addSequence = FALSE) {
69 $privateKey = self
::privateKey();
70 $sessionID = self
::sessionID();
71 $key = md5($sessionID . $name . $privateKey);
74 // now generate a random number between 1 and 100K and add it to the key
75 // so that we can have forms in mutiple tabs etc
76 $key = $key . '_' . mt_rand(1, 10000);
82 * Validate a form key based on the form name.
86 * @param bool $addSequence
91 public static function validate($key, $name, $addSequence = FALSE) {
92 if (!is_string($key)) {
97 list($k, $t) = explode('_', $key);
98 if ($t < 1 ||
$t > 10000) {
106 $privateKey = self
::privateKey();
107 $sessionID = self
::sessionID();
108 if ($k != md5($sessionID . $name . $privateKey)) {
119 public static function valid($key) {
120 // a valid key is a 32 digit hex number
121 // followed by an optional _ and a number between 1 and 10000
122 if (strpos('_', $key) !== FALSE) {
123 list($hash, $seq) = explode('_', $key);
125 // ensure seq is between 1 and 10000
126 if (!is_numeric($seq) ||
137 // ensure that hash is a 32 digit hex number
138 return preg_match('#[0-9a-f]{32}#i', $hash) ?
TRUE : FALSE;