Example #1
0
 /**
  * Adds this new notification object to the backend storage.
  */
 protected function insert()
 {
     global $wgEchoBackend, $wgEchoNotifications;
     $row = array('notification_event' => $this->event->getId(), 'notification_user' => $this->user->getId(), 'notification_anon_ip' => $this->user->isAnon() ? $this->user->getName() : $this->user->getId(), 'notification_timestamp' => $this->timestamp, 'notification_read_timestamp' => $this->readTimestamp, 'notification_bundle_hash' => '', 'notification_bundle_display_hash' => '');
     // Get the bundle key for this event if web bundling is enabled
     $bundleKey = '';
     if (!empty($wgEchoNotifications[$this->event->getType()]['bundle']['web'])) {
         wfRunHooks('EchoGetBundleRules', array($this->event, &$bundleKey));
     }
     if ($bundleKey) {
         $hash = md5($bundleKey);
         $row['notification_bundle_hash'] = $hash;
         $lastStat = $wgEchoBackend->getLastBundleStat($this->user, $hash);
         // Use a new display hash if:
         // 1. there was no last bundle notification
         // 2. last bundle notification with the same hash was read
         if ($lastStat && !$lastStat->notification_read_timestamp) {
             $row['notification_bundle_display_hash'] = $lastStat->notification_bundle_display_hash;
         } else {
             $row['notification_bundle_display_hash'] = md5($bundleKey . '-display-hash-' . wfTimestampNow());
         }
     }
     $wgEchoBackend->createNotification($row);
     wfRunHooks('EchoCreateNotificationComplete', array($this));
 }
 /**
  * Sends out the "you have advanced to level [fill in this]" messages to the users
  *
  * @param $userIdTo Integer: user ID of the receiver
  * @param $level Mixed: name of the level that the user advanced to
  */
 public function sendAdvancementNotificationEmail($userIdTo, $level)
 {
     $user = User::newFromId($userIdTo);
     $user->loadFromDatabase();
     // send echo notification
     $userpage = $user->getUserPage();
     EchoEvent::create(array('type' => 'advancement', 'extra' => array('advancement-user-id' => $userIdTo, 'new-level' => $level), 'title' => $userpage));
     // if ( $user->isEmailConfirmed() && $user->getIntOption( 'notifyhonorifics', 1 ) ) {
     // 	$updateProfileLink = SpecialPage::getTitleFor( 'UpdateProfile' );
     // 	$subject = wfMessage( 'level-advance-subject', $level )->text();
     // 	if ( trim( $user->getRealName() ) ) {
     // 		$name = $user->getRealName();
     // 	} else {
     // 		$name = $user->getName();
     // 	}
     // 	$body = wfMessage( 'level-advance-body',
     // 		$name,
     // 		$level,
     // 		$updateProfileLink->getFullURL()
     // 	)->text();
     // 	// The email contains HTML, so actually send it out as such, too.
     // 	// That's why this no longer uses User::sendMail().
     // 	// @see https://bugzilla.wikimedia.org/show_bug.cgi?id=68045
     // 	global $wgPasswordSender;
     // 	$sender = new MailAddress( $wgPasswordSender,
     // 		wfMessage( 'emailsender' )->inContentLanguage()->text() );
     // 	$to = new MailAddress( $user );
     // 	UserMailer::send( $to, $sender, $subject, $body, null, 'text/html; charset=UTF-8' );
     // }
 }
Example #3
0
 /**
  * Sends an <s>email</s>/echo to a user if someone wrote on their board.
  *
  * @param $user_id_to Integer: user ID of the reciever
  * @param $user_from Mixed: the user name of the person who wrote the board message
  */
 public function sendBoardNotificationEmail($user_id_to, $user_from, $message)
 {
     $user = User::newFromId($user_id_to);
     $user->loadFromId();
     $agent = User::newFromName($user_from);
     // send an echo notification
     $board_link = SpecialPage::getTitleFor('UserBoard');
     $username = $user->getName();
     EchoEvent::create(array('type' => 'board-msg', 'extra' => array('board-user-id' => $user_id_to, 'board-user' => $username, 'board-user-conv' => $user_from, 'board-content' => $message), 'agent' => $agent, 'title' => $board_link));
     // // Send email if user's email is confirmed and s/he's opted in to recieving social notifications
     // if ( $user->isEmailConfirmed() && $user->getIntOption( 'notifymessage', 1 ) ) {
     // 	$board_link = SpecialPage::getTitleFor( 'UserBoard' );
     // 	$update_profile_link = SpecialPage::getTitleFor( 'UpdateProfile' );
     // 	$subject = wfMessage( 'message_received_subject', $user_from )->parse();
     // 	$body = wfMessage( 'message_received_body',
     // 		$user->getName(),
     // 		$user_from,
     // 		htmlspecialchars( $board_link->getFullURL() ),
     // 		htmlspecialchars( $update_profile_link->getFullURL() )
     // 	)->text();
     // 	// The email contains HTML, so actually send it out as such, too.
     // 	// That's why this no longer uses User::sendMail().
     // 	// @see https://bugzilla.wikimedia.org/show_bug.cgi?id=68045
     // 	global $wgPasswordSender;
     // 	$sender = new MailAddress( $wgPasswordSender,
     // 		wfMessage( 'emailsender' )->inContentLanguage()->text() );
     // 	$to = new MailAddress( $user );
     // 	UserMailer::send( $to, $sender, $subject, $body, null, 'text/html; charset=UTF-8' );
     // }
 }
 /** add a user follow site action to the database.
  *
  *  @param $follower User object: the user who initiates the follow
  *  @param $followee User object: the user to be followed
  *	@return mixed: false if unsuccessful, id if successful
  */
 public function addUserUserFollow($follower, $followee)
 {
     if ($follower == null || $followee == null) {
         return false;
     }
     if ($follower == $followee) {
         return false;
     }
     if ($this->checkUserUserFollow($follower, $followee) != false) {
         return 0;
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->insert('user_user_follow', array('f_user_id' => $follower->getId(), 'f_user_name' => $follower->getName(), 'f_target_user_id' => $followee->getId(), 'f_target_user_name' => $followee->getName(), 'f_date' => date('Y-m-d H:i:s')), __METHOD__);
     $followId = $dbw->insertId();
     $this->incFollowCount($follower, $followee);
     $stats = new UserStatsTrack($follower->getId(), $follower->getName());
     $stats->incStatField('friend');
     //use friend record to count the number of people followed.
     $stats = new UserStatsTrack($followee->getId(), $followee->getName());
     $stats->incStatField('foe');
     // use foe record to count the number of people following.
     // TODO: Notify the followee?
     EchoEvent::create(array('type' => 'follow-msg', 'extra' => array('followee-user-id' => $followee->getId(), 'agent-page' => $follower->getUserPage()), 'agent' => $follower, 'title' => $followee->getUserPage()));
     return $followId;
 }
Example #5
0
 /**
  * Retrieve the base event for email bundling, the one with the largest eeb_id
  * @return bool
  */
 protected function retrieveBaseEvent()
 {
     $dbr = MWEchoDbFactory::getDB(DB_SLAVE);
     $res = $dbr->selectRow(array('echo_email_batch'), array('eeb_event_id'), array('eeb_user_id' => $this->mUser->getId(), 'eeb_event_hash' => $this->bundleHash), __METHOD__, array('ORDER BY' => 'eeb_event_priority DESC, eeb_id DESC', 'LIMIT' => 1));
     if (!$res) {
         return false;
     }
     $this->baseEvent = EchoEvent::newFromId($res->eeb_event_id);
     return true;
 }
 /**
  * @param EchoEvent $event
  * @param $param
  * @param Message $message
  * @param User $user
  */
 protected function processParam($event, $param, $message, $user)
 {
     if ($param === 'content-page') {
         if ($event->getTitle()) {
             $message->params($event->getTitle()->getSubjectPage()->getPrefixedText());
         } else {
             $message->params('');
         }
     } elseif ($param === 'subject-link') {
         $this->setTitleLink($event, $message);
         // The title text without namespace
     } elseif ($param === 'main-title-text') {
         if (!$event->getTitle()) {
             $message->params($this->getMessage('echo-no-title')->text());
         } else {
             $message->params($event->getTitle()->getText());
         }
     } else {
         parent::processParam($event, $param, $message, $user);
     }
 }
 /**
  * Get a list of notifications based on the passed parameters
  *
  * @param $user User the user to get notifications for
  * @param $format string/bool false to not format any notifications, string to a specific output format
  * @param $limit int The maximum number of notifications to return
  * @param $continue string Used for offset
  * @return array
  */
 public static function getNotifications($user, $format = false, $limit = 20, $continue = null)
 {
     global $wgEchoBackend;
     $output = array();
     // TODO: Make 'web' based on a new API param?
     $res = $wgEchoBackend->loadNotifications($user, $limit, $continue, 'web');
     foreach ($res as $row) {
         $event = EchoEvent::newFromRow($row);
         if ($row->notification_bundle_base && $row->notification_bundle_display_hash) {
             $event->setBundleHash($row->notification_bundle_display_hash);
         }
         $timestampMw = self::getUserLocalTime($user, $row->notification_timestamp);
         // Start creating date section header
         $now = wfTimestamp();
         $dateFormat = substr($timestampMw, 0, 8);
         if (substr(self::getUserLocalTime($user, $now), 0, 8) === $dateFormat) {
             // 'Today'
             $date = wfMessage('echo-date-today')->escaped();
         } elseif (substr(self::getUserLocalTime($user, $now - 86400), 0, 8) === $dateFormat) {
             // 'Yesterday'
             $date = wfMessage('echo-date-yesterday')->escaped();
         } else {
             // 'May 10' or '10 May' (depending on user's date format preference)
             $lang = RequestContext::getMain()->getLanguage();
             $dateFormat = $lang->getDateFormatString('pretty', $user->getDatePreference() ?: 'default');
             $date = $lang->sprintfDate($dateFormat, $timestampMw);
         }
         // End creating date section header
         $thisEvent = array('id' => $event->getId(), 'type' => $event->getType(), 'category' => $event->getCategory(), 'timestamp' => array('utcunix' => wfTimestamp(TS_UNIX, $row->notification_timestamp), 'unix' => self::getUserLocalTime($user, $row->notification_timestamp, TS_UNIX), 'mw' => $timestampMw, 'date' => $date));
         if ($event->getVariant()) {
             $thisEvent['variant'] = $event->getVariant();
         }
         if ($event->getTitle()) {
             $thisEvent['title'] = array('full' => $event->getTitle()->getPrefixedText(), 'namespace' => $event->getTitle()->getNSText(), 'namespace-key' => $event->getTitle()->getNamespace(), 'text' => $event->getTitle()->getText());
         }
         if ($event->getAgent()) {
             if ($event->userCan(Revision::DELETED_USER, $user)) {
                 $thisEvent['agent'] = array('id' => $event->getAgent()->getId(), 'name' => $event->getAgent()->getName());
             } else {
                 $thisEvent['agent'] = array('userhidden' => '');
             }
         }
         //if ( $row->notification_read_timestamp ) {
         $thisEvent['read'] = $row->notification_read_timestamp;
         //}
         if ($format) {
             $thisEvent['*'] = EchoNotificationController::formatNotification($event, $user, $format);
         }
         $output[$event->getID()] = $thisEvent;
     }
     return $output;
 }
Example #8
0
 /**
  * Function for logging the event for Schema:Echo
  * @param $user User being notified.
  * @param $event EchoEvent to log detail about.
  * @param $deliveryMethod string containing either 'web' or 'email'
  */
 public static function logSchemaEcho(User $user, EchoEvent $event, $deliveryMethod)
 {
     global $wgEchoConfig, $wgEchoNotifications;
     if (!$wgEchoConfig['eventlogging']['Echo']['enabled']) {
         // Only attempt event logging if Echo schema is enabled
         return;
     }
     // Notifications under system category should have -1 as sender id
     if ($event->getCategory() === 'system') {
         $sender = -1;
     } else {
         $agent = $event->getAgent();
         if ($agent) {
             $sender = $agent->isAnon() ? $agent->getName() : $agent->getId();
         } else {
             $sender = -1;
         }
     }
     if (isset($wgEchoNotifications[$event->getType()]['group'])) {
         $group = $wgEchoNotifications[$event->getType()]['group'];
     } else {
         $group = 'neutral';
     }
     $data = array('version' => $wgEchoConfig['version'], 'eventId' => $event->getId(), 'notificationType' => $event->getType(), 'notificationGroup' => $group, 'sender' => (string) $sender, 'recipientUserId' => $user->getId(), 'recipientEditCount' => (int) $user->getEditCount());
     // Add the source if it exists. (This is mostly for the Thanks extension.)
     $extra = $event->getExtra();
     if (isset($extra['source'])) {
         $data['eventSource'] = (string) $extra['source'];
     }
     if ($deliveryMethod == 'email') {
         $data['deliveryMethod'] = 'email';
     } else {
         // whitelist valid delivery methods so it is always valid
         $data['deliveryMethod'] = 'web';
     }
     // Add revision ID if it exists
     $rev = $event->getRevision();
     if ($rev) {
         $data['revisionId'] = $rev->getId();
     }
     self::actuallyLogTheEvent('Echo', $data);
 }
Example #9
0
 /**
  * Sends the (echo) notification about a new gift to the user who received the
  * gift, if the user wants notifications about new gifts and their e-mail
  * is confirmed.
  *
  * @param $user_id_to Integer: user ID of the receiver of the gift
  * @param $user_from Mixed: name of the user who sent the gift
  * @param $gift_id Integer: ID number of the given gift
  * @param $type Integer: gift type; unused
  */
 public function sendGiftNotificationEmail($user_id_to, $user_from, $gift_id, $type)
 {
     $gift = Gifts::getGift($gift_id);
     $user = User::newFromId($user_id_to);
     $user->loadFromDatabase();
     //send an echo notification
     $agent = User::newFromName($user_from);
     $giftsLink = SpecialPage::getTitleFor('ViewGift');
     EchoEvent::create(array('type' => 'gift-receive', 'extra' => array('gift-user-id' => $user_id_to, 'gift-id' => $gift_id), 'agent' => $agent, 'title' => $giftsLink));
     // if ( $user->isEmailConfirmed() && $user->getIntOption( 'notifygift', 1 ) ) {
     // 	$giftsLink = SpecialPage::getTitleFor( 'ViewGifts' );
     // 	$updateProfileLink = SpecialPage::getTitleFor( 'UpdateProfile' );
     // 	if ( trim( $user->getRealName() ) ) {
     // 		$name = $user->getRealName();
     // 	} else {
     // 		$name = $user->getName();
     // 	}
     // 	$subject = wfMessage( 'gift_received_subject',
     // 		$user_from,
     // 		$gift['gift_name']
     // 	)->parse();
     // 	$body = wfMessage( 'gift_received_body',
     // 		$name,
     // 		$user_from,
     // 		$gift['gift_name'],
     // 		$giftsLink->getFullURL(),
     // 		$updateProfileLink->getFullURL()
     // 	)->parse();
     // 	// The email contains HTML, so actually send it out as such, too.
     // 	// That's why this no longer uses User::sendMail().
     // 	// @see https://bugzilla.wikimedia.org/show_bug.cgi?id=68045
     // 	global $wgPasswordSender;
     // 	$sender = new MailAddress( $wgPasswordSender,
     // 		wfMessage( 'emailsender' )->inContentLanguage()->text() );
     // 	$to = new MailAddress( $user );
     // 	UserMailer::send( $to, $sender, $subject, $body, null, 'text/html; charset=UTF-8' );
     // }
 }
 public function execute()
 {
     if (!class_exists('EchoEvent')) {
         $this->error("Couldn't find EchoEvent class.\n", true);
     } elseif (!OpenStackNovaHost::validateHostname($this->getOption('instance'))) {
         $this->error("Instance hostname is invalid.\n", true);
     }
     $validActions = array('reboot', 'build');
     if (!in_array($this->getOption('action'), $validActions)) {
         $this->error("Unrecognised action.\n", true);
     }
     $dbw = wfGetDB(DB_MASTER);
     $result = $dbw->selectRow('openstack_notification_event', array('event_actor_id', 'event_project', 'event_instance_name'), array('event_action' => $this->getOption('action'), 'event_instance_host' => $this->getOption('instance')), __METHOD__);
     if (!$result) {
         $this->error("Lookup of temporary event info failed.\n", true);
     }
     $successful = EchoEvent::create(array('type' => 'osm-instance-' . $this->getOption('action') . '-completed', 'title' => Title::newFromText($result->event_project, NS_NOVA_RESOURCE), 'agent' => User::newFromId($result->event_actor_id), 'extra' => array('instanceName' => $result->event_instance_name, 'projectName' => $result->event_project, 'notifyAgent' => true)));
     if ($successful) {
         $dbw->delete('openstack_notification_event', array('event_action' => $this->getOption('action'), 'event_instance_host' => $this->getOption('instance'), 'event_instance_name' => $result->event_instance_name, 'event_project' => $result->event_project, 'event_actor_id' => $result->event_actor_id), __METHOD__);
         $this->output("Event created successfully.\n");
     } else {
         $this->error("Something went wrong creating the echo notification.\n", true);
     }
 }
 /**
  * Implements per-user whitelist sourced from a user wiki page
  *
  * @param $event EchoEvent The event to test for inclusion in whitelist
  * @param $user User The user that owns the whitelist
  * @return boolean True when the event agent is in the user whitelist
  */
 protected static function isWhitelistedByUser(EchoEvent $event, User $user)
 {
     global $wgEchoPerUserWhitelistFormat, $wgMemc;
     if ($wgEchoPerUserWhitelistFormat === null || !$event->getAgent()) {
         return false;
     }
     $userId = $user->getID();
     if ($userId === 0) {
         return false;
         // anonymous user
     }
     if (!isset(self::$userWhitelist[$userId])) {
         self::$userWhitelist[$userId] = new EchoContainmentSet();
         self::$userWhitelist[$userId]->addOnWiki(NS_USER, sprintf($wgEchoPerUserWhitelistFormat, $user->getName()), $wgMemc, wfMemcKey("echo_on_wiki_whitelist_" . $userId));
     }
     return self::$userWhitelist[$userId]->contains($event->getAgent()->getName());
 }
Example #12
0
 /**
  * Creates an EchoEvent from the database by ID
  *
  * @param $id int Event ID
  * @return EchoEvent
  */
 public static function newFromID($id)
 {
     $obj = new EchoEvent();
     $obj->loadFromID($id);
     return $obj;
 }
 /**
  *  Creates a link to the user page (user given by event)
  * @param EchoEvent $event
  * @param Message $message
  * @param type $props
  * @return type
  */
 public function setUserpageLink($event, $message, $props = array())
 {
     if (isset($props['created']) && $props['created']) {
         unset($props['created']);
         $aExtra = $event->getExtra();
         $oUser = User::newFromName($aExtra['user']);
         if (is_object($oUser)) {
             $title = $oUser->getUserPage();
         } else {
             $title = null;
         }
     } else {
         $title = $event->getAgent()->getUserPage();
     }
     if ($title === null) {
         $message->params("'''" . wfMessage('bs-echo-unknown-user') . "'''")->parse();
     } else {
         $this->buildLink($title, $message, $props, false);
     }
 }
Example #14
0
 public function runWelcome()
 {
     global $wgUser;
     wfProfileIn(__METHOD__);
     //set the variables (used to be in __construct() )
     $mUserId = $wgUser->getID();
     $mUserIP = wfGetIp();
     $mUserName = $wgUser->getName();
     $mAnon = $wgUser->isAnon();
     $mSysop = false;
     if ($mAnon) {
         return false;
     }
     $mUser = User::newFromId($mUserId);
     /**
      * fallback
      */
     if (!$mUser) {
         $mUser = User::newFromName($mUserName);
     }
     $oldValue = $wgErrorLog;
     $wgErrorLog = true;
     /**
      * overwrite $wgUser for ~~~~ expanding
      */
     $sysop = trim(wfMsgForContent("welcome-user"));
     if (!in_array($sysop, array("@disabled", "-"))) {
         $tmpUser = $wgUser;
         $wgUser = User::newFromName(self::WELCOMEUSER);
         $flags = 0;
         $bot_message = trim(wfMsgForContent("welcome-bot"));
         if ($bot_message == '@bot' || $wgUser && $wgUser->isAllowed('bot')) {
             $flags = EDIT_FORCE_BOT | EDIT_SUPPRESS_RC;
         } else {
             $flags = EDIT_SUPPRESS_RC;
         }
         if ($mUser && $mUser->getName() !== self::WELCOMEUSER) {
             /**
              * check again if talk page exists
              */
             $talkPage = $mUser->getUserPage()->getTalkPage();
             if ($talkPage) {
                 $mSysop = self::getLastSysop();
                 $gEG = $mSysop->getEffectiveGroups();
                 $isSysop = in_array('sysop', $gEG);
                 $isStaff = in_array('staff', $gEG);
                 unset($gEG);
                 $sysopPage = $mSysop->getUserPage()->getTalkPage();
                 $signature = self::expandSig();
                 $welcomeMsg = false;
                 $talkArticle = new Article($talkPage, 0);
                 if (!$talkArticle->exists()) {
                     /**
                      * now create user page (if not exists of course)
                      */
                     if (self::isEnabled("page-user")) {
                         $userPage = $mUser->getUserPage();
                         if ($userPage) {
                             $userArticle = new Article($userPage, 0);
                             if (!$userArticle->exists()) {
                                 $pageMsg = wfMsgForContent("welcome-user-page");
                                 $userArticle->doEdit($pageMsg, false, $flags);
                             }
                         }
                     }
                     if (self::isEnabled("message-user")) {
                         $key = "welcome-message-user";
                         $welcomeMsg = wfMsgExt($key, array("parsemag", "content"), array('', $sysopPage->getPrefixedText(), $signature, wfEscapeWikiText($mUser->getName())));
                     }
                     if ($welcomeMsg) {
                         global $wgLang;
                         $dateStr = $wgLang->timeanddate(wfTimestampNow());
                         $real_name = User::whoIsReal($mSysop->getID());
                         if ($real_name == "") {
                             $real_name = $mSysop->getName();
                         }
                         $comment = $welcomeMsg;
                         //add a hidden variable to id welcome user notifications for echo
                         $comment .= '<!--welcomeuser-->';
                         $formattedComment = wfMsg('postcomment_formatted_comment', $dateStr, $mSysop->getName(), $real_name, $comment);
                         $talkArticle->doEdit($formattedComment, wfMsgForContent("welcome-message-log"), $flags);
                         //notify via the echo notification system
                         if (class_exists('EchoEvent')) {
                             EchoEvent::create(array('type' => 'edit-user-talk', 'title' => $talkPage, 'agent' => $mSysop));
                         }
                     }
                 }
             }
         }
         $wgUser = $tmpUser;
         $wgErrorLog = $oldValue;
     }
     wfProfileOut(__METHOD__);
     return true;
 }
    function execute($par)
    {
        global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname;
        global $wgRequest, $wgSitename, $wgLanguageCode, $IP;
        global $wgScript, $wgFilterCallback, $wgScriptPath;
        $this->setHeaders();
        require_once "{$IP}/extensions/wikihow/EditPageWrapper.php";
        require_once "{$IP}/includes/EditPage.php";
        $target = isset($par) ? $par : $wgRequest->getVal('target');
        if (!$target) {
            $wgOut->addHTML("No target specified. In order to thank a group of authors, a page must be provided.");
            return;
        }
        $title = Title::newFromDBKey($target);
        $me = Title::makeTitle(NS_SPECIAL, "ThankAuthors");
        if (!$wgRequest->getVal('token')) {
            $sk = $wgUser->getSkin();
            $talk_page = $title->getTalkPage();
            $token = $this->getToken1();
            $thanks_msg = wfMsg('thank-you-kudos', $title->getFullURL(), wfMsg('howto', $title->getText()));
            // add the form HTML
            $wgOut->addHTML(<<<EOHTML
\t\t\t\t<script type='text/javascript'>
\t\t\t\t\tfunction submitThanks () {
\t\t\t\t\t\tvar message = \$('#details').val();
\t\t\t\t\t\tif(message == "") {
\t\t\t\t\t\t\talert("Please enter a message.");
\t\t\t\t\t\t\treturn false;
\t\t\t\t\t\t}
\t\t\t\t\t\tvar url = '{$me->getFullURL()}?token=' + \$('#token')[0].value + '&target=' + \$('#target')[0].value + '&details=' + \$('#details')[0].value;
\t\t\t\t\t\tvar form = \$('#thanks_form');
\t\t\t\t\t\tform.html(\$('#thanks_response').html());
\t\t\t\t\t\t\$.get(url);
\t\t\t\t\t\treturn true;
\t\t\t\t\t}
\t\t\t\t</script>

\t\t\t\t<div id="thanks_response" style="display:none;">{$thanks_msg}</div>
\t\t\t\t<div id="thanks_form"><div class="section_text">
EOHTML
);
            $wgOut->addWikiText(wfMsg('enjoyed-reading-article', $title->getFullText(), $talk_page->getFullText()));
            $wgOut->addHTML("<input id=\"target\" type=\"hidden\" name=\"target\" value=\"{$target}\"/>\n\t\t\t\t<input id=\"token\" type=\"hidden\" name=\"{$token}\" value=\"{$token}\"/>\n\t\t\t\t");
            $wgOut->addHTML("<br />\n\t\t\t\t<textarea style='width:98%;' id=\"details\" rows=\"5\" cols=\"100\" name=\"details\"></textarea><br/>\n\t\t\t\t<br /><button onclick='submitThanks();' class='button primary'>" . wfMsg('submit') . "</button>\n\t\t\t\t</div></div>");
        } else {
            // this is a post, accept the POST data and create the
            // Request article
            wfLoadExtensionMessages('PostComment');
            $wgOut->setArticleBodyOnly(true);
            $user = $wgUser->getName();
            $real_name = User::whoIsReal($wgUser->getID());
            if ($real_name == "") {
                $real_name = $user;
            }
            $dateStr = $wgLang->timeanddate(wfTimestampNow());
            $comment = $wgRequest->getVal("details");
            $text = $title->getFullText();
            wfDebug("STA: got text...");
            // filter out links
            $preg = "/[^\\s]*\\.[a-z][a-z][a-z]?[a-z]?/i";
            $matches = array();
            if (preg_match($preg, $comment, $matches) > 0) {
                $wgOut->addHTML(wfMsg('no_urls_in_kudos', $matches[0]));
                return;
            }
            $comment = strip_tags($comment);
            $formattedComment = wfMsg('postcomment_formatted_thanks', $dateStr, $user, $real_name, $comment, $text);
            wfDebug("STA: comment {$formattedComment}\n");
            wfDebug("STA: Checking blocks...");
            $tmp = "";
            if ($wgUser->isBlocked()) {
                $this->blockedIPpage();
                return;
            }
            if (!$wgUser->getID() && $wgWhitelistEdit) {
                $this->userNotLoggedInPage();
                return;
            }
            if ($target == "Spam-Blacklist") {
                $wgOut->readOnlyPage();
                return;
            }
            wfDebug("STA: checking read only\n");
            if (wfReadOnly()) {
                $wgOut->readOnlyPage();
                return;
            }
            wfDebug("STA: checking rate limiter\n");
            if ($wgUser->pingLimiter('userkudos')) {
                $wgOut->rateLimited();
                return;
            }
            wfDebug("STA: checking blacklist\n");
            if ($wgFilterCallback && $wgFilterCallback($title, $comment, "")) {
                // Error messages or other handling should be
                // performed by the filter function
                return;
            }
            wfDebug("STA: checking tokens\n");
            $usertoken = $wgRequest->getVal('token');
            $token1 = $this->getToken1();
            $token2 = $this->getToken2();
            if ($usertoken != $token1 && $usertoken != $token2) {
                wfDebug("STA: User kudos token doesn't match user: {$usertoken} token1: {$token1} token2: {$token2}");
                return;
            }
            wfDebug("STA: going through contributors\n");
            $article = new Article($title);
            //$contributors = $article->getContributors(0, 0, true);
            $contributors = ArticleAuthors::getAuthors($article->getID());
            foreach ($contributors as $k => $v) {
                $u = User::newFromName($k);
                $id = $u->getID();
                //$id = $c->getID();
                //$u = $c;
                wfDebug("STA: going through contributors {$u} {$id}\n");
                if ($id == "0") {
                    continue;
                }
                // forget the anon users.
                //notify via the echo notification system
                if (class_exists('EchoEvent')) {
                    EchoEvent::create(array('type' => 'kudos', 'title' => $title, 'extra' => array('kudoed-user-id' => $id), 'agent' => $wgUser));
                }
                $t = Title::newFromText("User_kudos:" . $u);
                $a = new Article($t);
                $update = $t->getArticleID() > 0;
                $text = "";
                if ($update) {
                    $text = $a->getContent(true);
                    $text .= "\n\n" . $formattedComment;
                    if ($wgFilterCallback && $wgFilterCallback($t, $text, $text)) {
                        // Error messages or other handling should be
                        // performed by the filter function
                        return;
                    }
                }
                if ($update) {
                    $a->updateArticle($text, "", true, false, false, '', false);
                } else {
                    $a->insertNewArticle($text, "", true, false, false, false, false);
                }
            }
            wfDebug("STA: done\n");
            $wgOut->addHTML("Done.");
            $wgOut->redirect('');
        }
    }
 /**
  * Submit the form parameters for the page config to the DB.
  *
  * @return mixed (true on success, error string on failure)
  */
 public function doSubmit()
 {
     # Double-check permissions
     if (!$this->isAllowed()) {
         return 'review_denied';
     }
     # We can only approve actual revisions...
     if ($this->getAction() === 'approve') {
         $rev = Revision::newFromTitle($this->page, $this->oldid);
         # Check for archived/deleted revisions...
         if (!$rev || $rev->getVisibility()) {
             return 'review_bad_oldid';
         }
         # Check for review conflicts...
         if ($this->lastChangeTime !== null) {
             // API uses null
             $lastChange = $this->oldFrev ? $this->oldFrev->getTimestamp() : '';
             if ($lastChange !== $this->lastChangeTime) {
                 return 'review_conflict_oldid';
             }
         }
         $status = $this->approveRevision($rev, $this->oldFrev);
         # We can only unapprove approved revisions...
     } elseif ($this->getAction() === 'unapprove') {
         # Check for review conflicts...
         if ($this->lastChangeTime !== null) {
             // API uses null
             $lastChange = $this->oldFrev ? $this->oldFrev->getTimestamp() : '';
             if ($lastChange !== $this->lastChangeTime) {
                 return 'review_conflict_oldid';
             }
         }
         # Check if we can find this flagged rev...
         if (!$this->oldFrev) {
             return 'review_not_flagged';
         }
         $status = $this->unapproveRevision($this->oldFrev);
     } elseif ($this->getAction() === 'reject') {
         $newRev = Revision::newFromTitle($this->page, $this->oldid);
         $oldRev = Revision::newFromTitle($this->page, $this->refid);
         # Do not mess with archived/deleted revisions
         if (!$oldRev || $oldRev->isDeleted(Revision::DELETED_TEXT)) {
             return 'review_bad_oldid';
         } elseif (!$newRev || $newRev->isDeleted(Revision::DELETED_TEXT)) {
             return 'review_bad_oldid';
         }
         # Check that the revs are in order
         if ($oldRev->getTimestamp() > $newRev->getTimestamp()) {
             return 'review_cannot_undo';
         }
         # Make sure we are only rejecting pending changes
         $srev = FlaggedRevision::newFromStable($this->page, FR_MASTER);
         if ($srev && $oldRev->getTimestamp() < $srev->getRevTimestamp()) {
             return 'review_cannot_reject';
             // not really a use case
         }
         $article = new WikiPage($this->page);
         # Get text with changes after $oldRev up to and including $newRev removed
         $new_text = $article->getUndoText($newRev, $oldRev);
         if ($new_text === false) {
             return 'review_cannot_undo';
         }
         $baseRevId = $newRev->isCurrent() ? $oldRev->getId() : 0;
         # Actually make the edit...
         $editStatus = $article->doEdit($new_text, $this->getComment(), 0, $baseRevId, $this->user);
         $status = $editStatus->isOK() ? true : 'review_cannot_undo';
         if ($editStatus->isOK() && class_exists('EchoEvent') && $editStatus->value['revision']) {
             $affectedRevisions = array();
             // revid -> userid
             $revisions = wfGetDB(DB_SLAVE)->select('revision', array('rev_id', 'rev_user'), array('rev_id <= ' . $newRev->getId(), 'rev_timestamp <= ' . $newRev->getTimestamp(), 'rev_id > ' . $oldRev->getId(), 'rev_timestamp > ' . $oldRev->getTimestamp(), 'rev_page' => $article->getId()), __METHOD__);
             foreach ($revisions as $row) {
                 $affectedRevisions[$row->rev_id] = $row->rev_user;
             }
             EchoEvent::create(array('type' => 'reverted', 'title' => $this->page, 'extra' => array('revid' => $editStatus->value['revision']->getId(), 'reverted-users-ids' => array_values($affectedRevisions), 'reverted-revision-ids' => array_keys($affectedRevisions), 'method' => 'flaggedrevs-reject'), 'agent' => $this->user));
         }
         # If this undid one edit by another logged-in user, update user tallies
         if ($status === true && $newRev->getParentId() == $oldRev->getId() && $newRev->getRawUser()) {
             if ($newRev->getRawUser() != $this->user->getId()) {
                 // no self-reverts
                 FRUserCounters::incCount($newRev->getRawUser(), 'revertedEdits');
             }
         }
     }
     # Watch page if set to do so
     if ($status === true) {
         if ($this->user->getOption('flaggedrevswatch') && !$this->page->userIsWatching()) {
             $this->user->addWatch($this->page);
         }
     }
     return $status;
 }
 /**
  * For an action taken on a talk page, notify users whose user pages
  * are linked.
  * @param $header string The subject line for the discussion.
  * @param $content string The content of the post, as a wikitext string.
  * @param $revision Revision object.
  * @param $agent User The user who made the comment.
  */
 public static function generateMentionEvents($header, $content, $revision, $agent)
 {
     $title = $revision->getTitle();
     if (!$title) {
         return;
     }
     $output = self::parseNonEditWikitext($content, new Article($title));
     $links = $output->getLinks();
     if (!isset($links[NS_USER]) || !is_array($links[NS_USER])) {
         return;
     }
     $mentionedUsers = array();
     $count = 0;
     foreach ($links[NS_USER] as $dbk => $page_id) {
         $user = User::newFromName($dbk);
         // we should not add user to 'mention' notification list if
         // 1. the user name is not valid
         // 2. the user mentions themselves
         // 3. the user is the owner of the talk page
         // 4. user is anonymous
         if (!$user || $user->isAnon() || $user->getId() == $revision->getUser() || $title->getNamespace() === NS_USER_TALK && $title->getDBkey() === $dbk) {
             continue;
         }
         $mentionedUsers[$user->getId()] = $user->getId();
         $count++;
         // This is an unbounded list, put a cap on the allowable mentioned user list
         if ($count > 100) {
             break;
         }
     }
     if (!$mentionedUsers) {
         return;
     }
     EchoEvent::create(array('type' => 'mention', 'title' => $title, 'extra' => array('content' => $content, 'section-title' => $header, 'revid' => $revision->getId(), 'mentioned-users' => $mentionedUsers), 'agent' => $agent));
 }
 /**
  * Handler for EchoGetDefaultNotifiedUsers hook.
  * @param EchoEvent $event EchoEvent to get implicitly subscribed users for
  * @param array &$users Array to append implicitly subscribed users to.
  * @return bool true in all cases
  */
 public static function onEchoGetDefaultNotifiedUsers($event, &$users)
 {
     switch ($event->getType()) {
         case 'bs-shoutbox-mention':
             $extra = $event->getExtra();
             if (!$extra || !isset($extra['mentioned-user-id'])) {
                 break;
             }
             $recipientId = $extra['mentioned-user-id'];
             //really ugly, but newFromId appears to be broken...
             $oDBr = wfGetDB(DB_SLAVE);
             $row = $oDBr->selectRow('user', '*', array('user_id' => (int) $recipientId));
             $recipient = User::newFromRow($row);
             $users[$recipientId] = $recipient;
             //$event->setExtra('username', $recipient->);
             break;
     }
     return true;
 }
 /**
  * Notify the user on the 100th published translation.
  */
 public static function hundredthTranslation(\User $recipient)
 {
     \EchoEvent::create(array('type' => 'cx-hundredth-translation', 'extra' => array('recipient' => $recipient->getId())));
 }
 /**
  * Returns a revision snippet
  * @param EchoEvent $event The event that the notification is for.
  * @param User $user The user to format the notification for.
  * @return String The revision snippet (or empty string)
  */
 public function getRevisionSnippet($event, $user)
 {
     $extra = $event->getExtra();
     if (!isset($extra['section-text']) || !$event->userCan(Revision::DELETED_TEXT, $user)) {
         return '';
     }
     $snippet = trim($extra['section-text']);
     return $snippet;
 }
 function onAccountCreated($user, $byEmail)
 {
     //default settings for new users that are different than default
     // $user->setOption( 'echo-subscriptions-web-kudos', true );
     // $user->saveSettings();
     //welcome new user!
     EchoEvent::create(array('type' => 'welcome', 'agent' => $user));
     return true;
 }
Example #22
0
 function editPage()
 {
     $user = MassMessage::getMessengerUser();
     $params = array('action' => 'edit', 'title' => $this->title->getPrefixedText(), 'section' => 'new', 'text' => $this->makeText(), 'notminor' => true, 'bot' => true, 'token' => $user->getEditToken());
     //XXCHANGEDXX [sc]
     //notify via the echo notification system
     if (class_exists('EchoEvent')) {
         if ($this->params['comment'][0]) {
             $agent = User::newFromName($this->params['comment'][0]);
         } else {
             $agent = $user;
             //default (yuck) to out bot name
         }
         EchoEvent::create(array('type' => 'edit-user-talk', 'title' => $this->title, 'agent' => $agent));
     }
     $this->makeAPIRequest($params);
 }
Example #23
0
 /**
  * Handler for ArticleRollbackComplete hook.
  * @see http://www.mediawiki.org/wiki/Manual:Hooks/ArticleRollbackComplete
  * @param $page WikiPage The article that was edited
  * @param $agent User The user who did the rollback
  * @param $newRevision Revision The revision the page was reverted back to
  * @param $oldRevision Revision The revision of the top edit that was reverted
  * @return bool true in all cases
  */
 static function onRollbackComplete($page, $agent, $newRevision, $oldRevision)
 {
     $victimId = $oldRevision->getUser();
     if ($victimId && !$oldRevision->getContent()->equals($newRevision->getContent())) {
         EchoEvent::create(array('type' => 'reverted', 'title' => $page->getTitle(), 'extra' => array('revid' => $page->getRevision()->getId(), 'reverted-user-id' => $victimId, 'reverted-revision-id' => $oldRevision->getId(), 'method' => 'rollback'), 'agent' => $agent));
     }
     return true;
 }
 /**
  * Don't send email notifications that are imported from LiquidThreads.  It will
  * still be in their web notifications (if enabled), but they will never be
  * notified via email (regardless of batching settings) for this particular
  * notification.
  *
  */
 public static function onEchoAbortEmailNotification(User $user, EchoEvent $event)
 {
     $extra = $event->getExtra();
     if (isset($extra['lqtThreadId']) && $extra['lqtThreadId'] !== null) {
         return false;
     }
     return true;
 }
 /**
  * Hook for email notification
  * @param User $user
  * @param EchoEvent $event
  * @return boolean
  */
 public function onEchoAbortEmailNotification($user, $event)
 {
     //New user notification is only for admins
     if ($event->getType() == 'bs-newuser') {
         if (!$user->isAllowed('wikiadmin')) {
             return false;
         }
     }
     return true;
 }
 /**
  * Helper function for getLink()
  *
  * @param EchoEvent $event
  * @param User $user The user receiving the notification
  * @param String $destination The destination type for the link
  * @return Array including target and query parameters
  */
 protected function getLinkParams($event, $user, $destination)
 {
     $target = null;
     $query = array();
     // Set up link parameters based on the destination (or pass to parent)
     switch ($destination) {
         case 'link-from-page':
             if ($this->bundleData['use-bundle']) {
                 if ($event->getTitle()) {
                     $target = SpecialPage::getTitleFor('WhatLinksHere', $event->getTitle()->getPrefixedText());
                 }
             } else {
                 $extra = self::extractExtra($event->getExtra());
                 if ($this->isTitleSet($extra)) {
                     $target = Title::newFromId($extra['link-from-page-id']);
                 }
             }
             break;
         default:
             return parent::getLinkParams($event, $user, $destination);
     }
     return array($target, $query);
 }
 public static function createDeletionEvent($instanceName, $project, $user)
 {
     if (class_exists('EchoEvent')) {
         EchoEvent::create(array('type' => 'osm-instance-deleted', 'title' => Title::newFromText($project, NS_NOVA_RESOURCE), 'agent' => $user, 'extra' => array('instanceName' => $instanceName, 'projectName' => $project)));
     }
 }
 /**
  * Add user to be notified on echo event
  * @param EchoEvent $event
  * @param array $users
  * @return bool
  */
 public static function onEchoGetDefaultNotifiedUsers($event, &$users)
 {
     switch ($event->getType()) {
         case 'cx-first-translation':
         case 'cx-tenth-translation':
         case 'cx-hundredth-translation':
             $extra = $event->getExtra();
             if (!isset($extra['recipient'])) {
                 break;
             }
             $recipientId = $extra['recipient'];
             $recipient = User::newFromId($recipientId);
             $users[$recipientId] = $recipient;
             break;
     }
     return true;
 }
 /**
  * @param  $formData
  * @param string $entryPoint
  * @return bool
  */
 function tryAddMemberSubmit($formData, $entryPoint = 'internal')
 {
     $project = new OpenStackNovaProject($formData['projectname']);
     $members = explode(',', $formData['member']);
     foreach ($members as $member) {
         $user = User::newFromName($member, 'usable');
         if (!$user) {
             $this->getOutput()->addWikiMsg('openstackmanager-failedtoadd', $formData['member'], $formData['projectname']);
             continue;
         }
         $success = $project->addMember($member);
         if ($success) {
             if (!$user->isAllowed('loginviashell')) {
                 # Grant user the shell right if they have
                 # successfully been added to a project
                 $user->addGroup('shell');
             }
             $this->getOutput()->addWikiMsg('openstackmanager-addedto', $formData['member'], $formData['projectname']);
             if (class_exists('EchoEvent')) {
                 EchoEvent::create(array('type' => 'osm-projectmembers-add', 'title' => Title::newFromText($formData['projectname'], NS_NOVA_RESOURCE), 'agent' => $this->getUser(), 'extra' => array('userAdded' => $user->getId())));
             }
         } else {
             $this->getOutput()->addWikiMsg('openstackmanager-failedtoadd', $formData['member'], $formData['projectname']);
         }
     }
     $out = '<br />';
     $out .= Linker::link($this->getPageTitle(), $this->msg('openstackmanager-backprojectlist')->escaped());
     $this->getOutput()->addHTML($out);
     return true;
 }
Example #30
0
 public static function onFlowThreadSpammed($post)
 {
     if ($post->userid === 0) {
         return true;
     }
     $poster = \User::newFromId($post->userid);
     $title = \Title::newFromId($post->pageid);
     \EchoEvent::create(array('type' => 'flowthread_spam', 'title' => $title, 'extra' => array('notifyAgent' => true, 'postid' => $post->id->getBin()), 'agent' => $poster));
     return true;
 }