private function parseChildren() { // Vine adds className+'Id' as an id to the object $class = preg_split("/\\\\/", get_called_class()); $className = strtolower($class[count($class) - 1]); $vineId = $className . 'Id'; $keys = get_object_vars($this->data); foreach ($keys as $key => $value) { if ($key == $vineId) { $this->data->id = $value; } elseif ($key == 'userId') { $this->data->user = User::fromId($value); } elseif ($key == 'postId') { $this->data->post = Post::fromId($value); } elseif ($key == 'created') { $this->data->{$key} = strptime($value); } else { if ($key == 'comments') { $this->data->{$key} = CommentCollection::fromStdClass($value); } else { if ($key == 'likes') { $this->data->{$key} = LikeCollection::fromStdClass($value); } else { if ($key == 'reposts') { $this->data->{$key} = RepostCollection::fromStdClass($value); } else { if ($key == 'tags') { $this->data->{$key} = PureTagCollection::fromStdClass($value); } else { if ($key == 'entities') { $this->data->{$key} = PureEntityCollection::fromStdClass($value); } else { if ($key == 'user') { $this->data->{$key} = User::fromStdClass($value); } } } } } } } } $names = ['user' => 'username', 'post' => 'description', 'comment' => 'comment', 'tag' => 'tag', 'channel' => 'channel', 'notification' => 'notificationTypeId', 'like' => 'postId', 'repost' => 'postId', 'conversation' => 'conversationId', 'message' => 'message']; $nameAttr = isset($names[$className]) ? $names[$className] : 'unknown'; $this->data->name = isset($this->data->{$nameAttr}) ? $this->data->{$nameAttr} : '<Unknown>'; }
/** * Gets the currently logged in user. * @return User */ public static function getUser() { // If we already got the user, just return it if (self::$user != null) { return self::$user; } // Get the user $userid = Cookie::get('userid', 0); $password = Cookie::get('sid', '0'); $user = User::fromId($userid); // Make sure the password is valid if (!$user->isCookiePasword($password)) { // Delete the cookies, they're obviously bad Cookie::delete('userid'); Cookie::delete('sid'); // Create a new guest user $user = User::guest(); } // Set the user and return self::$user = $user; return $user; }
function get_avatar() { // Get the user $user = User::fromId(Input::get('userid')); // Make sure the user has an avatar if (empty($user->getAvatarAttachmentId())) { throw new Exception('This user does not have an avatar.'); } // Render the attachment View::renderImage(Attachment::getStoragePath($user->getAvatarAttachmentId())); }
/** * Sends an email to the user telling them they have a new notification. */ public function sendEmail() { // Make sure we can send the email $user = User::fromId($this->getUserId()); if ($user->isGuest() || $this->hasBeenEmailed()) { return; } // Send the email if (!empty($this->getLink())) { $user->sendEmail('New notification!', 'You have received a new notification!<br />' . '"' . $this->getMessage() . '"<br /> Click <a href="' . APP_ABSOLUTE_URL . $this->getLink() . '">here</a> for more info.'); } else { $user->sendEmail('New notification!', 'You have received a new notification!<br />' . '"' . $this->getMessage() . '"<br /> Click <a href="' . APP_ABSOLUTE_URL . APP_RELATIVE_URL . '">here</a> for more info.'); } // Update the database $query = Database::connection()->prepare('UPDATE user_notification SET emailed_at = ? WHERE notificationid = ?'); $query->bindValue(1, time(), PDO::PARAM_INT); $query->bindValue(2, $this->getId(), PDO::PARAM_INT); $query->execute(); // Update the local info $this->row['emailed_at'] = time(); }
/** * Getter * * @param string $property property to get * * @throws PropertyAccessException * * @return property value */ public function __get($property) { if (in_array($property, array('id', 'survey_id', 'user_id', 'created', 'updated', 'answers'))) { return $this->{$property}; } if ($property == 'survey') { return Survey::fromId($this->survey_id); } if (in_array($property, array('user', 'owner', 'author'))) { return User::fromId($this->user_id); } throw new PropertyAccessException($this, $property); }
/** * Authentication check. * * @return bool */ public static function isAuthenticated() { if (is_null(self::$isAuthenticated)) { self::$isAuthenticated = false; // Do we have remote authentication data in the request ? if (!array_key_exists('signature', $_GET)) { return false; } if (!array_key_exists('timestamp', $_GET)) { return false; } $application = array_key_exists('remote_application', $_GET) ? $_GET['remote_application'] : null; $uid = array_key_exists('remote_user', $_GET) ? $_GET['remote_user'] : null; if (!$application && !$uid) { return false; } self::$attributes = array(); // Get data $received_signature = $_GET['signature']; $timestamp = (int) $_GET['timestamp']; if ($application) { // Check that application is known $applications = Config::get('auth_remote_applications'); if (!is_array($applications) || !array_key_exists($application, $applications)) { throw new AuthRemoteUknownApplicationException($application); } $application = new RemoteApplication($application, $applications[$application]); } // Check request time to avoid replays $late = time() - $timestamp - 15; if ($late > 0) { throw new AuthRemoteTooLateException($late); } // Get method from headers $method = null; foreach (array('X_HTTP_METHOD_OVERRIDE', 'REQUEST_METHOD') as $k) { if (!array_key_exists($k, $_SERVER)) { continue; } $method = strtolower($_SERVER[$k]); } // Build signed data $signed = $method . '&' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . (array_key_exists('PATH_INFO', $_SERVER) ? $_SERVER['PATH_INFO'] : ''); $args = $_GET; unset($args['signature']); if (count($args)) { $signed .= '?' . implode('&', RestUtilities::flatten($args)); } $input = Request::body(); if ($input) { $signed .= '&' . $input; } // Check signature if ($application) { $secret = $application->secret; } else { // Get user, fail if unknown or no user secret try { $user = User::fromId($uid); } catch (UserNotFoundException $e) { throw new AuthRemoteUserRejectedException($uid, 'user not found'); } if (!$user->auth_secret) { throw new AuthRemoteUserRejectedException($user->id, 'no secret set'); } $secret = $user->auth_secret; } $algorithm = Config::get('auth_remote_signature_algorithm'); if (!$algorithm) { $algorithm = 'sha1'; } $signature = hash_hmac($algorithm, $signed, $secret); if ($received_signature !== $signature) { throw new AuthRemoteSignatureCheckFailedException($signed, $secret, $received_signature, $signature); } // Register user id if given if ($uid) { self::$attributes['uid'] = $uid; } // Register admin level if asked for and enabled if ($application) { self::$isAdmin = $application->isAdmin; self::$application = $application; self::$attributes['remote_application'] = $application->name; } self::$isAuthenticated = true; } return self::$isAuthenticated; }
/** * Gets the context for this course. * @param User $user The user to get the context for. * @return array */ public function getContext(User $user) { if (!$this->canView($user)) { return null; } $arry = array('entryid' => $this->getEntryId(), 'courseid' => $this->getCourseId(), 'created_by' => User::fromId($this->getCreatorUserId())->getContext($user), 'can_edit' => $this->canEdit($user), 'is_due' => $this->hasDueTime(), 'due_at' => $this->getDueTime(), 'display_at' => $this->getDisplayTime(), 'title' => $this->getTitle(), 'description' => $this->getDescription(), 'is_visible' => $this->isVisible(), 'important' => $this->isImportantNow()); // Add the questions with all of their answers $questions = Question::forEntry($this); $question_contexts = array(); foreach ($questions as $question) { array_push($question_contexts, $question->getContext($user)); } $arry['questions'] = $question_contexts; // Add the attachments in $attachments = $this->getAttachments(); $attachment_contexts = array(); foreach ($attachments as $attachment) { array_push($attachment_contexts, $attachment->getContext()); } $arry['attachments'] = $attachment_contexts; return $arry; }
/** * Getter * * @param string $property property to get * * @throws PropertyAccessException * * @return property value */ public function __get($property) { if (in_array($property, array('id', 'user_id', 'type', 'title', 'description', 'created', 'choices', 'rules', 'guests'))) { return $this->{$property}; } if (in_array($property, array('user', 'owner', 'author'))) { return User::fromId($this->user_id); } if ($property == 'votes') { if (is_null($this->_votes)) { $this->_votes = Vote::fromSurvey($this); } return $this->_votes; } if ($property == 'can') { if (is_null($this->_can)) { if (Auth::isAdmin() || $this->owner->is(Auth::user())) { // Admin and survey owner have all permissions on survey $this->_can = (object) array('view' => true, 'view_votes' => true, 'vote' => true, 'delete_vote' => true); } else { // Basic users permissions must be evaluated $this->_can = (new Event('survey_permissions', $this))->trigger(function () { return (object) array('view' => true, 'view_votes' => true, 'vote' => (bool) Auth::user(), 'delete_vote' => true); }); } } return $this->_can; } throw new PropertyAccessException($this, $property); }
/** * Get user(s) * * Call examples : * /user : get all users (admin) * /user/@me : get current user (null if no session) * /user/<uid> : get user (admin or current) * * @param int $id user id to get info about * * @return mixed * * @throws RestAuthenticationRequiredException * @throws RestAdminRequiredException * @throws RestBadParameterException */ public static function get($id = null) { // "Session getter" if ($id == '@me') { return Auth::isAuthenticated() ? static::cast(Auth::user()) : null; } // Need to be authenticated ... if (!Auth::isAuthenticated()) { throw new RestAuthenticationRequiredException(); } $request = RestServer::getRequest(); if ($id) { $user = User::fromId($id); // Check ownership if (!$user->is(Auth::user()) && !Auth::isAdmin()) { throw new RestOwnershipRequiredException(Auth::user()->id, 'user = ' . $user->id); } return self::cast($user); } if (!Auth::isAdmin()) { throw new RestAdminRequiredException(); } $users = User::all(); if ($request->filterOp) { $users = static::filter($users, $request->filterOp); } if ($request->updatedSince) { $time = $request->updatedSince; $users = array_filter($users, function ($user) use($time) { return $user->last_activity >= $time; }); } $data = array(); foreach ($users as $user) { $data[] = static::cast($user); } return $data; }
function remove_student() { Auth::checkLoggedIn(); // Get the course and make sure the user can edit it $course = Course::fromId(Input::get('courseid')); if (!$course->canEdit(Auth::getUser())) { throw new Exception('You cannot remove users from this course'); } // Get the user id to remove $user = User::fromId(Input::get('userid')); // Make sure permissions are not being overstepped if ($course->getCreatorUserId() != Auth::getUser()->getUserId() && !$user->isAdmin() && $user->getUserId() == $course->getCreatorUserId()) { throw new Exception('You are not allowed to remove the creator from the class.'); } // Remove the user $course->removeUser($user); // Render the new context View::renderJson($course->getContext(Auth::getUser())); }
function handler_group_ajax_admin_rights($page) { S::assert_xsrf_token(); $group = Group::fromId(Json::i('gid')); $user = User::fromId(Json::i('uid')); if ($group && $user) { if (S::user()->isMe($user) && !S::user()->isAdmin()) { $page->jsonAssign('msg', 'On ne peut pas changer ses propres droits'); } else { if (S::user()->hasRights($group, Rights::admin()) || S::user()->isWeb()) { $group->select(GroupSelect::subscribe()); $rights = new Rights(Json::s('rights')); $caste = $group->caste($rights); if ($caste->userfilter()) { $page->jsonAssign('msg', 'Ce droit est défini de manière logique.'); } else { // Log the event if involving admin rights if ($rights->isMe(Rights::admin())) { S::logger()->log('groups/admin/rights', array('gid' => $group->id(), 'uid' => $user->id(), 'cid' => $caste->id(), 'add' => Json::b('add'))); } if (Json::b('add')) { $caste->addUser($user); } else { $caste->removeUser($user); } } } } } return PL_JSON; }
/** * Returns the context for this answer. * @return array */ public function getContext(User $user) { // Build the likes array $likesUsers = $this->getLikes(); $likes_contexts = array(); foreach ($likesUsers as $like) { array_push($likes_contexts, $like->getContext($user)); } // See if the professor has liked this answer $professorLiked = false; $course = Course::fromId(Question::fromId($this->getQuestionId())->getCourseId()); foreach ($likesUsers as $curUser) { if ($course->canEdit($curUser)) { $professorLiked = true; break; } } $isProfessor = $course->canEdit(User::fromId($this->getUserId())); // Return the context return array('answerid' => $this->getAnswerId(), 'questionid' => $this->getQuestionId(), 'created_at' => $this->getCreationTime(), 'created_by' => User::fromId($this->getUserId())->getContext($user), 'edited' => $this->isEdited(), 'edited_at' => $this->getEditedTime(), 'edited_by' => User::fromId($this->getEditorUserid())->getContext($user), 'text' => $this->getText(), 'can_edit' => $this->canEdit($user), 'has_liked' => $this->hasLiked($user), 'likes' => $likes_contexts, 'professor_liked' => $professorLiked, 'is_professor' => $isProfessor); }
/** * Creates a new user and returns it. * @param string $firstName The first name of the user. * @param string $lastName The last name of the user. * @param string $email The email address of the user. * @param string $password The plaintext password for the user. * @return User * @throws Exception */ public static function create($firstName, $lastName, $email, $password) { // First check the email address $email = strtolower($email); if (!Utils::isValidEmail($email)) { throw new Exception('Unable to create new user: invalid email address given.'); } // Create some variables for the user $createdAt = time(); $salt = Utils::generateRandomPassword(); $saltCookie = Utils::generateRandomPassword(); $emailToken = Utils::generateRandomId(); $password = self::transformPassword($password, $salt); // Create the query $query = Database::connection()->prepare('INSERT INTO user (first_name, last_name, email, email_token, salt, salt_cookie, password,' . ' created_at, created_from, last_visit_at, last_visit_from, current_visit_at, current_visit_from)' . ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); $query->bindValue(1, $firstName, PDO::PARAM_STR); $query->bindValue(2, $lastName, PDO::PARAM_STR); $query->bindValue(3, $email, PDO::PARAM_STR); $query->bindValue(4, $emailToken, PDO::PARAM_STR); $query->bindValue(5, $salt, PDO::PARAM_STR); $query->bindValue(6, $saltCookie, PDO::PARAM_STR); $query->bindValue(7, $password, PDO::PARAM_STR); $query->bindValue(8, $createdAt, PDO::PARAM_INT); $query->bindValue(9, Session::getIpAddress(), PDO::PARAM_STR); $query->bindValue(10, $createdAt, PDO::PARAM_INT); $query->bindValue(11, Session::getIpAddress(), PDO::PARAM_STR); $query->bindValue(12, $createdAt, PDO::PARAM_INT); $query->bindValue(13, Session::getIpAddress(), PDO::PARAM_STR); // Execute the query if (!$query->execute()) { throw new Exception('Unable to create new user: database insert failed.'); } // Get the id of the new user $userid = Database::connection()->lastInsertId(); // Get the user $user = User::fromId($userid); // Send out the verification email $user->sendVerificationEmail(); // Return the user return $user; }