CodeKey.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. <?php
  2. /**
  3. * TODO: rename to "Token" with display field "token"
  4. *
  5. * @author Mark Scherer
  6. * @cakephp 2.0
  7. * @license MIT
  8. * 2011-11-17 ms
  9. */
  10. class CodeKey extends ToolsAppModel {
  11. public $displayField = 'key';
  12. public $order = array('CodeKey.created' => 'DESC');
  13. protected $defaultLength = 22;
  14. protected $validity = MONTH;
  15. public $validate = array(
  16. 'type' => array(
  17. 'notEmpty' => array(
  18. 'rule' => array('notEmpty'),
  19. 'message' => 'valErrMandatoryField',
  20. ),
  21. ),
  22. 'key' => array(
  23. 'notEmpty' => array(
  24. 'rule' => array('notEmpty'),
  25. 'message' => 'valErrMandatoryField',
  26. 'last' => true,
  27. ),
  28. 'isUnique' => array(
  29. 'rule' => array('isUnique'),
  30. 'message' => 'valErrCodeKeyExists',
  31. ),
  32. ),
  33. 'content' => array(
  34. 'maxLength' => array(
  35. 'rule' => array('maxLength', 255),
  36. 'message' => array('valErrMaxCharacters %s', 255),
  37. 'allowEmpty' => true
  38. ),
  39. ),
  40. 'used' => array('numeric')
  41. );
  42. //public $types = array('activate');
  43. /**
  44. * stores new key in DB
  45. * @param string type: neccessary
  46. * @param string key: optional key, otherwise a key will be generated
  47. * @param mixed user_id: optional (if used, only this user can use this key)
  48. * @param string content: up to 255 characters of content may be added (optional)
  49. * NOW: checks if this key is already used (should be unique in table)
  50. * @return string key on SUCCESS, boolean false otherwise
  51. * 2009-05-13 ms
  52. */
  53. public function newKey($type, $key = null, $uid = null, $content = null) {
  54. if (empty($type)) { // || !in_array($type,$this->types)
  55. return false;
  56. }
  57. if (empty($key)) {
  58. $key = $this->generateKey($this->defaultLength);
  59. $keyLength = $this->defaultLength;
  60. } else {
  61. $keyLength = mb_strlen($key);
  62. }
  63. $data = array(
  64. 'type' => $type,
  65. 'user_id' => (string)$uid,
  66. 'content' => (string)$content,
  67. 'key' => $key,
  68. );
  69. $this->set($data);
  70. $max = 99;
  71. while (!$this->validates()) {
  72. $data['key'] = $this->generateKey($keyLength);
  73. $this->set($data);
  74. $max--;
  75. if ($max == 0) { //die('Exeption in CodeKey');
  76. return false;
  77. }
  78. }
  79. $this->create();
  80. if ($this->save($data)) {
  81. return $key;
  82. }
  83. return false;
  84. }
  85. /**
  86. * usesKey (only once!) - by KEY
  87. * @param string type: neccessary
  88. * @param string key: neccessary
  89. * @param mixed user_id: needs to be provided if this key has a user_id stored
  90. * @return ARRAY(content) if successfully used or if already used (used=1), FALSE else
  91. * 2009-05-13 ms
  92. */
  93. public function useKey($type, $key, $uid = null, $treatUsedAsInvalid = false) {
  94. if (empty($type) || empty($key)) {
  95. return false;
  96. }
  97. $conditions = array('conditions'=>array($this->alias.'.key'=>$key,$this->alias.'.type'=>$type));
  98. if (!empty($uid)) {
  99. $conditions['conditions'][$this->alias.'.user_id'] = $uid;
  100. }
  101. $res = $this->find('first', $conditions);
  102. if (empty($res)) {
  103. return false;
  104. }
  105. if (!empty($uid) && !empty($res[$this->alias]['user_id']) && $res[$this->alias]['user_id'] != $uid) {
  106. // return $res; # more secure to fail here if user_id is not provided, but was submitted prev.
  107. return false;
  108. }
  109. # already used?
  110. if (!empty($res[$this->alias]['used'])) {
  111. if ($treatUsedAsInvalid) {
  112. return false;
  113. }
  114. # return true and let the application check what to do then
  115. return $res;
  116. }
  117. # actually spend key (set to used)
  118. if ($this->spendKey($res[$this->alias]['id'])) {
  119. return $res;
  120. }
  121. # no limit? we dont spend key then
  122. if (!empty($res[$this->alias]['unlimited'])) {
  123. return $res;
  124. }
  125. $this->log('VIOLATION in CodeKey Model (method useKey)');
  126. return false;
  127. }
  128. /**
  129. * sets Key to "used" (only once!) - directly by ID
  130. * @param id of key to spend: neccessary
  131. * @return boolean true on success, false otherwise
  132. * 2009-05-13 ms
  133. */
  134. public function spendKey($id = null) {
  135. if (empty($id)) {
  136. return false;
  137. }
  138. //$this->id = $id;
  139. if ($this->updateAll(array($this->alias.'.used' => $this->alias.'.used + 1', $this->alias.'.modified'=>'"'.date(FORMAT_DB_DATETIME).'"'), array($this->alias.'.id'=>$id))) {
  140. return true;
  141. }
  142. return false;
  143. }
  144. /**
  145. * remove old/invalid keys
  146. * does not remove recently used ones (for proper feedback)!
  147. * @return boolean success
  148. * 2010-06-17 ms
  149. */
  150. public function garbigeCollector() {
  151. $conditions = array(
  152. $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity),
  153. );
  154. return $this->deleteAll($conditions, false);
  155. }
  156. /**
  157. * get admin stats
  158. * 2010-10-22 ms
  159. */
  160. public function stats() {
  161. $keys = array();
  162. $keys['unused_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
  163. $keys['used_valid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created >='=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
  164. $keys['unused_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>0, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
  165. $keys['used_invalid'] = $this->find('count', array('conditions'=>array($this->alias.'.used'=>1, $this->alias.'.created <'=>date(FORMAT_DB_DATETIME, time()-$this->validity))));
  166. $types = $this->find('all', array('conditions'=>array(), 'fields'=>array('DISTINCT type')));
  167. $keys['types'] = !empty($types) ? Set::extract('/'.$this->alias.'/type', $types) : array();
  168. return $keys;
  169. }
  170. /**
  171. * @param length (defaults to defaultLength)
  172. * @return string codekey
  173. * 2009-05-13 ms
  174. */
  175. public function generateKey($length = null) {
  176. if (empty($length)) {
  177. $length = $this->defaultLength;
  178. }
  179. if ((class_exists('CommonComponent') || App::import('Component', 'Common')) && method_exists('CommonComponent', 'generatePassword')) {
  180. return CommonComponent::generatePassword($length);
  181. } else {
  182. return $this->_generateKey($length);
  183. }
  184. }
  185. /**
  186. * backup method - only used if no custom function exists
  187. * 2010-06-17 ms
  188. */
  189. protected function _generateKey($length = null) {
  190. $chars = "234567890abcdefghijkmnopqrstuvwxyz"; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
  191. $i = 0;
  192. $password = "";
  193. $max = strlen($chars) - 1;
  194. while ($i < $length) {
  195. $password .= $chars[mt_rand(0, $max)];
  196. $i++;
  197. }
  198. return $password;
  199. }
  200. }