User.php 11 KB

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