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 // The below algorithm is mainly copied from the previous Ostatus_profile->processShare()
79 if (count($act->objects) !== 1) {
80 // TRANS: Client exception thrown when trying to share multiple activities at once.
81 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
84 $shared = $act->objects[0];
85 if (!$shared instanceof Activity) {
86 // TRANS: Client exception thrown when trying to share a non-activity object.
87 throw new ClientException(_m('Can only handle shared activities.'));
90 $sharedUri = $shared->id;
91 if (!empty($shared->objects[0]->id)) {
92 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
93 // fucks up federation, because the URI is no longer recognised by the origin.
94 // So we set it to the object ID if it exists, otherwise we trust $shared->id
95 $sharedUri = $shared->objects[0]->id;
97 if (empty($sharedUri)) {
98 throw new ClientException(_m('Shared activity does not have an id'));
101 // First check if we have the shared activity. This has to be done first, because
102 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
103 // who might be the creator of the shared activity in question.
104 $sharedNotice = Notice::getKV('uri', $sharedId);
105 if (!$sharedNotice instanceof Notice) {
106 // If no locally stored notice is found, process it!
107 // TODO: Remember to check Deleted_notice!
108 // TODO: If a post is shared that we can't retrieve - what to do?
110 $other = self::ensureActivityObjectProfile($shared->actor);
111 $sharedNotice = $other->processActivity($shared, $method);
112 if (!$sharedNotice instanceof Notice) {
113 // And if we apparently can't get the shared notice, we'll abort the whole thing.
114 // TRANS: Client exception thrown when saving an activity share fails.
115 // TRANS: %s is a share ID.
116 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
118 } catch (FeedSubException $e) {
119 // Remote feed could not be found or verified, should we
120 // transform this into an "RT @user Blah, blah, blah..."?
121 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
126 // We don't have to save a repeat in a separate table, we can
127 // find repeats by just looking at the notice.repeat_of field.
132 // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
133 // with the other microapps/activityhandlers as well.
134 // Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
135 public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
137 if (!$this->isMyNotice($stored)) {
141 common_debug('Extending activity '.$stored->id.' with '.get_called_class());
142 $this->extendActivity($stored, $act, $scoped);
146 public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
148 // TODO: How to handle repeats of deleted notices?
149 $target = Notice::getById($stored->repeat_of);
150 // TRANS: A repeat activity's title. %1$s is repeater's nickname
151 // and %2$s is the repeated user's nickname.
152 $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
153 $stored->getProfile()->getNickname(),
154 $target->getProfile()->getNickname());
155 $act->objects[] = $target->asActivity($scoped);
158 public function activityObjectFromNotice(Notice $notice)
160 // Repeat is a little bit special. As it's an activity, our
161 // ActivityObject is instead turned into an Activity
162 $object = new Activity();
163 $object->verb = ActivityVerb::SHARE;
164 $object->content = $notice->rendered;
165 $this->extendActivity($stored, $act);
170 public function deleteRelated(Notice $notice)
172 // No action needed as we don't have a separate table for share objects.
179 * Typically just used to fill out Twitter-compatible API status data.
181 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
183 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
185 if ($scoped instanceof Profile) {
186 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
188 $status['favorited'] = false;
193 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
195 $userdata['favourites_count'] = Fave::countByProfile($profile);
199 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
201 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
203 if ($scoped instanceof Profile) {
204 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
209 public function onNoticeDeleteRelated(Notice $notice)
211 parent::onNoticeDeleteRelated($notice);
213 // The below algorithm is because we want to delete fave
214 // activities on any notice which _has_ faves, and not as
215 // in the parent function only ones that _are_ faves.
218 $fave->notice_id = $notice->id;
221 while ($fave->fetch()) {
229 public function onProfileDeleteRelated(Profile $profile, array &$related)
232 $fave->user_id = $profile->id;
233 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
236 Fave::blowCacheForProfileId($profile->id);
240 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
242 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
243 Fave::fillFaves($notice_ids);
246 if ($scoped instanceof Profile) {
247 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
252 * show the "favorite" form in the notice options element
253 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
257 public function onEndShowNoticeOptionItems($nli)
259 // FIXME: Use bitmasks (but be aware that PUBLIC_SCOPE is 0!)
260 if ($nli->notice->scope == Notice::PUBLIC_SCOPE ||
261 $nli->notice->scope == Notice::SITE_SCOPE) {
262 $scoped = Profile::current();
263 if ($scoped instanceof Profile &&
264 $scoped->getID() !== $nli->notice->getProfile()->getID()) {
266 if ($scoped->hasRepeated($nli->notice)) {
267 $nli->out->element('span', array('class' => 'repeated',
268 // TRANS: Title for repeat form status in notice list when a notice has been repeated.
269 'title' => _('Notice repeated.')),
270 // TRANS: Repeat form status in notice list when a notice has been repeated.
273 $repeat = new RepeatForm($nli->out, $nli->notice);
280 public function showNoticeListItem(NoticeListItem $nli)
284 public function openNoticeListItemElement(NoticeListItem $nli)
288 public function closeNoticeListItemElement(NoticeListItem $nli)
293 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
296 $fave->user_id = $uas->getUser()->id;
298 if (!empty($uas->after)) {
299 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
303 while ($fave->fetch()) {
304 $objs[] = clone($fave);
311 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
313 if ($nli instanceof ThreadedNoticeListSubItem) {
314 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
315 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
317 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
319 $threadActive = $item->show() || $threadActive;
323 public function onEndFavorNotice(Profile $actor, Notice $target)
326 $notice_author = $target->getProfile();
327 // Don't notify ourselves of our own favorite on our own notice,
328 // or if it's a remote user (since we don't know their email addresses etc.)
329 if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
332 $local_user = $notice_author->getUser();
333 mail_notify_fave($local_user, $actor, $target);
334 } catch (Exception $e) {
335 // Mm'kay, probably not a local user. Let's skip this favor notification.
340 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
341 * using the class FavCommand.
343 * @param string $cmd Command being run
344 * @param string $arg Rest of the message (including address)
345 * @param User $user User sending the message
346 * @param Command &$result The resulting command object to be run.
348 * @return boolean hook value
350 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
352 if ($result === false && in_array($cmd, array('repeat', 'rp', 'rt', 'rd'))) {
356 list($other, $extra) = CommandInterpreter::split_arg($arg);
357 if (!empty($extra)) {
360 $result = new RepeatCommand($user, $other);
368 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
370 // TRANS: Help message for IM/SMS command "fav <nickname>".
371 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
372 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
373 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
377 * Are we allowed to perform a certain command over the API?
379 public function onCommandSupportedAPI(Command $cmd, &$supported)
381 $supported = $supported || $cmd instanceof RepeatCommand;
384 // Form stuff (settings etc.)
386 public function onEndEmailFormData(Action $action, Profile $scoped)
388 $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
390 $action->elementStart('li');
391 $action->checkbox('email-notify_fave',
392 // TRANS: Checkbox label in e-mail preferences form.
393 _('Send me email when someone adds my notice as a favorite.'),
395 $action->elementEnd('li');
400 public function onStartEmailSaveForm(Action $action, Profile $scoped)
402 $emailfave = $action->booleanintstring('email-notify_fave');
404 if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
405 // No need to update setting
408 } catch (NoResultException $e) {
409 // Apparently there's no previously stored setting, then continue to save it as it is now.
412 $scoped->setPref('email', 'notify_fave', $emailfave);
419 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
421 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
422 // TRANS: Menu item in personal group navigation menu.
423 _m('MENU','Favorites'),
424 // @todo i18n FIXME: Need to make this two messages.
425 // TRANS: Menu item title in personal group navigation menu.
426 // TRANS: %s is a username.
427 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
428 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
429 'nav_timeline_favorites');
432 public function onEndPublicGroupNav(Menu $menu)
434 if (!common_config('singleuser', 'enabled')) {
435 // TRANS: Menu item in search group navigation panel.
436 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
437 // TRANS: Menu item title in search group navigation panel.
438 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
442 public function onEndShowSections(Action $action)
444 if (!$action->isAction(array('all', 'public'))) {
448 if (!common_config('performance', 'high')) {
449 $section = new PopularNoticeSection($action, $action->getScoped());
454 protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
456 return Fave::existsForProfile($target, $scoped)
457 // TRANS: Page/dialog box title when a notice is marked as favorite already
458 ? _m('TITLE', 'Unmark notice as favorite')
459 // TRANS: Page/dialog box title when a notice is not marked as favorite
460 : _m('TITLE', 'Mark notice as favorite');
463 protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
465 if ($action->isPost()) {
466 // The below tests are only for presenting to the user. POSTs which inflict
467 // duplicate favorite entries are handled with AlreadyFulfilledException.
471 $exists = Fave::existsForProfile($target, $scoped);
472 $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
475 case $exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
476 case !$exists && ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
477 common_redirect(common_local_url('activityverb',
478 array('id' => $target->getID(),
479 'verb' => ActivityUtils::resolveUri($expected_verb, true))));
482 // No need to redirect as we are on the correct action already.
488 protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
491 case ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
492 Fave::addNew($scoped, $target);
494 case ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
495 Fave::removeEntry($scoped, $target);
498 throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
503 protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
505 return Fave::existsForProfile($target, $scoped)
506 ? new DisfavorForm($action, $target)
507 : new FavorForm($action, $target);
510 public function onPluginVersion(array &$versions)
512 $versions[] = array('name' => 'Share verb',
513 'version' => GNUSOCIAL_VERSION,
514 'author' => 'Mikael Nordfeldth',
515 'homepage' => 'https://gnu.io/',
517 // TRANS: Plugin description.
518 _m('Shares (repeats) using ActivityStreams.'));