User.php 11 KB

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