public function run() { $faker = Faker::create(); $log = new Stream('php://stdout'); $log->info('Start ' . __CLASS__); /** @var Phalcon\Db\AdapterInterface $database */ $database = $this->getDI()->get('db'); $database->begin(); for ($i = 0; $i <= self::USERS_TOTAL; $i++) { $user = new Users(); $user->username = $faker->userName; $user->email = $faker->email; $user->timezone = $faker->timezone; $user->moderator = rand(0, 1) ? 'Y' : 'N'; $user->karma = mt_rand(10, 20000); $user->vote = mt_rand(10, 200); $user->votePoint = mt_rand(10, 100); $user->gender = rand(0, 1) ? 1 : 2; //1-male, 2-female $user->passwd = 'todolate'; $user->status = 1; //1-active, 2-pending $user->theme = 'D'; if (!$user->save()) { var_dump($users->getMessages()); $database->rollback(); die; } $log->info('users: ' . $user->getUsername()); } }
/** * Add the badge to ther user * * @param Users $user * @param array $extra */ public function add(Users $user, $extra = null) { $userBadge = new UsersBadges(); $userBadge->setUsersId($user->getId()); $userBadge->setBadge($this->getName()); /** * Default it will set Bronze badges. * In each class extend it will overwrite */ $userBadge->setCode3(UsersBadges::CODE); var_dump($userBadge->save()); }
/** * */ public function process() { $badges = $this->getBadges(); foreach (Users::find() as $user) { $this->processUserBadges($user, $badges); } }
public function run() { $faker = Faker::create(); $log = new Stream('php://stdout'); $log->info('Start ' . __CLASS__); /** @var Phalcon\Db\AdapterInterface $database */ $database = $this->getDI()->get('db'); $userIds = Users::find(['columns' => 'id'])->toArray(); $database->begin(); for ($i = 0; $i <= self::POSTS_TOTAL; $i++) { $title = $faker->company; $userRandId = array_rand($userIds); $posts = new Posts(); $posts->usersId = $userIds[$userRandId]['id']; $posts->type = rand(0, 1) ? 'questions' : 'tips'; $posts->title = $title; $posts->slug = \Phalcon\Tag::friendlyTitle($title); $posts->numberViews = rand(5, 100); $posts->numberReply = rand(0, 20); $posts->content = $faker->text; $posts->sticked = 'N'; $posts->status = 'A'; $posts->locked = 'N'; $posts->deleted = 0; $posts->acceptedAnswer = 'N'; if (!$posts->save()) { var_dump($posts->getMessages()); $database->rollback(); die; } $log->info('posts: ' . $posts->getTitle()); } }
/** * Sends the digest */ public function send() { $lastMonths = new \DateTime(); $lastMonths->modify('-6 month'); $parameters = array('modifiedAt >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => [$lastMonths->getTimestamp()]); $users = []; foreach (Users::find($parameters) as $user) { $toMail = $user->getEmail(); if ($toMail && strpos($user->email, '@phalconbook') === false) { $users[trim($toMail)] = $user->getInforUser(); } } $sitename = '[ ' . $this->config->application->name . ' Forum ]'; $subject = 'Top Stories from ' . $sitename . date('d/m/y'); foreach ($users as $email => $username) { try { $params = ['username' => $username, 'subject' => $subject, 'posts' => $this->getData()]; if (!$this->mail->send($email, 'senddigest', $params)) { var_dump('send disgest email false'); } } catch (\Exception $e) { echo $e->getMessage(), PHP_EOL; } } }
/** * @param string $uid to checking condition when authentication again * @param object $user here is oauth * @param object $toekn here it is token get by oauth * @param object $object here is it is find in database * @param string $nameOauth there are google, github, facebook... * * @return mixed */ public function commonOauthSave($uid, $user, $token, $object, $nameOauth) { if (!$object) { $object = new Users(); //setTokenGithub or setTokenGoogle $uuidName = 'setUuid' . $nameOauth; $tokenName = 'setToken' . $nameOauth; $object->{$tokenName}($token->accessToken); $object->setTokenType(Users::TOKEN_TYPE); //$object->setUid($uid); $object->{$uuidName}($uid); $object->setEmail($user->email); $object->setFirstname($user->firstName); //@ Todo later, it perfect if we do haven't delete in database $username = '******' . (Users::count() + 1); $object->setUsername($username); if (empty($user->email)) { $object->setEmail($username . '*****@*****.**'); } $object->setStatus(Users::STATUS_ACTIVE); $object->increaseKarma(Karma::LOGIN); if (!$object->save()) { $this->displayModelErrors($object); return $this->indexRedirect(); } } //Update session id session_regenerate_id(true); //Store the user data in session $this->auth->setSession($object); //Store the user data in cookies $this->auth->setRememberEnviroment($object); //Dispaly notification when user login $this->notification($object); return $this->currentRedirect(); }
/** * @param int $limit * @return \Phalcon\Mvc\Model\ResultsetInterface */ public static function highestKarma($limit = 4) { $user = Users::query()->limit($limit)->order('karma DESC')->execute(); if ($user->valid()) { return $user; } }
public function afterCreate() { if ($this->id > 0) { $activity = new Activities(); $activity->setUsersId($this->usersId); $activity->setPostsId($this->postsId); $activity->setType(Activities::NEW_REPLY); $activity->save(); $toNotify = []; /** * Notify users that always want notifications */ foreach (Users::find(['notifications = "Y"', 'columns' => 'id'])->toArray() as $user) { if ($this->usersId != $user['id']) { $notificationId = $this->setNotification($user['id'], $this->postsId, $this->id, Notifications::TYPE_REPLY); $this->setActivityNotifications($user['id'], $this->postsId, $this->id, $this->usersId, ActivityNotifications::TYPE_REPLY); $toNotify[$user['id']] = $notificationId; } } /** * Notify users that always want notifications for comment */ /** * Register users subscribed to the post */ foreach (PostsSubscribers::findByPostsId($this->postsId) as $subscriber) { if (!isset($toNotify[$subscriber->getUsersId()])) { $notificationId = $this->setNotification($subscriber->getUsersId(), $this->postsId, $this->id, Notifications::TYPE_REPLY); $this->setActivityNotifications($subscriber->getUsersId(), $this->postsId, $this->id, $this->usersId, ActivityNotifications::TYPE_REPLY); $toNotify[$subscriber->getUsersId()] = $notificationId; } } /** * Register the user in the post's notifications */ if (!isset($toNotify[$this->usersId])) { $parameters = ['usersId = ?0 AND postsId = ?1', 'bind' => array($this->usersId, $this->postsId)]; $hasNotifications = PostsNotifications::count($parameters); if (!$hasNotifications) { $notification = new PostsNotifications(); $notification->setUsersId($this->usersId); $notification->setPostsId($this->postsId); $notification->save(); } } /** * Queue notifications to be sent */ $this->getDI()->getQueue()->put($toNotify); } }
/** * Displays a post and its comments * * @param $id * @param $slug * * @return \Phalcon\Http\ResponseInterface */ public function viewAction($id, $slug) { $id = (int) $id; $userId = $this->auth->getAuth()['id']; if (!($object = Posts::findFirstById($id))) { $this->flashSession->error(t('Posts doesn\'t exist.')); return $this->indexRedirect(); } if ($object->getDeleted()) { $this->flashSession->error('The Post is deleted'); return $this->indexRedirect(); } $ipAddress = $this->request->getClientAddress(); $parameters = ['postsId = ?0 AND ipaddress = ?1', 'bind' => [$id, $ipAddress]]; $viewed = PostsViews::count($parameters); //A view is stored by ipaddress if (!$viewed) { //Increase the number of views in the post $object->setNumberViews($object->getNumberViews() + 1); if ($object->getUsersId() != $userId) { $object->user->increaseKarma(Karma::VISIT_ON_MY_POST); if ($userId > 0) { $user = Users::findFirstById($userId); if ($user) { if ($user->getModerator() == 'Y') { $user->increaseKarma(Karma::MODERATE_VISIT_POST); } else { $user->increaseKarma(Karma::VISIT_POST); } //send log to server if (!$user->save()) { $this->saveLoger($user->getMessages()); } } } } if (!$object->save()) { $this->saveLoger($object->getMessages()); } $postView = new PostsViews(); $postView->setPostsId($id); $postView->setIpaddress($ipAddress); if (!$postView->save()) { $this->saveLoger($postView->getMessages()); } } $this->view->setVars(['post' => $object, 'form' => new ReplyForm(), 'votes' => $object->getVotes($id, Vote::OBJECT_POSTS), 'postsReply' => $object->getPostsWithVotes($id), 'commentForm' => new CommentForm(), 'userPosts' => $object->user, 'type' => Posts::POST_QUESTIONS]); $this->tag->setTitle($this->escaper->escapeHtml($object->getTitle())); return $this->view->pick('single'); }
public function tokenTwitterkAction() { $this->view->disable(); $auth = new TwitterAuth($this->config->twitter); list($uid, $token, $user) = $auth->authorize(); if (isset($token) && is_object($token)) { //Edit/Create the user $object = Users::findFirstByUid($uid); $this->commonOauthSave($uid, $user, $token, $object, 'Facebook'); } else { $this->flashSession->error('Invalid Google response. Please try again'); return $this->response->redirect(); } }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { return $user->getModerator() == 'Y'; }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { return $user->getKarma() >= 5000; }
/** * @return \Phalcon\Http\ResponseInterface */ public function forgotpasswordAction() { //Resets any "template before" layouts because we use mutiple theme $this->view->cleanTemplateBefore(); if ($this->session->has('auth')) { $this->view->disable(); return $this->response->redirect(); } $form = new ForgotPasswordForm(); if ($this->request->isPost()) { if (!$form->isValid($_POST)) { foreach ($form->getMessages() as $message) { $this->flashSession->error($message); } } else { $object = Users::findFirstByEmail($this->request->getPost('email')); if (!$object) { // @TODO: Implement brute force protection $this->flashSession->error(t('User not found.')); return $this->currentRedirect(); } $lastpass = $object->getLastPasswdReset(); if (!empty($lastpass) && date('Y-m-d H:i:s') - $object->getLastPasswdReset() > $this->config->application->passwdResetInterval) { $this->flashSession->error(t('You need to wait ') . (date('Y-m-d H:i:s') - $object->getLastPasswdReset()) . ' minutes'); return $this->currentRedirect(); } $passwordForgotHash = sha1('forgot' . microtime()); $object->setPasswdForgotHash($passwordForgotHash); $object->setLastPasswdReset(date('Y-m-d H:i:s')); if (!$object->save()) { $this->displayModelErrors($object); } else { $params = ['firstname' => $object->getFirstname(), 'lastname' => $object->getLastname(), 'link' => ($this->request->isSecureRequest() ? 'https://' : 'http://') . $this->request->getHttpHost() . '/oauth/resetpassword?forgothash=' . $passwordForgotHash]; if (!$this->mail->send($object->getEmail(), 'forgotpassword', $params)) { $this->flashSession->error(t('Error sendig email.')); } else { $this->flashSession->success(t('An email was sent to your address in order to continue with the reset password process.')); return $this->response->redirect(); } } } } $this->view->form = $form; }
public function testValidateReturnsFalseIfDuplicateEmail() { $user = new Users(); $user->email = '*****@*****.**'; $this->assertFalse($user->save(), "New User should not created"); }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { $date = new \DateTime(); $date->modify('-1 year'); return $user->getKarma() >= 1000 && $user->getCreatedAt() < $date->getTimestamp(); }
/** * @param $id * @return mixed */ public function getUserById($id) { return Users::findFirstById($id); }
public function settingsAction() { $object = Users::findFirstById($this->auth->getAuth()['id']); if (!$object) { $this->flashSession->error(t('Hack attempt!!!')); return $this->response->redirect(); } $form = new UserSettingForm($object); $form->bind($_POST, $object); if ($this->request->isPost()) { if (!$form->isValid()) { foreach ($form->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { $object->setDigest($this->request->getPost('digest')); if (!$object->save()) { foreach ($object->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { $this->flashSession->success(t('Data was successfully saved')); $this->refreshAuthSession($object->toArray()); return $this->response->redirect($this->router->getControllerName() . '/settings'); } } } $this->tag->setTitle(t('Edit profile')); $this->view->form = $form; $this->view->object = $object; }
/** * registerAction function. * * @access public * @return void */ public function registerAction() { if (empty($this->router->getParams()[0])) { $this->flashSession->error('Hack attempt!!!'); return $this->response->redirect('/'); } if ($this->auth->getAuth()) { $this->view->disable(); return $this->response->redirect(); } $registerHash = $this->router->getParams()[0]; $object = Users::findFirstByRegisterHash($registerHash); if (!$object) { $this->flashSession->error('Invalid data.'); return $this->response->redirect(); } $form = new ResetPasswordForm(); $this->view->form = $form; if ($this->request->isPost()) { if (!$form->isValid($_POST)) { foreach ($form->getMessages() as $message) { $this->flashSession->error($message); } } else { $object->setPasswd($this->security->hash($this->request->getPost('password_new_confirm'))); $object->setRegisterHash(null); $object->setStatus(Users::STATUS_ACTIVE); if (!$object->save()) { $this->displayModelErrors($object); } else { $this->flashSession->success(t('Your password was changed successfully.')); return $this->response->redirect(); } } } $this->view->pick(['auth/resetpassword']); }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { return $user->countReplies() >= 10; }
public function changepasswordAction() { $form = new ChangePasswordForm(); $object = Users::findFirstById($this->auth->getAuth()['id']); $this->view->form = $form; if ($this->request->isPost()) { if (!$form->isValid($this->request->getPost())) { foreach ($form->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { if ($object && $object->getStatus() == $object::STATUS_ACTIVE) { if (!$this->security->checkHash($this->request->getPost('passwd'), $object->getPasswd())) { $this->flashSession->error(t('Oops! Wrong password.')); } else { $newPass = $this->security->hash($this->request->getPost('passwd_new_confirm')); $object->setPasswd($newPass); if (!$object->save()) { $this->displayModelErrors($object); } else { $this->flashSession->success(t('Hooray! Your password was successfully changed.')); return $this->response->redirect($this->router->getControllerName() . '/changepassword'); } } } elseif ($object && $object->getStatus() != Users::STATUS_ACTIVE) { $this->flashSession->error(t('User status is: ') . $object->getStatusesWithLabels()[$object->getStatus()] . '. You can\'t change your password.'); } else { $this->flashSession->error(t('User doesn\'t exist !')); } } } return true; }
/** * Comments are temporary "Post-It" notes left on a question or answer. * They can be up-voted (but not down-voted) and flagged, but do not generate reputation. * There's no revision history, and when they are deleted they're gone for good. * * @return mixed */ public function commentAction() { $this->view->disable(); if (!$this->request->isPost()) { return $this->response->redirect($this->router->getControllerName()); } $user = Users::findFirstById($this->auth->getAuth()['id']); if (!$user) { $this->flashSession->error(t('You need to login first')); return $this->currentRedirect(); } if ($user->getVote() < 9) { $this->flashSession->error(t('You must have 10 points to add comment')); return $this->currentRedirect(); } $object = new Comment(); $form = new CommentForm($object); $form->bind($_POST, $object); if (!$form->isValid($this->request->getPost())) { foreach ($form->getMessages() as $message) { $this->flashSession->error($message->getMessage()); } } else { if (!$object->save()) { $this->displayModelErrors($object); } } return $this->currentRedirect(); }
/** * Check condition to allow comment or vote * * @return mixed */ public function getVote() { $identity = $this->session->get('auth'); if (isset($identity['id'])) { $user = Users::findFirstById($identity['id']); if (!$user) { error_log('The user does not exist' . __CLASS__ . ' and ' . __LINE__); return false; } return $user->getVote(); } return false; }
/** * Implement hook beforeUpdate of Model Phalcon * * @return mixed */ public function afterCreate() { if ($this->id > 0) { /** * Register the activity */ $activity = new Activities(); $activity->setUsersId($this->usersId); $activity->setPostsId($this->id); $activity->setType(Activities::NEW_POSTS); $activity->save(); /** * Register the user in the post's notifications */ $notification = new PostsNotifications(); $notification->setUsersId($this->usersId); $notification->setPostsId($this->id); $notification->save(); $toNotify = []; /** * Notify users that always want notifications */ foreach (Users::find(['notifications = "Y"', 'columns' => 'id'])->toArray() as $user) { if ($this->usersId != $user['id']) { $notificationId = $this->setNotification($user['id'], $this->id, null, Notifications::TYPE_POSTS); $toNotify[$user['id']] = $notificationId; } } /** * Queue notifications to be sent */ $this->getDI()->getQueue()->put($toNotify); } }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { return $user->countPosts('acceptedAnswer = "Y"') >= 1; }
/** * Initiate grid */ protected static function setGrid() { parent::$grid = ['grid' => ['name' => ['title' => t('Name'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => '']], 'username' => ['title' => t('Username'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => '']], 'email' => ['title' => t('Email'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => '']], 'moderator' => ['title' => t('Moderator'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => 'width:100px']], 'admin' => ['title' => t('Admin'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => 'width:100px']], 'karma' => ['title' => t('Karma'), 'order' => true, 'filter' => ['type' => 'input', 'sanitize' => 'string', 'style' => 'width:100px']], 'status' => ['title' => t('Status'), 'order' => true, 'filter' => ['type' => 'select', 'sanitize' => 'int', 'using' => null, 'values' => Users::getStatusesWithLabels(), 'style' => 'width: 100px;']], 'null' => ['title' => t('Actions')]], 'query' => ['columns' => ['a.id', "CONCAT(a.firstname, ' ', a.lastname) as name ", 'a.username', 'a.gender', 'a.email', 'a.status', 'a.admin', 'a.moderator', 'a.karma'], 'joins' => [], 'groupBy' => 'a.id']]; }
/** * Get information editor user * * @return mixed|bool */ public function getUserById($id) { $user = Users::query()->where('id = :id:')->bind(['id' => $id])->limit(1)->execute(); if ($user->valid()) { return $user->getFirst(); } return false; }
/** * * @param Phanbook\Models\Users $object */ public function setSession($object) { $this->session->set('auth', array('id' => $object->getId(), 'admin' => $object->getAdmin(), 'moderator' => $object->getModerator(), 'theme' => $object->getTheme(), 'name' => $object->getInforUser(), 'username' => $object->getUsername(), 'email' => $object->getEmail())); }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { $canHave = Vote::count(['usersId = ?0 AND positive = 1', 'bind' => [$user->getId()]]) > 0; return $canHave; }
/** * Check whether the user can have the badge * * @param Users $user * @return boolean */ public function canHave(Users $user) { return $user->countReplies('accepted = "Y"') >= 15; }
/** * The answer a question * @return mixed */ public function answerAction() { $this->view->disable(); $auth = $this->auth->getAuth(); if (!$auth) { $this->flashSession->error(t('You must be logged in first to post answer')); return $this->currentRedirect(); } if ($this->request->isPost()) { $postId = $this->request->getPost('id'); $content = $this->request->getPost('content', 'trim'); if (str_word_count($content) < 10) { $this->flashSession->error(t('Body must be at least 15 word')); return $this->currentRedirect(); } $post = Posts::findFirstById($postId); $user = Users::findFirstById($auth['id']); //Only update the number of replies if the user that commented isn't the same that posted if ($user->getId() != $post->getUsersId()) { $post->setNumberReply($post->getNumberReply() + 1); $post->user->increaseKarma(Karma::SOMEONE_REPLIED_TO_MY_POST); $user->increaseKarma(Karma::REPLY_ON_SOMEONE_ELSE_POST); if (!$post->save() || !$user->save()) { error_log('Save fail answerAction. I am on here ' . __LINE__); return false; } } $object = new PostsReply(); $object->setPostsId($postId); $object->setContent($content); $object->setUsersId($auth['id']); if (!$object->save()) { foreach ($object->getMessages() as $message) { $this->flashSession->error($message); } return $this->currentRedirect(); } $this->flashSession->success(t('Data was successfully saved')); return $this->currentRedirect(); } }