public function homeAction() { // action body // echo $_COOKIE["account"]; // print_r( $this->cookie); $imgpath = $_SERVER['DOCUMENT_ROOT'] . "/WebOne/public/image/head/"; $id = $_SESSION["userinfo"][0][id]; // print_r($_SESSION["userinfo"][0]); $userinfo = new userinfoModel(); $db = $userinfo->getAdapter(); $user = $db->query('SELECT * FROM userinfo where userid=?', $id)->fetchAll()[0]; $activitys = new ActivityModel(); $db1 = $activitys->getAdapter(); $hotactivity = $db1->query('select * from activity order by nums desc limit 0,1')->fetchAll()[0]; $questions = new QuestionModel(); $db2 = $questions->getAdapter(); $hotquestion = $db2->query('select * from question order by answernum desc limit 0,1')->fetchAll()[0]; if (file_exists($imgpath . $id . ".jpg")) { $this->view->path = $baseUrl . "/WebOne/public/image/head/" . $id . ".jpg"; } else { $this->view->path = $baseUrl . "/WebOne/public/image/initial.jpg"; } $userid = $hotquestion[userid]; $Usertable = new UserModel(); $db3 = $Usertable->getAdapter(); $name = $db3->query('select name from User where id=?', $userid)->fetchAll()[0][name]; $this->view->user = $user; $this->view->info = $_SESSION["userinfo"]; $this->view->activity = $hotactivity; $this->view->question = $hotquestion; $this->view->name = $name; }
/** * Grabs all new notifications and adds them to the sender's inform queue. * * This method gets called by dashboard's hooks file to display new * notifications on every pageload. * * @since 2.0.18 * @access public * * @param Gdn_Controller $Sender The object calling this method. */ public static function informNotifications($Sender) { $Session = Gdn::session(); if (!$Session->isValid()) { return; } $ActivityModel = new ActivityModel(); // Get five pending notifications. $Where = array('NotifyUserID' => Gdn::session()->UserID, 'Notified' => ActivityModel::SENT_PENDING); // If we're in the middle of a visit only get very recent notifications. $Where['DateUpdated >'] = Gdn_Format::toDateTime(strtotime('-5 minutes')); $Activities = $ActivityModel->getWhere($Where, 0, 5)->resultArray(); $ActivityIDs = array_column($Activities, 'ActivityID'); $ActivityModel->setNotified($ActivityIDs); $Sender->EventArguments['Activities'] =& $Activities; $Sender->fireEvent('InformNotifications'); foreach ($Activities as $Activity) { if ($Activity['Photo']) { $UserPhoto = anchor(img($Activity['Photo'], array('class' => 'ProfilePhotoMedium')), $Activity['Url'], 'Icon'); } else { $UserPhoto = ''; } $Excerpt = Gdn_Format::plainText($Activity['Story']); $ActivityClass = ' Activity-' . $Activity['ActivityType']; $Sender->informMessage($UserPhoto . Wrap($Activity['Headline'], 'div', array('class' => 'Title')) . Wrap($Excerpt, 'div', array('class' => 'Excerpt')), 'Dismissable AutoDismiss' . $ActivityClass . ($UserPhoto == '' ? '' : ' HasIcon')); } }
/** * Award a badge to a user and record some activity * * @param int $BadgeID * @param int $UserID This is the user that should get the award * @param int $InsertUserID This is the user that gave the award * @param string $Reason This is the reason the giver gave with the award */ public function Award($BadgeID, $UserID, $InsertUserID = NULL, $Reason = '') { $Badge = Yaga::BadgeModel()->GetByID($BadgeID); if (!empty($Badge)) { if (!$this->Exists($UserID, $BadgeID)) { $this->SQL->Insert('BadgeAward', array('BadgeID' => $BadgeID, 'UserID' => $UserID, 'InsertUserID' => $InsertUserID, 'Reason' => $Reason, 'DateInserted' => date(DATE_ISO8601))); // Record the points for this badge UserModel::GivePoints($UserID, $Badge->AwardValue, 'Badge'); // Increment the user's badge count $this->SQL->Update('User')->Set('CountBadges', 'CountBadges + 1', FALSE)->Where('UserID', $UserID)->Put(); if (is_null($InsertUserID)) { $InsertUserID = Gdn::Session()->UserID; } // Record some activity $ActivityModel = new ActivityModel(); $Activity = array('ActivityType' => 'BadgeAward', 'ActivityUserID' => $UserID, 'RegardingUserID' => $InsertUserID, 'Photo' => $Badge->Photo, 'RecordType' => 'Badge', 'RecordID' => $BadgeID, 'Route' => '/badges/detail/' . $Badge->BadgeID . '/' . Gdn_Format::Url($Badge->Name), 'HeadlineFormat' => T('Yaga.Badge.EarnedHeadlineFormat'), 'Data' => array('Name' => $Badge->Name), 'Story' => $Badge->Description); // Create a public record $ActivityModel->Queue($Activity, FALSE); // TODO: enable the grouped notifications after issue #1776 is resolved , array('GroupBy' => 'Route')); // Notify the user of the award $Activity['NotifyUserID'] = $UserID; $ActivityModel->Queue($Activity, 'BadgeAward', array('Force' => TRUE)); // Actually save the activity $ActivityModel->SaveQueue(); $this->EventArguments['UserID'] = $UserID; $this->FireEvent('AfterBadgeAward'); } } }
public function getData($Limit = false) { if (!$Limit) { $Limit = $this->Limit; } $ActivityModel = new ActivityModel(); $Data = $ActivityModel->getWhere(array('NotifyUserID' => ActivityModel::NOTIFY_PUBLIC), '', '', $Limit, 0); $this->ActivityData = $Data; }
public function GetData($Limit = FALSE) { if (!$Limit) { $Limit = $this->Limit; } $ActivityModel = new ActivityModel(); $Data = $ActivityModel->GetWhere(array('NotifyUserID' => ActivityModel::NOTIFY_PUBLIC), 0, $Limit); $this->ActivityData = $Data; }
/** * This determines if the current user can react on this item with this action * * @param string $Type valid options are 'discussion', 'comment', and 'activity' * @param int $ID * @param int $ActionID * @throws Gdn_UserException */ public function Index($Type, $ID, $ActionID) { $Type = strtolower($Type); $Action = $this->ActionModel->GetByID($ActionID); // Make sure the action exists and the user is allowed to react if (!$Action) { throw new Gdn_UserException(T('Yaga.Action.Invalid')); } if (!Gdn::Session()->CheckPermission($Action->Permission)) { throw PermissionException(); } switch ($Type) { case 'discussion': $Model = new DiscussionModel(); $AnchorID = '#Discussion_'; break; case 'comment': $Model = new CommentModel(); $AnchorID = '#Comment_'; break; case 'activity': $Model = new ActivityModel(); $AnchorID = '#Activity_'; break; default: throw new Gdn_UserException(T('Yaga.Action.InvalidTargetType')); break; } $Item = $Model->GetID($ID); if ($Item) { $Anchor = $AnchorID . $ID . ' .ReactMenu'; } else { throw new Gdn_UserException(T('Yaga.Action.InvalidTargetID')); } $UserID = Gdn::Session()->UserID; switch ($Type) { case 'comment': case 'discussion': $ItemOwnerID = $Item->InsertUserID; break; case 'activity': $ItemOwnerID = $Item['RegardingUserID']; break; default: throw new Gdn_UserException(T('Yaga.Action.InvalidTargetType')); break; } if ($ItemOwnerID == $UserID) { throw new Gdn_UserException(T('Yaga.Error.ReactToOwn')); } // It has passed through the gauntlet $this->ReactionModel->Set($ID, $Type, $ItemOwnerID, $UserID, $ActionID); $this->JsonTarget($Anchor, RenderReactionList($ID, $Type, FALSE), 'ReplaceWith'); // Don't render anything $this->Render('Blank', 'Utility', 'Dashboard'); }
public function AddActivity() { // Build the story for the activity. $Header = $this->GetImportHeader(); $PorterVersion = GetValue('Vanilla Export', $Header, T('unknown')); $SourceData = GetValue('Source', $Header, T('unknown')); $Story = sprintf(T('Vanilla Export: %s, Source: %s'), $PorterVersion, $SourceData); $ActivityModel = new ActivityModel(); $ActivityModel->Add(Gdn::Session()->UserID, 'Import', $Story); return TRUE; }
/** * * * @return bool * @throws Gdn_UserException */ public function addActivity() { // Build the story for the activity. $Header = $this->getImportHeader(); $PorterVersion = val('Vanilla Export', $Header, t('unknown')); $SourceData = val('Source', $Header, t('unknown')); $Story = sprintf(t('Vanilla Export: %s, Source: %s'), $PorterVersion, $SourceData); $ActivityModel = new ActivityModel(); $ActivityModel->add(Gdn::session()->UserID, 'Import', $Story); return true; }
public function lists() { $page = intval(Input::get('page', 1)); $start_time = Input::get('start_time', ''); $expire = Input::get('expire', ''); $args = ['start_time' => $start_time, 'expire' => $expire]; $model = new ActivityModel(); $count = $model->getCount($args); $rows = $model->getRows($page, $args); $page_size = Pagination::getPageSize($count); return View::make('activity.lists', ['rows' => $rows, 'page' => $page, 'page_size' => $page_size, 'params' => $args]); }
public function post($data = []) { if (empty($data)) { throw new Exception('Some data is needed to be posted.'); } else { $activity = new ActivityModel(); if (array_key_exists('user_id', $data)) { $activity->setUserId($data['user_id']); } if (array_key_exists('exercise_name', $data)) { $activity->setExerciseName($data['exercise_name']); } if (array_key_exists('exercise_duration', $data)) { $activity->setExerciseDuration($data['exercise_duration']); } if (array_key_exists('exercise_calories', $data)) { $activity->setExerciseCalories($data['exercise_calories']); } if (array_key_exists('exercise_distance', $data)) { $activity->setExerciseDistance($data['exercise_distance']); } if (array_key_exists('exercise_timestamp', $data)) { $activity->setExerciseTimestamp($data['exercise_timestamp']); } if ($activity->save()) { return true; } else { return false; } } }
/** * Builds a report using the passed parameters, and displays the result * using the report show view * * @param Array $params */ public function report_build($params) { $formdata = (object) $params; $this->_data->range = IntervalModel::get_range_total($formdata); $this->_data->intervals = IntervalModel::get_between($formdata); $this->_data->incidences = ActivityModel::find_all_incidences($formdata->user); new UserReportShowView($this->_data); }
public function GetData($Limit = 5, $RoleID = '') { if (!is_array($RoleID) && $RoleID != '') { $RoleID = array($RoleID); } $ActivityModel = new ActivityModel(); if (is_array($RoleID)) { $Data = $ActivityModel->GetForRole($RoleID, 0, $Limit); } else { $Data = $ActivityModel->Get('', 0, $Limit); } $this->ActivityData = $Data; if (!is_array($RoleID)) { $RoleID = array(); } $this->_RoleID = $RoleID; }
public function Post($Notify = FALSE, $UserID = FALSE) { if (is_numeric($Notify)) { $UserID = $Notify; $Notify = FALSE; } if (!$UserID) { $UserID = Gdn::Session()->UserID; } switch ($Notify) { case 'mods': $this->Permission('Garden.Moderation.Manage'); $NotifyUserID = ActivityModel::NOTIFY_MODS; break; case 'admins': $this->Permission('Garden.Settings.Manage'); $NotifyUserID = ActivityModel::NOTIFY_ADMINS; break; default: $this->Permission('Garden.Profiles.Edit'); $NotifyUserID = ActivityModel::NOTIFY_PUBLIC; break; } $Activities = array(); if ($this->Form->IsPostBack()) { $Data = $this->Form->FormValues(); $Data = $this->ActivityModel->FilterForm($Data); $Data['Format'] = C('Garden.InputFormatter'); if ($UserID != Gdn::Session()->UserID) { // This is a wall post. $Activity = array('ActivityType' => 'WallPost', 'ActivityUserID' => $UserID, 'RegardingUserID' => Gdn::Session()->UserID, 'HeadlineFormat' => T('HeadlineFormat.WallPost', '{RegardingUserID,you} → {ActivityUserID,you}'), 'Story' => $Data['Comment'], 'Format' => $Data['Format']); } else { // This is a status update. $Activity = array('ActivityType' => 'Status', 'HeadlineFormat' => T('HeadlineFormat.Status', '{ActivityUserID,user}'), 'Story' => $Data['Comment'], 'Format' => $Data['Format'], 'NotifyUserID' => $NotifyUserID); $this->SetJson('StatusMessage', Gdn_Format::Display($Data['Comment'])); } $Activity = $this->ActivityModel->Save($Activity, FALSE, array('CheckSpam' => TRUE)); if ($Activity == SPAM) { $this->StatusMessage = T('Your post has been flagged for moderation.'); $this->Render('Blank', 'Utility'); return; } if ($Activity) { if ($UserID == Gdn::Session()->UserID && $NotifyUserID == ActivityModel::NOTIFY_PUBLIC) { Gdn::UserModel()->SetField(Gdn::Session()->UserID, 'About', Gdn_Format::PlainText($Activity['Story'], $Activity['Format'])); } $Activities = array($Activity); ActivityModel::JoinUsers($Activities); $this->ActivityModel->CalculateData($Activities); } } if ($this->DeliveryType() == DELIVERY_TYPE_ALL) { Redirect($this->Request->Get('Target', '/activity')); } $this->SetData('Activities', $Activities); $this->Render('Activities'); }
public function CommentAlreadyChecking($param) { $data = parent::CommentAlreadyCheckingProcess($param); if (empty($data['ac_id'])) { return true; } else { // Already thank activity return false; } }
/** * 将消息和用户关联 * @param ActivityModel $p_msgModel 消息模型 * @param array $p_queryWhere 用户的筛选方案 * @return int 关联个数 */ public static function createNewModels($p_msgModel, $p_queryWhere = array()) { $userIDs = DBModel::instance('user')->where($p_queryWhere)->selectValues('id'); $tmpData = array(); $tmpData['msgID'] = $p_msgModel->getId(); $tmpData['readStatus'] = READ_STATUS::UNREAD; $tmpData['createTime'] = date('Y-m-d H:i:s'); $tmpData['modifyTime'] = date('Y-m-d H:i:s'); $dbFac = static::newDBModel(); foreach ($userIDs as $userID) { $tmpData['userID'] = $userID; $dbFac->insert($tmpData); } //推送 if (count($userIDs) > 0) { $p_where = array(); $p_where['joinList'] = array(); $p_where['joinList'][] = array('relationActivityUser t2', array('t2.userID = t1.userID', 't2.msgID' => $p_msgID, 't2.readStatus' => READ_STATUS::UNREAD)); DeviceController::pushSingleMessage($p_where, $p_msgModel->getTitle(), $p_msgModel->getDescription(), $customtype = null, $customvalue = null, $tag_name = null); } return count($userIDs); }
/** * Grabs all new notifications and adds them to the sender's inform queue. * * This method gets called by dashboard's hooks file to display new * notifications on every pageload. * * @since 2.0.18 * @access public * * @param Gdn_Controller $Sender The object calling this method. */ public static function InformNotifications($Sender) { $Session = Gdn::Session(); if (!$Session->IsValid()) { return; } $ActivityModel = new ActivityModel(); // Get five pending notifications. $Where = array('NotifyUserID' => Gdn::Session()->UserID, 'Notified' => ActivityModel::SENT_PENDING); // If we're in the middle of a visit only get very recent notifications. $Where['DateInserted >'] = Gdn_Format::ToDateTime(strtotime('-5 minutes')); $Activities = $ActivityModel->GetWhere($Where, 0, 5)->ResultArray(); $ActivityIDs = ConsolidateArrayValuesByKey($Activities, 'ActivityID'); $ActivityModel->SetNotified($ActivityIDs); foreach ($Activities as $Activity) { if ($Activity['Photo']) { $UserPhoto = Anchor(Img($Activity['Photo'], array('class' => 'ProfilePhotoMedium')), $Activity['Url'], 'Icon'); } else { $UserPhoto = ''; } $Excerpt = Gdn_Format::Display($Activity['Story']); $Sender->InformMessage($UserPhoto . Wrap($Activity['Headline'], 'div', array('class' => 'Title')) . Wrap($Excerpt, 'div', array('class' => 'Excerpt')), 'Dismissable AutoDismiss' . ($UserPhoto == '' ? '' : ' HasIcon')); } }
public function content() { global $CONFIG; if (empty($this->_data->activity)) { return BootstrapHelper::alert('info', Lang::get('event:noactivity'), Lang::get('event:noactivity:message')); } //check if there is a next page (page count starts at 0 thus the +1) $this->_data->page + 1 < ActivityModel::pages() ? $next = true : ($next = false); $activity_table_content = ''; foreach ($this->_data->activity as $entry) { $activity_table_content .= '<tr> <td>' . $entry->id . '</td> <td><span class="label ' . BootstrapHelper::get_label_for_action($entry->action) . '">' . BootstrapHelper::get_event_description($entry->action) . '</span></td> <td>' . Lang::get('dayofweek' . date('N', $entry->timestamp)) . '</td> <td>' . date('d/m/Y', $entry->timestamp) . '</td> <td>' . date('G:i:s', $entry->timestamp) . '</td> <td>' . utf8_encode($entry->firstname) . '</td> <td>' . utf8_encode($entry->lastname) . '</td> <td><a href="' . $CONFIG->wwwroot . '/admin/users/' . $entry->userid . '/details">' . $entry->identifier . '</a></td> </tr> '; } return ' <section id="activity" class="well"> <table class="table"> <thead> <tr> <th>#</th> <th>' . Lang::get('action') . '</th> <th>' . Lang::get('day') . '</th> <th>' . Lang::get('date') . '</th> <th>' . Lang::get('time') . '</th> <th>' . Lang::get('firstname') . '</th> <th>' . Lang::get('lastname') . '</th> <th>' . Lang::get('identifier') . '</th> </tr> </thead> <tbody>' . $activity_table_content . ' </tbody> </table> ' . MenuHelper::get_pagination_links($CONFIG->wwwroot . '/admin/activity/', $this->_data->page, $next) . ' <div class="container"></div> </section>'; }
/** * Save message from form submission. * * @since 2.0.0 * @access public * * @param array $FormPostValues Values submitted via form. * @return int Unique ID of message created or updated. */ public function Save($FormPostValues, $Conversation = NULL) { $Session = Gdn::Session(); // Define the primary key in this model's table. $this->DefineSchema(); // Add & apply any extra validation rules: $this->Validation->ApplyRule('Body', 'Required'); $this->AddInsertFields($FormPostValues); // Validate the form posted values $MessageID = FALSE; if ($this->Validate($FormPostValues)) { $Fields = $this->Validation->SchemaValidationFields(); // All fields on the form that relate to the schema TouchValue('Format', $Fields, C('Garden.InputFormatter', 'Html')); $MessageID = $this->SQL->Insert($this->Name, $Fields); $this->LastMessageID = $MessageID; $ConversationID = ArrayValue('ConversationID', $Fields, 0); if (!$Conversation) { $Conversation = $this->SQL->GetWhere('Conversation', array('ConversationID' => $ConversationID))->FirstRow(DATASET_TYPE_ARRAY); } // Get the new message count for the conversation. $SQLR = $this->SQL->Select('MessageID', 'count', 'CountMessages')->Select('MessageID', 'max', 'LastMessageID')->From('ConversationMessage')->Where('ConversationID', $ConversationID)->Get()->FirstRow(DATASET_TYPE_ARRAY); if (sizeof($SQLR)) { list($CountMessages, $LastMessageID) = array_values($SQLR); } else { return; } // Update the conversation's DateUpdated field. $DateUpdated = Gdn_Format::ToDateTime(); $this->SQL->Update('Conversation c')->Set('CountMessages', $CountMessages)->Set('LastMessageID', $LastMessageID)->Set('UpdateUserID', Gdn::Session()->UserID)->Set('DateUpdated', $DateUpdated)->Where('ConversationID', $ConversationID)->Put(); // Update the last message of the users that were previously up-to-date on their read messages. $this->SQL->Update('UserConversation uc')->Set('uc.LastMessageID', $MessageID)->Set('uc.DateConversationUpdated', $DateUpdated)->Where('uc.ConversationID', $ConversationID)->Where('uc.Deleted', '0')->Where('uc.CountReadMessages', $CountMessages - 1)->Where('uc.UserID <>', $Session->UserID)->Put(); // Update the date updated of the users that were not up-to-date. $this->SQL->Update('UserConversation uc')->Set('uc.DateConversationUpdated', $DateUpdated)->Where('uc.ConversationID', $ConversationID)->Where('uc.Deleted', '0')->Where('uc.CountReadMessages <>', $CountMessages - 1)->Where('uc.UserID <>', $Session->UserID)->Put(); // Update the sending user. $this->SQL->Update('UserConversation uc')->Set('uc.CountReadMessages', $CountMessages)->Set('Deleted', 0)->Set('uc.DateConversationUpdated', $DateUpdated)->Where('ConversationID', $ConversationID)->Where('UserID', $Session->UserID)->Put(); // Find users involved in this conversation $UserData = $this->SQL->Select('UserID')->Select('LastMessageID')->Select('Deleted')->From('UserConversation')->Where('ConversationID', $ConversationID)->Get()->Result(DATASET_TYPE_ARRAY); $UpdateCountUserIDs = array(); $NotifyUserIDs = array(); // Collapse for call to UpdateUserCache and ActivityModel. $InsertUserFound = FALSE; foreach ($UserData as $UpdateUser) { $LastMessageID = GetValue('LastMessageID', $UpdateUser); $UserID = GetValue('UserID', $UpdateUser); $Deleted = GetValue('Deleted', $UpdateUser); if ($UserID == GetValue('InsertUserID', $Fields)) { $InsertUserFound = TRUE; if ($Deleted) { $this->SQL->Put('UserConversation', array('Deleted' => 0, 'DateConversationUpdated' => $DateUpdated), array('ConversationID' => $ConversationID, 'UserID' => $UserID)); } } // Update unread for users that were up to date if ($LastMessageID == $MessageID) { $UpdateCountUserIDs[] = $UserID; } // Send activities to users that have not deleted the conversation if (!$Deleted) { $NotifyUserIDs[] = $UserID; } } if (!$InsertUserFound) { $UserConversation = array('UserID' => GetValue('InsertUserID', $Fields), 'ConversationID' => $ConversationID, 'LastMessageID' => $LastMessageID, 'CountReadMessages' => $CountMessages, 'DateConversationUpdated' => $DateUpdated); $this->SQL->Insert('UserConversation', $UserConversation); } if (sizeof($UpdateCountUserIDs)) { $ConversationModel = new ConversationModel(); $ConversationModel->UpdateUserUnreadCount($UpdateCountUserIDs, TRUE); } $ActivityModel = new ActivityModel(); foreach ($NotifyUserIDs as $NotifyUserID) { if ($Session->UserID == $NotifyUserID) { continue; } // don't notify self. // Notify the users of the new message. $ActivityID = $ActivityModel->Add($Session->UserID, 'ConversationMessage', '', $NotifyUserID, '', "/messages/{$ConversationID}#{$MessageID}", FALSE); $Story = GetValue('Body', $Fields, ''); if (C('Conversations.Subjects.Visible')) { $Story = ConcatSep("\n\n", GetValue('Subject', $Conversation, ''), $Story); } $ActivityModel->SendNotification($ActivityID, $Story); } } return $MessageID; }
/** * Get a record from the database. * * @param string $recordType The type of record to get. This is usually the un-prefixed table name of the record. * @param int $id The ID of the record. * @param bool $throw Whether or not to throw an exception if the record isn't found. * @return array|false Returns an array representation of the record or false if the record isn't found. * @throws Exception Throws an exception with a 404 code if the record isn't found and {@link $throw} is true. * @throws Gdn_UserException Throws an exception when {@link $recordType} is unknown. */ function getRecord($recordType, $id, $throw = false) { $Row = false; switch (strtolower($recordType)) { case 'discussion': $Model = new DiscussionModel(); $Row = $Model->getID($id); $Row->Url = DiscussionUrl($Row); $Row->ShareUrl = $Row->Url; if ($Row) { return (array) $Row; } break; case 'comment': $Model = new CommentModel(); $Row = $Model->getID($id, DATASET_TYPE_ARRAY); if ($Row) { $Row['Url'] = Url("/discussion/comment/{$id}#Comment_{$id}", true); $Model = new DiscussionModel(); $Discussion = $Model->getID($Row['DiscussionID']); if ($Discussion) { $Discussion->Url = DiscussionUrl($Discussion); $Row['ShareUrl'] = $Discussion->Url; $Row['Name'] = $Discussion->Name; $Row['Discussion'] = (array) $Discussion; } return $Row; } break; case 'activity': $Model = new ActivityModel(); $Row = $Model->getID($id, DATASET_TYPE_ARRAY); if ($Row) { $Row['Name'] = formatString($Row['HeadlineFormat'], $Row); $Row['Body'] = $Row['Story']; return $Row; } break; default: throw new Gdn_UserException('Unknown record type requested.'); } if ($throw) { throw NotFoundException(); } else { return false; } }
/** * * @param DiscussionController $Sender * @param array $Args */ public function DiscussionController_QnA_Create($Sender, $Args = array()) { $Comment = Gdn::SQL()->GetWhere('Comment', array('CommentID' => $Sender->Request->Get('commentid')))->FirstRow(DATASET_TYPE_ARRAY); if (!$Comment) { throw NotFoundException('Comment'); } $Discussion = Gdn::SQL()->GetWhere('Discussion', array('DiscussionID' => $Comment['DiscussionID']))->FirstRow(DATASET_TYPE_ARRAY); // Check for permission. if (!(Gdn::Session()->UserID == GetValue('InsertUserID', $Discussion) || Gdn::Session()->CheckPermission('Garden.Moderation.Manage'))) { throw PermissionException('Garden.Moderation.Manage'); } if (!Gdn::Session()->ValidateTransientKey($Sender->Request->Get('tkey'))) { throw PermissionException(); } switch ($Args[0]) { case 'accept': $QnA = 'Accepted'; break; case 'reject': $QnA = 'Rejected'; break; } if (isset($QnA)) { $DiscussionSet = array('QnA' => $QnA); $CommentSet = array('QnA' => $QnA); if ($QnA == 'Accepted') { $CommentSet['DateAccepted'] = Gdn_Format::ToDateTime(); $CommentSet['AcceptedUserID'] = Gdn::Session()->UserID; if (!$Discussion['DateAccepted']) { $DiscussionSet['DateAccepted'] = Gdn_Format::ToDateTime(); $DiscussionSet['DateOfAnswer'] = $Comment['DateInserted']; } } // Update the comment. Gdn::SQL()->Put('Comment', $CommentSet, array('CommentID' => $Comment['CommentID'])); // Update the discussion. if ($Discussion['QnA'] != $QnA && (!$Discussion['QnA'] || in_array($Discussion['QnA'], array('Unanswered', 'Answered', 'Rejected')))) { Gdn::SQL()->Put('Discussion', $DiscussionSet, array('DiscussionID' => $Comment['DiscussionID'])); } // Determine QnA change if ($Comment['QnA'] != $QnA) { $Change = 0; switch ($QnA) { case 'Rejected': $Change = -1; if ($Comment['QnA'] != 'Accepted') { $Change = 0; } break; case 'Accepted': $Change = 1; break; default: if ($Comment['QnA'] == 'Rejected') { $Change = 0; } if ($Comment['QnA'] == 'Accepted') { $Change = -1; } break; } } // Apply change effects if ($Change) { // Update the user $UserID = GetValue('InsertUserID', $Comment); $this->RecalculateUserQnA($UserID); // Update reactions if ($this->Reactions) { include_once Gdn::Controller()->FetchViewLocation('reaction_functions', '', 'plugins/Reactions'); $Rm = new ReactionModel(); // If there's change, reactions will take care of it $Rm->React('Comment', $Comment['CommentID'], 'AcceptAnswer'); } } // Record the activity. if ($QnA == 'Accepted') { $Activity = array('ActivityType' => 'AnswerAccepted', 'NotifyUserID' => $Comment['InsertUserID'], 'HeadlineFormat' => '{ActivityUserID,You} accepted {NotifyUserID,your} answer.', 'RecordType' => 'Comment', 'RecordID' => $Comment['CommentID'], 'Route' => CommentUrl($Comment, '/'), 'Emailed' => ActivityModel::SENT_PENDING, 'Notified' => ActivityModel::SENT_PENDING); $ActivityModel = new ActivityModel(); $ActivityModel->Save($Activity); } } Redirect("/discussion/comment/{$Comment['CommentID']}#Comment_{$Comment['CommentID']}"); }
function plgAfterSave(&$model) { $data = array(); App::import('Model', 'activity', 'jreviews'); App::import('Helper', 'routes', 'jreviews'); $Activity = new ActivityModel(); $Routes = RegisterClass::getInstance('RoutesHelper'); $data['Activity']['user_id'] = $this->c->_user->id; $data['Activity']['email'] = $this->c->_user->email; $data['Activity']['created'] = gmdate('Y-m-d H:i:s'); $data['Activity']['ipaddress'] = $this->c->ipaddress; $data['Activity']['activity_new'] = isset($model->data['insertid']) ? 1 : 0; switch ($this->activityModel->name) { case 'Claim': //Get the full listing info to create proper permalinks $listing = $this->c->Listing->findRow(array('conditions' => array('Listing.id = ' . (int) $model->data['Claim']['listing_id'])), array()); $permalink = $Routes->content('', $listing, array('return_url' => true)); $permalink = cmsFramework::makeAbsUrl($permalink); $data['Activity']['activity_type'] = 'claim'; $data['Activity']['listing_id'] = $model->data['Claim']['listing_id']; $data['Activity']['extension'] = 'com_content'; $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $permalink; $Activity->store($data); break; case 'Listing': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Listing']['created_by']) break; //Get the full listing info to create proper permalinks $listing = $this->c->Listing->findRow(array('conditions' => array('Listing.id = ' . (int) $model->data['Listing']['id']))); $permalink = $Routes->content('', $listing, array('return_url' => true)); $permalink = cmsFramework::makeAbsUrl($permalink); $data['Activity']['activity_type'] = 'listing'; $data['Activity']['email'] = Sanitize::getString($model->data, 'email'); $data['Activity']['listing_id'] = $model->data['Listing']['id']; $data['Activity']['extension'] = 'com_content'; $data['Activity']['permalink'] = $permalink; $Activity->store($data); break; case 'Review': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Review']['userid']) break; $data['Activity']['activity_type'] = 'review'; $data['Activity']['listing_id'] = $model->data['Review']['pid']; $data['Activity']['review_id'] = $model->data['Review']['id']; $data['Activity']['extension'] = $model->data['Review']['mode']; $data['Activity']['value'] = round(Sanitize::getVar($model->data, 'average_rating'), 0); $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'OwnerReply': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Listing']['created_by']) break; $data['Activity']['activity_type'] = 'owner_reply'; $data['Activity']['listing_id'] = $model->data['Listing']['listing_id']; $data['Activity']['review_id'] = $model->data['OwnerReply']['id']; $data['Activity']['extension'] = $model->data['Listing']['extension']; // Editing not yet implemented so all replies are new $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'Discussion': // Skip logging of admin actions on user listings // if($this->c->_user->id != $model->data['Discussion']['user_id']) break; // Get listing id and extension $this->c->_db->setQuery("\n SELECT \n Review.pid AS listing_id, Review.`mode` AS extension\n FROM \n #__jreviews_comments AS Review\n WHERE \n Review.id = " . $model->data['Discussion']['review_id']); // Get listing owner id and check if it matches the current user if ($listing = current($this->c->_db->loadAssocList())) { $data['Activity']['activity_type'] = 'review_discussion'; $data['Activity']['listing_id'] = $listing['listing_id']; $data['Activity']['review_id'] = $model->data['Discussion']['review_id']; $data['Activity']['post_id'] = $model->data['Discussion']['discussion_id']; $data['Activity']['extension'] = $listing['extension']; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); } break; case 'Report': $data['Activity']['activity_type'] = $model->data['Report']['post_id'] ? 'discussion_report' : 'review_report'; $data['Activity']['listing_id'] = $model->data['Report']['listing_id']; $data['Activity']['review_id'] = $model->data['Report']['review_id']; $data['Activity']['extension'] = $model->data['Report']['extension']; // Editing not yet implemented so all replies are new $data['Activity']['activity_new'] = 1; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); break; case 'Vote': // Get listing id and extension $this->c->_db->setQuery("\n SELECT \n Review.pid AS listing_id, Review.`mode` AS extension\n FROM \n #__jreviews_comments AS Review\n WHERE \n Review.id = " . $model->data['Vote']['review_id']); // Get listing owner id and check if it matches the current user if ($listing = current($this->c->_db->loadAssocList())) { $data['Activity']['activity_type'] = 'helpful_vote'; $data['Activity']['listing_id'] = $listing['listing_id']; $data['Activity']['review_id'] = $model->data['Vote']['review_id']; $data['Activity']['helpful_vote_id'] = $model->data['Vote']['vote_id']; $data['Activity']['extension'] = $listing['extension']; $data['Activity']['value'] = $model->data['Vote']['vote_yes']; $data['Activity']['permalink'] = $Routes->reviewDiscuss('', array('review_id' => $data['Activity']['review_id']), array('return_url' => true)); $Activity->store($data); } break; } $this->published = false; // Run once. With paid listings it is possible for a plugin to run a 2nd time when the order is processed together with the listing (free) }
/** * Add another user to the conversation. * * @since 2.0.0 * @access public * * @param int $ConversationID Unique ID of conversation effected. * @param int $UserID Unique ID of current user. */ public function AddUserToConversation($ConversationID, $UserID) { if (!is_array($UserID)) { $UserID = array($UserID); } // First define the current users in the conversation $OldContributorData = $this->GetRecipients($ConversationID); $OldContributorData = Gdn_DataSet::Index($OldContributorData, 'UserID'); $AddedUserIDs = array(); // Get some information about this conversation $ConversationData = $this->SQL->Select('LastMessageID')->Select('CountMessages')->From('Conversation')->Where('ConversationID', $ConversationID)->Get()->FirstRow(); // Add the user(s) if they are not already in the conversation foreach ($UserID as $NewUserID) { if (!array_key_exists($NewUserID, $OldContributorData)) { $AddedUserIDs[] = $NewUserID; $this->SQL->Insert('UserConversation', array('UserID' => $NewUserID, 'ConversationID' => $ConversationID, 'LastMessageID' => $ConversationData->LastMessageID, 'CountReadMessages' => 0, 'DateConversationUpdated' => $ConversationData['DateUpdated'])); } elseif ($OldContributorData[$NewUserID]->Deleted) { $AddedUserIDs[] = $NewUserID; $this->SQL->Put('UserConversation', array('Deleted' => 0), array('ConversationID' => $ConversationID, 'UserID' => $NewUserID)); } } if (count($AddedUserIDs) > 0) { $Session = Gdn::Session(); // Update the Contributors field on the conversation $Contributors = array_unique(array_merge($AddedUserIDs, array_keys($OldContributorData))); sort($Contributors); $this->SQL->Update('Conversation')->Set('Contributors', Gdn_Format::Serialize($Contributors))->Where('ConversationID', $ConversationID)->Put(); $ActivityModel = new ActivityModel(); foreach ($AddedUserIDs as $AddedUserID) { $ActivityModel->Queue(array('ActivityType' => 'AddedToConversation', 'NotifyUserID' => $AddedUserID, 'HeadlineFormat' => T('You were added to a conversation.', '{InsertUserID,user} added {NotifyUserID,you} to a <a href="{Url,htmlencode}">conversation</a>.')), 'ConversationMessage'); } $ActivityModel->SaveQueue(); $this->UpdateUserUnreadCount($AddedUserIDs); } }
/** * Registration that requires approval. * * Events: RegistrationPending * * @access private * @since 2.0.0 */ private function RegisterApproval() { Gdn::UserModel()->AddPasswordStrength($this); // If the form has been posted back... if ($this->Form->IsPostBack()) { // Add validation rules that are not enforced by the model $this->UserModel->DefineSchema(); $this->UserModel->Validation->ApplyRule('Name', 'Username', $this->UsernameError); $this->UserModel->Validation->ApplyRule('TermsOfService', 'Required', T('You must agree to the terms of service.')); $this->UserModel->Validation->ApplyRule('Password', 'Required'); $this->UserModel->Validation->ApplyRule('Password', 'Strength'); $this->UserModel->Validation->ApplyRule('Password', 'Match'); $this->UserModel->Validation->ApplyRule('DiscoveryText', 'Required', 'Tell us why you want to join!'); // $this->UserModel->Validation->ApplyRule('DateOfBirth', 'MinimumAge'); $this->FireEvent('RegisterValidation'); try { $Values = $this->Form->FormValues(); unset($Values['Roles']); $AuthUserID = $this->UserModel->Register($Values); if (!$AuthUserID) { $this->Form->SetValidationResults($this->UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. Gdn::Session()->Start($AuthUserID); if ($this->Form->GetFormValue('RememberMe')) { Gdn::Authenticator()->SetIdentity($AuthUserID, TRUE); } // Notification text $Label = T('NewApplicantEmail', 'New applicant:'); $Story = Anchor(Gdn_Format::Text($Label . ' ' . $Values['Name']), ExternalUrl('dashboard/user/applicants')); $this->EventArguments['AuthUserID'] = $AuthUserID; $this->EventArguments['Story'] =& $Story; $this->FireEvent('RegistrationPending'); $this->View = "RegisterThanks"; // Tell the user their application will be reviewed by an administrator. // Grab all of the users that need to be notified. $Data = Gdn::Database()->SQL()->GetWhere('UserMeta', array('Name' => 'Preferences.Email.Applicant'))->ResultArray(); $ActivityModel = new ActivityModel(); foreach ($Data as $Row) { $ActivityModel->Add($AuthUserID, 'Applicant', $Story, $Row['UserID'], '', '/dashboard/user/applicants', 'Only'); } } } catch (Exception $Ex) { $this->Form->AddError($Ex); } } $this->Render(); }
public function Notifications() { $this->Permission('Garden.SignIn.Allow'); $Session = Gdn::Session(); // Drop notification count back to zero. $SQL = Gdn::SQL(); $SQL->Update('User')->Set('CountNotifications', '0')->Where('UserID', $Session->UserID)->Put(); $ActivityModel = new ActivityModel(); $this->NotificationData = $ActivityModel->GetNotifications($Session->UserID); $this->Render(); }
/** * Record advanced notifications for users. * * @param ActivityModel $ActivityModel * @param array $Activity * @param array $Discussion * @param array $NotifiedUsers */ public function recordAdvancedNotications($ActivityModel, $Activity, $Discussion) { if (is_numeric($Discussion)) { $Discussion = $this->getID($Discussion); } $CategoryID = val('CategoryID', $Discussion); // Figure out the category that governs this notification preference. $i = 0; $Category = CategoryModel::categories($CategoryID); if (!$Category) { return; } while ($Category['Depth'] > 2 && $i < 20) { if (!$Category || $Category['Archived']) { return; } $i++; $Category = CategoryModel::categories($Category['ParentCategoryID']); } // Grab all of the users that need to be notified. $Data = $this->SQL->whereIn('Name', array('Preferences.Email.NewComment.' . $Category['CategoryID'], 'Preferences.Popup.NewComment.' . $Category['CategoryID']))->get('UserMeta')->resultArray(); $NotifyUsers = array(); foreach ($Data as $Row) { if (!$Row['Value']) { continue; } $UserID = $Row['UserID']; // Check user can still see the discussion. if (!Gdn::userModel()->GetCategoryViewPermission($UserID, $Category['CategoryID'])) { continue; } $Name = $Row['Name']; if (strpos($Name, '.Email.') !== false) { $NotifyUsers[$UserID]['Emailed'] = ActivityModel::SENT_PENDING; } elseif (strpos($Name, '.Popup.') !== false) { $NotifyUsers[$UserID]['Notified'] = ActivityModel::SENT_PENDING; } } foreach ($NotifyUsers as $UserID => $Prefs) { $Activity['NotifyUserID'] = $UserID; $Activity['Emailed'] = val('Emailed', $Prefs, false); $Activity['Notified'] = val('Notified', $Prefs, false); $ActivityModel->Queue($Activity); } }
//if ($SQL->getWhere('ActivityType', array('Name' => 'Banned'))->numRows() == 0) $SQL->replace('ActivityType', array('AllowComments' => '0', 'FullHeadline' => '%1$s banned %3$s.', 'ProfileHeadline' => '%1$s banned %3$s.', 'Notify' => '0', 'Public' => '1'), array('Name' => 'Banned'), true); //if ($SQL->getWhere('ActivityType', array('Name' => 'Unbanned'))->numRows() == 0) $SQL->replace('ActivityType', array('AllowComments' => '0', 'FullHeadline' => '%1$s un-banned %3$s.', 'ProfileHeadline' => '%1$s un-banned %3$s.', 'Notify' => '0', 'Public' => '1'), array('Name' => 'Unbanned'), true); // Applicant activity if ($SQL->getWhere('ActivityType', array('Name' => 'Applicant'))->numRows() == 0) { $SQL->insert('ActivityType', array('AllowComments' => '0', 'Name' => 'Applicant', 'FullHeadline' => '%1$s applied for membership.', 'ProfileHeadline' => '%1$s applied for membership.', 'Notify' => '1', 'Public' => '0')); } $WallPostType = $SQL->getWhere('ActivityType', array('Name' => 'WallPost'))->firstRow(DATASET_TYPE_ARRAY); if (!$WallPostType) { $WallPostTypeID = $SQL->insert('ActivityType', array('AllowComments' => '1', 'ShowIcon' => '1', 'Name' => 'WallPost', 'FullHeadline' => '%3$s wrote on %2$s %5$s.', 'ProfileHeadline' => '%3$s wrote:')); $WallCommentTypeID = $SQL->getWhere('ActivityType', array('Name' => 'WallComment'))->value('ActivityTypeID'); // Update all old wall comments to wall posts. $SQL->update('Activity')->set('ActivityTypeID', $WallPostTypeID)->set('ActivityUserID', 'RegardingUserID', false)->set('RegardingUserID', 'InsertUserID', false)->where('ActivityTypeID', $WallCommentTypeID)->where('RegardingUserID is not null')->put(); } $ActivityModel = new ActivityModel(); $ActivityModel->defineType('Default'); $ActivityModel->defineType('Registration'); $ActivityModel->defineType('Status'); $ActivityModel->defineType('Ban'); // Message Table $Construct->table('Message')->primaryKey('MessageID')->column('Content', 'text')->column('Format', 'varchar(20)', true)->column('AllowDismiss', 'tinyint(1)', '1')->column('Enabled', 'tinyint(1)', '1')->column('Application', 'varchar(255)', true)->column('Controller', 'varchar(255)', true)->column('Method', 'varchar(255)', true)->column('CategoryID', 'int', true)->column('IncludeSubcategories', 'tinyint', '0')->column('AssetTarget', 'varchar(20)', true)->column('CssClass', 'varchar(20)', true)->column('Sort', 'int', true)->set($Explicit, $Drop); $Prefix = $SQL->Database->DatabasePrefix; if ($PhotoIDExists && !$PhotoExists) { $Construct->query("update {$Prefix}User u\n join {$Prefix}Photo p\n on u.PhotoID = p.PhotoID\n set u.Photo = p.Name"); } if ($PhotoIDExists) { $Construct->table('User')->dropColumn('PhotoID'); } $Construct->table('Tag'); $FullNameColumnExists = $Construct->columnExists('FullName');
/** * A convenience function that allows adding to the activity table with a single line. */ function AddActivity($ActivityUserID, $ActivityType, $Story = '', $RegardingUserID = '', $Route = '', $SendEmail = '') { $ActivityModel = new ActivityModel(); return $ActivityModel->Add($ActivityUserID, $ActivityType, $Story, $RegardingUserID, '', $Route, $SendEmail); }
/** * Approve a membership applicant. * * @param int $UserID * @param string $Email * @return bool * @throws Exception */ public function approve($UserID, $Email) { $applicantRoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_APPLICANT); // Make sure the $UserID is an applicant $RoleData = $this->getRoles($UserID); if ($RoleData->numRows() == 0) { throw new Exception(t('ErrorRecordNotFound')); } else { $AppRoles = $RoleData->result(DATASET_TYPE_ARRAY); $ApplicantFound = false; foreach ($AppRoles as $AppRole) { if (in_array(val('RoleID', $AppRole), $applicantRoleIDs)) { $ApplicantFound = true; } } } if ($ApplicantFound) { // Retrieve the default role(s) for new users $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER); // Wipe out old & insert new roles for this user $this->saveRoles($UserID, $RoleIDs, false); // Send out a notification to the user $User = $this->getID($UserID); if ($User) { $Email = new Gdn_Email(); $Email->subject(sprintf(t('[%1$s] Membership Approved'), c('Garden.Title'))); $Email->to($User->Email); $message = sprintf(t('Hello %s!'), val('Name', $User)) . ' ' . t('You have been approved for membership.'); $emailTemplate = $Email->getEmailTemplate()->setMessage($message)->setButton(externalUrl(signInUrl()), t('Sign In Now'))->setTitle(t('Membership Approved')); $Email->setEmailTemplate($emailTemplate); try { $Email->send(); } catch (Exception $e) { if (debug()) { throw $e; } } // Report that the user was approved. $ActivityModel = new ActivityModel(); $ActivityModel->save(['ActivityUserID' => $UserID, 'ActivityType' => 'Registration', 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')], false, ['GroupBy' => 'ActivityTypeID']); // Report the approval for moderators. $ActivityModel->save(['ActivityType' => 'Registration', 'ActivityUserID' => Gdn::session()->UserID, 'RegardingUserID' => $UserID, 'NotifyUserID' => ActivityModel::NOTIFY_MODS, 'HeadlineFormat' => t('HeadlineFormat.RegistrationApproval', '{ActivityUserID,user} approved the applications for {RegardingUserID,user}.')], false, ['GroupBy' => ['ActivityTypeID', 'ActivityUserID']]); Gdn::userModel()->saveAttribute($UserID, 'ApprovedByUserID', Gdn::session()->UserID); } } return true; }
public function Save2($CommentID, $Insert, $CheckExisting = TRUE) { $Fields = $this->GetID($CommentID, DATASET_TYPE_ARRAY); $Session = Gdn::Session(); // Make a quick check so that only the user making the comment can make the notification. // This check may be used in the future so should not be depended on later in the method. if ($Fields['InsertUserID'] != $Session->UserID) { return; } $DiscussionModel = new DiscussionModel(); $DiscussionID = ArrayValue('DiscussionID', $Fields); $Discussion = $DiscussionModel->GetID($DiscussionID); if ($Insert) { // Notify any users who were mentioned in the comment $Usernames = GetMentions($Fields['Body']); $UserModel = Gdn::UserModel(); $Story = ArrayValue('Body', $Fields, ''); $NotifiedUsers = array(); foreach ($Usernames as $Username) { $User = $UserModel->GetByUsername($Username); if ($User && $User->UserID != $Session->UserID) { $NotifiedUsers[] = $User->UserID; $ActivityModel = new ActivityModel(); $ActivityID = $ActivityModel->Add($Session->UserID, 'CommentMention', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $User->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE); $ActivityModel->SendNotification($ActivityID, $Story); } } // Notify users who have bookmarked the discussion $BookmarkData = $DiscussionModel->GetBookmarkUsers($DiscussionID); foreach ($BookmarkData->Result() as $Bookmark) { if (!in_array($Bookmark->UserID, $NotifiedUsers) && $Bookmark->UserID != $Session->UserID) { $NotifiedUsers[] = $Bookmark->UserID; $ActivityModel = new ActivityModel(); $ActivityID = $ActivityModel->Add($Session->UserID, 'BookmarkComment', Anchor(Gdn_Format::Text($Discussion->Name), 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID), $Bookmark->UserID, '', 'discussion/comment/' . $CommentID . '/#Comment_' . $CommentID, FALSE); $ActivityModel->SendNotification($ActivityID, $Story); } } // Record user-comment activity if ($Discussion !== FALSE && !in_array($Session->UserID, $NotifiedUsers)) { $this->RecordActivity($Discussion, $Session->UserID, $CommentID, 'Only'); } } $this->UpdateCommentCount($DiscussionID); // Mark the comment read (note: add 1 to $Discussion->CountComments because this comment has been added since $Discussion was loaded) $this->SetWatch($Discussion, $Discussion->CountComments, $Discussion->CountComments + 1, $Discussion->CountComments + 1); // Update the discussion author's CountUnreadDiscussions (ie. // the number of discussions created by the user that s/he has // unread messages in) if this comment was not added by the // discussion author. $Data = $this->SQL->Select('d.InsertUserID')->Select('d.DiscussionID', 'count', 'CountDiscussions')->From('Discussion d')->Join('Comment c', 'd.DiscussionID = c.DiscussionID')->Join('UserDiscussion w', 'd.DiscussionID = w.DiscussionID and w.UserID = d.InsertUserID')->Where('w.CountComments >', 0)->Where('c.InsertUserID', $Session->UserID)->Where('c.InsertUserID <>', 'd.InsertUserID', TRUE, FALSE)->GroupBy('d.InsertUserID')->Get(); if ($Data->NumRows() > 0) { $UserData = $Data->FirstRow(); $this->SQL->Update('User')->Set('CountUnreadDiscussions', $UserData->CountDiscussions)->Where('UserID', $UserData->InsertUserID)->Put(); } $this->UpdateUser($Session->UserID); }
/** * * * @param bool $Notify * @param bool $UserID */ public function post($Notify = false, $UserID = false) { if (is_numeric($Notify)) { $UserID = $Notify; $Notify = false; } if (!$UserID) { $UserID = Gdn::session()->UserID; } switch ($Notify) { case 'mods': $this->permission('Garden.Moderation.Manage'); $NotifyUserID = ActivityModel::NOTIFY_MODS; break; case 'admins': $this->permission('Garden.Settings.Manage'); $NotifyUserID = ActivityModel::NOTIFY_ADMINS; break; default: $this->permission('Garden.Profiles.Edit'); $NotifyUserID = ActivityModel::NOTIFY_PUBLIC; break; } $Activities = array(); if ($this->Form->authenticatedPostBack()) { $Data = $this->Form->formValues(); $Data = $this->ActivityModel->filterForm($Data); if (!isset($Data['Format']) || strcasecmp($Data['Format'], 'Raw') == 0) { $Data['Format'] = c('Garden.InputFormatter'); } if ($UserID != Gdn::session()->UserID) { // This is a wall post. $Activity = array('ActivityType' => 'WallPost', 'ActivityUserID' => $UserID, 'RegardingUserID' => Gdn::session()->UserID, 'HeadlineFormat' => t('HeadlineFormat.WallPost', '{RegardingUserID,you} → {ActivityUserID,you}'), 'Story' => $Data['Comment'], 'Format' => $Data['Format'], 'Data' => array('Bump' => true)); } else { // This is a status update. $Activity = array('ActivityType' => 'Status', 'HeadlineFormat' => t('HeadlineFormat.Status', '{ActivityUserID,user}'), 'Story' => $Data['Comment'], 'Format' => $Data['Format'], 'NotifyUserID' => $NotifyUserID, 'Data' => array('Bump' => true)); $this->setJson('StatusMessage', Gdn_Format::plainText($Activity['Story'], $Activity['Format'])); } $Activity = $this->ActivityModel->save($Activity, false, array('CheckSpam' => true)); if ($Activity == SPAM || $Activity == UNAPPROVED) { $this->StatusMessage = t('ActivityRequiresApproval', 'Your post will appear after it is approved.'); $this->render('Blank', 'Utility'); return; } if ($Activity) { if ($UserID == Gdn::session()->UserID && $NotifyUserID == ActivityModel::NOTIFY_PUBLIC) { Gdn::userModel()->setField(Gdn::session()->UserID, 'About', Gdn_Format::plainText($Activity['Story'], $Activity['Format'])); } $Activities = array($Activity); ActivityModel::joinUsers($Activities); $this->ActivityModel->calculateData($Activities); } else { $this->Form->setValidationResults($this->ActivityModel->validationResults()); $this->StatusMessage = $this->ActivityModel->Validation->resultsText(); // $this->render('Blank', 'Utility'); } } if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $Target = $this->Request->get('Target', '/activity'); if (isSafeUrl($Target)) { redirect($Target); } else { redirect(url('/activity')); } } $this->setData('Activities', $Activities); $this->render('Activities'); }