3 * GNU Social - a federating social network
4 * Copyright (C) 2014, Free Software Foundation, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
24 * @maintainer Mikael Nordfeldth <mmn@hethane.se>
26 class FavoritePlugin extends ActivityVerbHandlerPlugin
28 protected $email_notify_fave = 1;
35 public function types()
40 public function verbs()
42 return array(ActivityVerb::FAVORITE, ActivityVerb::LIKE,
43 ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE);
46 public function onCheckSchema()
48 $schema = Schema::get();
49 $schema->ensureTable('fave', Fave::schemaDef());
53 public function initialize()
55 common_config_set('email', 'notify_fave', $this->email_notify_fave);
58 public function onStartUpgrade()
60 // This is a migration feature that will make sure we move
61 // certain User preferences to the Profile_prefs table.
62 // Introduced after commit b5fd2a048fc621ea05d756caba17275ab3dd0af4
63 // on Sun Jul 13 16:30:37 2014 +0200
65 $user->whereAdd('emailnotifyfav IS NOT NULL');
67 printfnq("Detected old User table (emailnotifyfav IS NOT NULL). Moving 'emailnotifyfav' property to Profile_prefs...");
68 // First we'll make sure Profile_prefs exists
69 $schema = Schema::get();
70 $schema->ensureTable('profile_prefs', Profile_prefs::schemaDef());
72 // Make sure we have our own tables setup properly
73 while ($user->fetch()) {
74 $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
76 $user->emailnotifyfav = 'null'; // flag this preference as migrated
83 public function onEndUpgrade()
85 printfnq("Ensuring all faves have a URI...");
88 $fave->whereAdd('uri IS NULL');
91 while ($fave->fetch()) {
94 $fave->query(sprintf('UPDATE fave '.
97 'WHERE user_id = %d '.
99 Fave::newUri($fave->user_id, $fave->notice_id, $fave->modified),
100 common_sql_date(strtotime($fave->modified)),
103 } catch (Exception $e) {
104 common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
112 public function onRouterInitialized(URLMapper $m)
115 $m->connect('main/favor', array('action' => 'favor'));
116 $m->connect('main/disfavor', array('action' => 'disfavor'));
118 if (common_config('singleuser', 'enabled')) {
119 $nickname = User::singleUserNickname();
121 $m->connect('favorites',
122 array('action' => 'showfavorites',
123 'nickname' => $nickname));
124 $m->connect('favoritesrss',
125 array('action' => 'favoritesrss',
126 'nickname' => $nickname));
128 $m->connect('favoritedrss', array('action' => 'favoritedrss'));
129 $m->connect('favorited/', array('action' => 'favorited'));
130 $m->connect('favorited', array('action' => 'favorited'));
132 $m->connect(':nickname/favorites',
133 array('action' => 'showfavorites'),
134 array('nickname' => Nickname::DISPLAY_FMT));
135 $m->connect(':nickname/favorites/rss',
136 array('action' => 'favoritesrss'),
137 array('nickname' => Nickname::DISPLAY_FMT));
141 $m->connect('api/favorites/create.:format',
142 array('action' => 'ApiFavoriteCreate'),
143 array('format' => '(xml|json)'));
144 $m->connect('api/favorites/destroy.:format',
145 array('action' => 'ApiFavoriteDestroy'),
146 array('format' => '(xml|json)'));
147 $m->connect('api/favorites/list.:format',
148 array('action' => 'ApiTimelineFavorites'),
149 array('format' => '(xml|json|rss|atom|as)'));
150 $m->connect('api/favorites/:id.:format',
151 array('action' => 'ApiTimelineFavorites'),
152 array('id' => Nickname::INPUT_FMT,
153 'format' => '(xml|json|rss|atom|as)'));
154 $m->connect('api/favorites.:format',
155 array('action' => 'ApiTimelineFavorites'),
156 array('format' => '(xml|json|rss|atom|as)'));
157 $m->connect('api/favorites/create/:id.:format',
158 array('action' => 'ApiFavoriteCreate'),
159 array('id' => '[0-9]+',
160 'format' => '(xml|json)'));
161 $m->connect('api/favorites/destroy/:id.:format',
162 array('action' => 'ApiFavoriteDestroy'),
163 array('id' => '[0-9]+',
164 'format' => '(xml|json)'));
167 $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
168 array('action' => 'AtomPubShowFavorite'),
169 array('profile' => '[0-9]+',
170 'notice' => '[0-9]+'));
172 $m->connect('api/statusnet/app/favorites/:profile.atom',
173 array('action' => 'AtomPubFavoriteFeed'),
174 array('profile' => '[0-9]+'));
176 // Required for qvitter API
177 $m->connect('api/statuses/favs/:id.:format',
178 array('action' => 'ApiStatusesFavs'),
179 array('id' => '[0-9]+',
180 'format' => '(xml|json)'));
183 // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
184 protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
186 assert($this->isMyActivity($act));
188 // If empty, we should've created it ourselves on our node.
189 if (!isset($options['created'])) {
190 $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
193 // We must have an objects[0] here because in isMyActivity we require the count to be == 1
194 $actobj = $act->objects[0];
196 $object = Fave::saveActivityObject($actobj, $stored);
200 // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
201 // with the other microapps/activityhandlers as well.
202 // Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
203 public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
205 if (!$this->isMyNotice($stored)) {
209 common_debug('Extending activity '.$stored->id.' with '.get_called_class());
210 $this->extendActivity($stored, $act, $scoped);
214 public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
216 Fave::extendActivity($stored, $act, $scoped);
219 public function activityObjectFromNotice(Notice $notice)
221 $fave = Fave::fromStored($notice);
222 return $fave->asActivityObject();
225 public function deleteRelated(Notice $notice)
228 $fave = Fave::fromStored($notice);
230 } catch (NoResultException $e) {
231 // Cool, no problem. We wanted to get rid of it anyway.
238 * Typically just used to fill out Twitter-compatible API status data.
240 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
242 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
244 if ($scoped instanceof Profile) {
245 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
247 $status['favorited'] = false;
252 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
254 $userdata['favourites_count'] = Fave::countByProfile($profile);
258 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
260 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
262 if ($scoped instanceof Profile) {
263 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
268 public function onNoticeDeleteRelated(Notice $notice)
270 parent::onNoticeDeleteRelated($notice);
272 // The below algorithm is because we want to delete fave
273 // activities on any notice which _has_ faves, and not as
274 // in the parent function only ones that _are_ faves.
277 $fave->notice_id = $notice->id;
280 while ($fave->fetch()) {
288 public function onProfileDeleteRelated(Profile $profile, array &$related)
291 $fave->user_id = $profile->id;
292 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
295 Fave::blowCacheForProfileId($profile->id);
299 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
301 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
302 Fave::fillFaves($notice_ids);
305 if ($scoped instanceof Profile) {
306 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
311 * show the "favorite" form in the notice options element
312 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
316 public function onStartShowNoticeOptionItems($nli)
318 if (Event::handle('StartShowFaveForm', array($nli))) {
319 $scoped = Profile::current();
320 if ($scoped instanceof Profile) {
321 if (Fave::existsForProfile($nli->notice, $scoped)) {
322 $disfavor = new DisfavorForm($nli->out, $nli->notice);
325 $favor = new FavorForm($nli->out, $nli->notice);
329 Event::handle('EndShowFaveForm', array($nli));
333 public function showNoticeListItem(NoticeListItem $nli)
337 public function openNoticeListItemElement(NoticeListItem $nli)
341 public function closeNoticeListItemElement(NoticeListItem $nli)
346 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
349 $fave->user_id = $uas->getUser()->id;
351 if (!empty($uas->after)) {
352 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
356 while ($fave->fetch()) {
357 $objs[] = clone($fave);
364 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
366 if ($nli instanceof ThreadedNoticeListSubItem) {
367 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
368 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
370 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
372 $threadActive = $item->show() || $threadActive;
376 public function onEndFavorNotice(Profile $actor, Notice $target)
379 $notice_author = $target->getProfile();
380 // Don't notify ourselves of our own favorite on our own notice,
381 // or if it's a remote user (since we don't know their email addresses etc.)
382 if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
385 $local_user = $notice_author->getUser();
386 mail_notify_fave($local_user, $actor, $target);
387 } catch (Exception $e) {
388 // Mm'kay, probably not a local user. Let's skip this favor notification.
393 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
394 * using the class FavCommand.
396 * @param string $cmd Command being run
397 * @param string $arg Rest of the message (including address)
398 * @param User $user User sending the message
399 * @param Command &$result The resulting command object to be run.
401 * @return boolean hook value
403 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
405 if ($result === false && $cmd == 'fav') {
409 list($other, $extra) = CommandInterpreter::split_arg($arg);
410 if (!empty($extra)) {
413 $result = new FavCommand($user, $other);
421 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
423 // TRANS: Help message for IM/SMS command "fav <nickname>".
424 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
425 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
426 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
430 * Are we allowed to perform a certain command over the API?
432 public function onCommandSupportedAPI(Command $cmd, &$supported)
434 $supported = $supported || $cmd instanceof FavCommand;
437 // Form stuff (settings etc.)
439 public function onEndEmailFormData(Action $action, Profile $scoped)
441 $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
443 $action->elementStart('li');
444 $action->checkbox('email-notify_fave',
445 // TRANS: Checkbox label in e-mail preferences form.
446 _('Send me email when someone adds my notice as a favorite.'),
448 $action->elementEnd('li');
453 public function onStartEmailSaveForm(Action $action, Profile $scoped)
455 $emailfave = $action->booleanintstring('email-notify_fave');
457 if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
458 // No need to update setting
461 } catch (NoResultException $e) {
462 // Apparently there's no previously stored setting, then continue to save it as it is now.
465 $scoped->setPref('email', 'notify_fave', $emailfave);
472 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
474 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
475 // TRANS: Menu item in personal group navigation menu.
476 _m('MENU','Favorites'),
477 // @todo i18n FIXME: Need to make this two messages.
478 // TRANS: Menu item title in personal group navigation menu.
479 // TRANS: %s is a username.
480 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
481 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
482 'nav_timeline_favorites');
485 public function onEndPublicGroupNav(Menu $menu)
487 if (!common_config('singleuser', 'enabled')) {
488 // TRANS: Menu item in search group navigation panel.
489 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
490 // TRANS: Menu item title in search group navigation panel.
491 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
495 public function onEndShowSections(Action $action)
497 if (!$action->isAction(array('all', 'public'))) {
501 if (!common_config('performance', 'high')) {
502 $section = new PopularNoticeSection($action, $action->getScoped());
507 protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
509 return Fave::existsForProfile($target, $scoped)
510 // TRANS: Page/dialog box title when a notice is marked as favorite already
511 ? _m('TITLE', 'Unmark notice as favorite')
512 // TRANS: Page/dialog box title when a notice is not marked as favorite
513 : _m('TITLE', 'Mark notice as favorite');
516 protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
518 if ($action->isPost()) {
519 // The below tests are only for presenting to the user. POSTs which inflict
520 // duplicate favorite entries are handled with AlreadyFulfilledException.
524 $exists = Fave::existsForProfile($target, $scoped);
525 $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
528 case $exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
529 case !$exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
530 common_redirect(common_local_url('activityverb',
531 array('id' => $target->getID(),
532 'verb' => ActivityUtils::resolveUri($expected_verb, true))));
535 // No need to redirect as we are on the correct action already.
541 protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
544 case ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
545 Fave::addNew($scoped, $target);
547 case ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
548 Fave::removeEntry($scoped, $target);
551 throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
556 protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
558 return Fave::existsForProfile($target, $scoped)
559 ? new DisfavorForm($action, $target)
560 : new FavorForm($action, $target);
563 public function onPluginVersion(array &$versions)
565 $versions[] = array('name' => 'Favorite',
566 'version' => GNUSOCIAL_VERSION,
567 'author' => 'Mikael Nordfeldth',
568 'homepage' => 'http://gnu.io/',
570 // TRANS: Plugin description.
571 _m('Favorites (likes) using ActivityStreams.'));
578 * Notify a user that one of their notices has been chosen as a 'fave'
580 * @param User $rcpt The user whose notice was faved
581 * @param Profile $sender The user who faved the notice
582 * @param Notice $notice The notice that was faved
586 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
588 if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
592 // This test is actually "if the sender is sandboxed"
593 if (!$sender->hasRight(Right::EMAILONFAVE)) {
597 if ($rcpt->hasBlocked($sender)) {
598 // If the author has blocked us, don't spam them with a notification.
602 // We need the global mail.php for various mail related functions below.
603 require_once INSTALLDIR.'/lib/mail.php';
605 $bestname = $sender->getBestName();
607 common_switch_locale($rcpt->language);
609 // TRANS: Subject for favorite notification e-mail.
610 // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
611 $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
613 // TRANS: Body for favorite notification e-mail.
614 // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
615 // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
616 // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
617 // TRANS: %7$s is the adding user's nickname.
618 $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
619 " as one of their favorites.\n\n" .
620 "The URL of your notice is:\n\n" .
622 "The text of your notice is:\n\n" .
624 "You can see the list of %1\$s's favorites here:\n\n" .
627 common_exact_date($notice->created),
628 common_local_url('shownotice',
629 array('notice' => $notice->id)),
631 common_local_url('showfavorites',
632 array('nickname' => $sender->getNickname())),
633 common_config('site', 'name'),
634 $sender->getNickname()) .
637 $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
639 common_switch_locale();
640 mail_to_user($rcpt, $subject, $body, $headers);