User.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. namespace app\models;
  3. use \MongoDate;
  4. use \lithium\util\String;
  5. use \lithium\util\Validator;
  6. use \App\Libraries\openID\LightOpenID;
  7. use \lithium\security\Password;
  8. class User extends \lithium\data\Model {
  9. public $hasMany = array('Post');
  10. public static function __init()
  11. {
  12. //Initialize the parent if you want the database and everything setup (which of course we do)
  13. parent::__init();
  14. //Confirms that the username isn't already in use.
  15. Validator::add('isUniqUser', function($username) {
  16. //If we can't find a user with the same user name then the name is unique.
  17. return User::count(array('conditions' => compact('username'))) == 0;
  18. });
  19. //Checks if the username contains profanity
  20. Validator::add('isClean', function($username) {
  21. //Needs to do a dictonary lookup, but too lazy to implement right now.
  22. return true;
  23. });
  24. Validator::add('isValidGender', function($gender) {
  25. //If the geneder is male or female return true.
  26. return ($gender == 'Male' || $gender == 'Female');
  27. });
  28. Validator::add('isUniqueEmail', function($email) {
  29. //Find all the email address that match the one inputted,
  30. //If there is none found (count == 0) then return true (Email address is unique)
  31. return User::count(array('conditions' => compact('email'))) == 0;
  32. });
  33. Validator::add('validBirthday', function($birthday) {
  34. // :TODO:
  35. //*birthday needs to be 1930 <= $birthday <= current year - 11 (11 or older);
  36. return true;
  37. });
  38. }
  39. /* Validation code */
  40. /*
  41. Things that need to be validated
  42. *The username cannot be taken
  43. *the username cannot cotain special chars or spaces
  44. *there must be an email address
  45. *The email address needs to be a valid email
  46. *it cannot be in use already
  47. *the password needs to be atleast 6 characters
  48. *the username cannot contain profanity
  49. *birthday needs to be 1930 <= $birthday <= current year - 11 (11 or older);
  50. *gender must be Male or Female
  51. */
  52. public $validates = array(
  53. 'username' => array(array('isUniqUser', 'message' => "Username is already taken."),
  54. array('notEmpty', 'message' => 'Please enter a Username.'),
  55. array('isClean', 'message' => 'Profanity is not allowed in Usernames'),
  56. array('alphaNumeric', 'message' => "Usernames cant contain special characters")
  57. ),
  58. 'email' => array(array('email', 'message' => 'The email address is not valid.'),
  59. array('notEmpty', 'message' => 'An email address must be entered.'),
  60. array('isUniqueEmail', 'message' => 'That email address is already in use. Did you forget your password?')
  61. ) /*,
  62. 'newpass' => array(array('lengthBetween' => array('min' => '6', 'max' =>'20'),
  63. 'message' => 'Your password must be between 6 and 20 characters')
  64. )*/ /*,
  65. //It's always possible for people to submit invalid data using cURL or something.
  66. 'gender' => array('isValidGender', 'message' => 'Please check for dangly bits or lack thereof.')
  67. */
  68. );
  69. /* Defaults */
  70. /*
  71. joindate = today,
  72. accesslevel = "user"
  73. */
  74. public function updateuser($entity, $data)
  75. {
  76. $conditions = array('_id' => $entity->_id, 'state' => 'default');
  77. $options = array('multiple' => false, 'safe' => true, 'upsert'=>true);
  78. return static::update($data, $conditions, $options);
  79. }
  80. /**
  81. * Creates a post and stores it into the appropriate user(s) array(s)
  82. * @param User $entity the instance of the user posting the message
  83. * @param Array $data The data from the request (usually submiited from the form)
  84. * @param Array $options Currently not implemented
  85. * @return null Nothing for now, though should return true or false in the future :TODO:
  86. */
  87. public function post($entity, $data, array $options = array())
  88. {
  89. //TODO, fix all methods so that they don't take $data directly
  90. //TODO add validators to these methods/models
  91. //Create the post
  92. $post = Post::create(array('datetime' => new MongoDate(),
  93. 'username' => $entity->username,
  94. 'user_id' => $entity->_id,
  95. 'level' => null));
  96. //1. Parse
  97. //Break the string into an array of words
  98. $search = explode(" ", $data['body']);
  99. //if the first word is DM
  100. if ($search[0] == "DM")
  101. {
  102. //Remove the '@' symbol before we search for that username
  103. $to = substr($search[1], 1);
  104. $post->type = "DM";
  105. //:TODO: Catch the return incase it's false.
  106. return $post->directMessage($to);
  107. }
  108. //If the post beings with a mention (it's a reply / note)
  109. if ($search[0] == "@")
  110. {
  111. //Set the post level to hidden
  112. $post->level = "hidden";
  113. }
  114. //Check if there are any mentions or topics
  115. $post->body = $post->parse($search);
  116. //Because there is a chance that parse will set post level to something
  117. //We pass the current value to level since it will just
  118. //return the same it not set.
  119. //Yes, we could use an if ! null but whatever.
  120. $post->level = $this->postLevel($entity, $post, $post->level);
  121. //Save the post to the posts database.
  122. $post->save();
  123. //If the user has friends
  124. if (count($entity->friends) > 0)
  125. {
  126. //Save this posts to the feed of all the Users Friends
  127. $post->storeAll($entity->friends);
  128. }
  129. //Add this post to the user's feed array
  130. $post->store($entity);
  131. //$save = $entity->save(null, array('validate' => false));
  132. /* In the future, there should be a way to make this method quicker and non-blocking*/
  133. //For each friend, post it in their feed (friends is an array of usernames as strings)
  134. /*if (!empty($entity->friends))
  135. {
  136. foreach ($entity->friends as $friend)
  137. {
  138. //Grab the friend from the database
  139. $curFriend = User::find('first', array('conditions' => array('username' => $friend)));
  140. //Add the post to their feed.
  141. //Array unshift puts the new post at the first element of the feed array.
  142. $curFriend->feed = array_unshift($post->_id, $curFriend->feed);
  143. //Save the friend to the database,
  144. $curFriend->save(array('validates' => false));
  145. //Eventually, we can call a node.js endpoint here
  146. //To tell all subscribers that there is a new a post
  147. //Something like "curl POST $post->_id nodeserver://endpoint/myFeed"
  148. }
  149. } */
  150. }
  151. /**
  152. * Store's the post to the specified user's feed
  153. * @param User $user The user to add the post to
  154. * @param Post $post The post too add to the feed
  155. * @return boolean True if the operation sucsceeded, false otherwise
  156. */
  157. private function storePost($user, $post)
  158. {
  159. $updateData = array('$push' => array('feed' => $post['_id']->__toString()));
  160. $conditions = array('_id' => $user['_id']);
  161. $result = User::update($updateData, $conditions, array('atomic' => false));
  162. return $result;
  163. }
  164. /**
  165. * Returns the appropriate post level for the post
  166. * @see app\models\Post
  167. * @param User $user The user instance of the user that the post will be posted to
  168. * @param Post $post The Post to determine the level for
  169. * @param string $level The level (if you want to override the output)
  170. * @return string $level if one is passed in, otherwise hidden if the post begins with a mention or private if the user has his posts protected
  171. */
  172. public static function postLevel($user, $post, $level = null)
  173. {
  174. //if for some crazy reason you need to set the post to a specific type using this
  175. // method then if $level is not null, return $level
  176. if ($level != null)
  177. {
  178. return $level;
  179. }
  180. //If the post is directed at user (begins with @username)
  181. //This is done in parse right now
  182. //return "hidden"
  183. //If the user has their post set to private
  184. if (isset($user->settings['private']));
  185. {
  186. //return private
  187. return "private";
  188. }
  189. //If none of the above apply
  190. return "public";
  191. }
  192. //When we switch to a graph database, there is a bidirection vertex function
  193. //So we can cut this search down to one query, and one line of code :P
  194. /**
  195. * Check wether user1 and user2 are friends
  196. *
  197. * @param string $user1 The username of the first user
  198. * @param string $user2 The username of the second user
  199. * @return boolean True if the users are friends, false otherwise
  200. */
  201. public static function areFriends($user1, $user2)
  202. {
  203. //Get the first user from the database,
  204. $usr1 = User::find('first', array('conditions' => array('username' => $user1)));
  205. //If user 2 is in user1's friends,
  206. if (in_array($user2, $usr1->friends))
  207. {
  208. $usr2 = User::find('first', array('conditions' => array('username' => $user2)));
  209. //And user1 is in user2s friends
  210. if (in_array($user1, $usr2->friends))
  211. {
  212. return true;
  213. }
  214. }
  215. //otherwise
  216. return false;
  217. }
  218. /**
  219. * GetPosts gets posts from the user (entity) based on some params, and returns them
  220. * @param User $entity, the calling object
  221. * @param Array $options, the options that will be used, you can see the defaults below
  222. * @return array(), with all the posts found or false, if somehow that didn't happen
  223. */
  224. public function getPosts($entity, array $options = array())
  225. {
  226. $posts;
  227. $defaults = array(
  228. 'limit' => '20',
  229. 'qualifier' => 'all',
  230. 'level' => 'public',
  231. );
  232. //If the user passed in options
  233. if (!empty($options))
  234. {
  235. //merge the options with the defaults (upsert them)
  236. array_merge($defaults, $options);
  237. }
  238. //var_dump($entity);
  239. //exit();
  240. //If the user has more posts than the limit, return the limit, if the have less return
  241. $count = (count($entity->feed) >= $defaults['limit']) ? $defaults['limit'] : count($entity->feed);
  242. if ($count == 0)
  243. {
  244. return false;
  245. }
  246. //else
  247. var_dump(Post::find('all', array('conditions' => array('$in' => $entity->feed))));
  248. exit();
  249. for ($i = 0; $i < $count; $i++)
  250. {
  251. $posts[] = Post::find('all', array('conditions' => array('$in' => $entity->feed)));
  252. $posts[] = Post::find($qaulifier, array('conditions' => array('_id' => $entity->feed[$i], 'level' => $defaults[level])));
  253. }
  254. return $posts;
  255. }
  256. /**
  257. * Increments the amount profile views for the user.
  258. * This is the command we are going to give to Mongo, which breaks down to db.users.update({_id : $id}, {$inc: {profileViews : 1}} )
  259. * Which says, find the user by their mongo ID, then increment their profile views by one.
  260. * @param User $entity The instance of user to increment
  261. * @param string $type Not implemented but in the future will allow you to increment anime manga and kdrama list views :TODO:
  262. * @return null
  263. */
  264. public function incrementViews($entity, $type = null)
  265. {
  266. if ($type = null)
  267. {
  268. $views = 'profileViews';
  269. }
  270. $updateData = array('$inc' => array('profileViews' => 1));
  271. $conditions = array('_id' => $entity['_id']);
  272. $result = User::update($updateData, $conditions, array('atomic' => false));
  273. return $result;
  274. }
  275. //Overrides save so we can do some stuff before the data is commited to the database.
  276. public function save($entity, $data = null, array $options = array())
  277. {
  278. //If the new password field is empty, or this is a new user
  279. if(!empty($entity->newpass) || !$entity->exists())
  280. {
  281. //Generate Salt for the user.
  282. $salt = Password::salt('bf', 6);
  283. //Hash their password.
  284. $data['password'] = Password::hash($entity->newpass, $salt);
  285. $data['pepper'] = $salt;
  286. unset($entity->newpass);
  287. }
  288. //If the entity doesn't exist or if the password password has been modified
  289. return parent::save($entity, $data, $options);
  290. }
  291. }
  292. ?>