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 SharePlugin extends ActivityVerbHandlerPlugin
33 public function types()
38 public function verbs()
40 return array(ActivityVerb::SHARE);
43 public function onRouterInitialized(URLMapper $m)
46 $m->connect('main/repeat', array('action' => 'repeat'));
48 // Share for Twitter API ("Retweet")
49 $m->connect('api/statuses/retweeted_by_me.:format',
50 array('action' => 'ApiTimelineRetweetedByMe',
51 'format' => '(xml|json|atom|as)'));
53 $m->connect('api/statuses/retweeted_to_me.:format',
54 array('action' => 'ApiTimelineRetweetedToMe',
55 'format' => '(xml|json|atom|as)'));
57 $m->connect('api/statuses/retweets_of_me.:format',
58 array('action' => 'ApiTimelineRetweetsOfMe',
59 'format' => '(xml|json|atom|as)'));
61 $m->connect('api/statuses/retweet/:id.:format',
62 array('action' => 'ApiStatusesRetweet',
64 'format' => '(xml|json)'));
66 $m->connect('api/statuses/retweets/:id.:format',
67 array('action' => 'ApiStatusesRetweets',
69 'format' => '(xml|json)'));
72 // FIXME: Set this to abstract public in lib/activityhandlerplugin.php when all plugins have migrated!
73 protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
75 assert($this->isMyActivity($act));
77 // We don't have to save a repeat in a separate table, we can
78 // find repeats by just looking at the notice.repeat_of field.
83 // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
84 // with the other microapps/activityhandlers as well.
85 // Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
86 public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
88 if (!$this->isMyNotice($stored)) {
92 common_debug('Extending activity '.$stored->id.' with '.get_called_class());
93 $this->extendActivity($stored, $act, $scoped);
97 public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
99 // TODO: How to handle repeats of deleted notices?
100 $target = Notice::getById($stored->repeat_of);
101 // TRANS: A repeat activity's title. %1$s is repeater's nickname
102 // and %2$s is the repeated user's nickname.
103 $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
104 $stored->getProfile()->getNickname(),
105 $target->getProfile()->getNickname());
106 $act->objects[] = $target->asActivity($scoped);
109 public function activityObjectFromNotice(Notice $notice)
111 // Repeat is a little bit special. As it's an activity, our
112 // ActivityObject is instead turned into an Activity
113 $object = new Activity();
114 $object->verb = ActivityVerb::SHARE;
115 $object->type = $notice->object_type;
116 $object->title = sprintf(_('%1$s repeated a notice by %2$s'),
117 $object->getProfile()->getNickname(),
118 $target->getProfile()->getNickname());
119 $object->content = $notice->rendered;
123 public function deleteRelated(Notice $notice)
126 $fave = Fave::fromStored($notice);
128 } catch (NoResultException $e) {
129 // Cool, no problem. We wanted to get rid of it anyway.
136 * Typically just used to fill out Twitter-compatible API status data.
138 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
140 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
142 if ($scoped instanceof Profile) {
143 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
145 $status['favorited'] = false;
150 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
152 $userdata['favourites_count'] = Fave::countByProfile($profile);
156 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
158 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
160 if ($scoped instanceof Profile) {
161 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
166 public function onNoticeDeleteRelated(Notice $notice)
168 parent::onNoticeDeleteRelated($notice);
170 // The below algorithm is because we want to delete fave
171 // activities on any notice which _has_ faves, and not as
172 // in the parent function only ones that _are_ faves.
175 $fave->notice_id = $notice->id;
178 while ($fave->fetch()) {
186 public function onProfileDeleteRelated(Profile $profile, array &$related)
189 $fave->user_id = $profile->id;
190 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
193 Fave::blowCacheForProfileId($profile->id);
197 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
199 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
200 Fave::fillFaves($notice_ids);
203 if ($scoped instanceof Profile) {
204 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
209 * show the "favorite" form in the notice options element
210 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
214 public function onStartShowNoticeOptionItems($nli)
216 if (Event::handle('StartShowFaveForm', array($nli))) {
217 $scoped = Profile::current();
218 if ($scoped instanceof Profile) {
219 if (Fave::existsForProfile($nli->notice, $scoped)) {
220 $disfavor = new DisfavorForm($nli->out, $nli->notice);
223 $favor = new FavorForm($nli->out, $nli->notice);
227 Event::handle('EndShowFaveForm', array($nli));
231 public function showNoticeListItem(NoticeListItem $nli)
235 public function openNoticeListItemElement(NoticeListItem $nli)
239 public function closeNoticeListItemElement(NoticeListItem $nli)
244 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
247 $fave->user_id = $uas->getUser()->id;
249 if (!empty($uas->after)) {
250 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
254 while ($fave->fetch()) {
255 $objs[] = clone($fave);
262 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
264 if ($nli instanceof ThreadedNoticeListSubItem) {
265 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
266 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
268 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
270 $threadActive = $item->show() || $threadActive;
274 public function onEndFavorNotice(Profile $actor, Notice $target)
277 $notice_author = $target->getProfile();
278 // Don't notify ourselves of our own favorite on our own notice,
279 // or if it's a remote user (since we don't know their email addresses etc.)
280 if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
283 $local_user = $notice_author->getUser();
284 mail_notify_fave($local_user, $actor, $target);
285 } catch (Exception $e) {
286 // Mm'kay, probably not a local user. Let's skip this favor notification.
291 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
292 * using the class FavCommand.
294 * @param string $cmd Command being run
295 * @param string $arg Rest of the message (including address)
296 * @param User $user User sending the message
297 * @param Command &$result The resulting command object to be run.
299 * @return boolean hook value
301 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
303 if ($result === false && $cmd == 'fav') {
307 list($other, $extra) = CommandInterpreter::split_arg($arg);
308 if (!empty($extra)) {
311 $result = new FavCommand($user, $other);
319 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
321 // TRANS: Help message for IM/SMS command "fav <nickname>".
322 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
323 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
324 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
328 * Are we allowed to perform a certain command over the API?
330 public function onCommandSupportedAPI(Command $cmd, &$supported)
332 $supported = $supported || $cmd instanceof FavCommand;
335 // Form stuff (settings etc.)
337 public function onEndEmailFormData(Action $action, Profile $scoped)
339 $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
341 $action->elementStart('li');
342 $action->checkbox('email-notify_fave',
343 // TRANS: Checkbox label in e-mail preferences form.
344 _('Send me email when someone adds my notice as a favorite.'),
346 $action->elementEnd('li');
351 public function onStartEmailSaveForm(Action $action, Profile $scoped)
353 $emailfave = $action->booleanintstring('email-notify_fave');
355 if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
356 // No need to update setting
359 } catch (NoResultException $e) {
360 // Apparently there's no previously stored setting, then continue to save it as it is now.
363 $scoped->setPref('email', 'notify_fave', $emailfave);
370 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
372 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
373 // TRANS: Menu item in personal group navigation menu.
374 _m('MENU','Favorites'),
375 // @todo i18n FIXME: Need to make this two messages.
376 // TRANS: Menu item title in personal group navigation menu.
377 // TRANS: %s is a username.
378 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
379 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
380 'nav_timeline_favorites');
383 public function onEndPublicGroupNav(Menu $menu)
385 if (!common_config('singleuser', 'enabled')) {
386 // TRANS: Menu item in search group navigation panel.
387 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
388 // TRANS: Menu item title in search group navigation panel.
389 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
393 public function onEndShowSections(Action $action)
395 if (!$action->isAction(array('all', 'public'))) {
399 if (!common_config('performance', 'high')) {
400 $section = new PopularNoticeSection($action, $action->getScoped());
405 protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
407 return Fave::existsForProfile($target, $scoped)
408 // TRANS: Page/dialog box title when a notice is marked as favorite already
409 ? _m('TITLE', 'Unmark notice as favorite')
410 // TRANS: Page/dialog box title when a notice is not marked as favorite
411 : _m('TITLE', 'Mark notice as favorite');
414 protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
416 if ($action->isPost()) {
417 // The below tests are only for presenting to the user. POSTs which inflict
418 // duplicate favorite entries are handled with AlreadyFulfilledException.
422 $exists = Fave::existsForProfile($target, $scoped);
423 $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
426 case $exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
427 case !$exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
428 common_redirect(common_local_url('activityverb',
429 array('id' => $target->getID(),
430 'verb' => ActivityUtils::resolveUri($expected_verb, true))));
433 // No need to redirect as we are on the correct action already.
439 protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
442 case ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
443 Fave::addNew($scoped, $target);
445 case ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
446 Fave::removeEntry($scoped, $target);
449 throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
454 protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
456 return Fave::existsForProfile($target, $scoped)
457 ? new DisfavorForm($action, $target)
458 : new FavorForm($action, $target);
461 public function onPluginVersion(array &$versions)
463 $versions[] = array('name' => 'Favorite',
464 'version' => GNUSOCIAL_VERSION,
465 'author' => 'Mikael Nordfeldth',
466 'homepage' => 'http://gnu.io/',
468 // TRANS: Plugin description.
469 _m('Favorites (likes) using ActivityStreams.'));
476 * Notify a user that one of their notices has been chosen as a 'fave'
478 * @param User $rcpt The user whose notice was faved
479 * @param Profile $sender The user who faved the notice
480 * @param Notice $notice The notice that was faved
484 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
486 if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
490 // This test is actually "if the sender is sandboxed"
491 if (!$sender->hasRight(Right::EMAILONFAVE)) {
495 if ($rcpt->hasBlocked($sender)) {
496 // If the author has blocked us, don't spam them with a notification.
500 // We need the global mail.php for various mail related functions below.
501 require_once INSTALLDIR.'/lib/mail.php';
503 $bestname = $sender->getBestName();
505 common_switch_locale($rcpt->language);
507 // TRANS: Subject for favorite notification e-mail.
508 // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
509 $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
511 // TRANS: Body for favorite notification e-mail.
512 // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
513 // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
514 // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
515 // TRANS: %7$s is the adding user's nickname.
516 $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
517 " as one of their favorites.\n\n" .
518 "The URL of your notice is:\n\n" .
520 "The text of your notice is:\n\n" .
522 "You can see the list of %1\$s's favorites here:\n\n" .
525 common_exact_date($notice->created),
526 common_local_url('shownotice',
527 array('notice' => $notice->id)),
529 common_local_url('showfavorites',
530 array('nickname' => $sender->getNickname())),
531 common_config('site', 'name'),
532 $sender->getNickname()) .
535 $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
537 common_switch_locale();
538 mail_to_user($rcpt, $subject, $body, $headers);