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