]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Share/SharePlugin.php
Moving Ostatus_profile processShare to SharePlugin
[quix0rs-gnu-social.git] / plugins / Share / SharePlugin.php
1 <?php
2 /*
3  * GNU Social - a federating social network
4  * Copyright (C) 2014, Free Software Foundation, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * @package     Activity
24  * @maintainer  Mikael Nordfeldth <mmn@hethane.se>
25  */
26 class SharePlugin extends ActivityVerbHandlerPlugin
27 {
28     public function tag()
29     {
30         return 'share';
31     }
32
33     public function types()
34     {
35         return array();
36     }
37
38     public function verbs()
39     {
40         return array(ActivityVerb::SHARE);
41     }
42
43     public function onRouterInitialized(URLMapper $m)
44     {
45         // Web UI actions
46         $m->connect('main/repeat', array('action' => 'repeat'));
47
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)'));
52
53         $m->connect('api/statuses/retweeted_to_me.:format',
54                     array('action' => 'ApiTimelineRetweetedToMe',
55                           'format' => '(xml|json|atom|as)'));
56
57         $m->connect('api/statuses/retweets_of_me.:format',
58                     array('action' => 'ApiTimelineRetweetsOfMe',
59                           'format' => '(xml|json|atom|as)'));
60
61         $m->connect('api/statuses/retweet/:id.:format',
62                     array('action' => 'ApiStatusesRetweet',
63                           'id' => '[0-9]+',
64                           'format' => '(xml|json)'));
65
66         $m->connect('api/statuses/retweets/:id.:format',
67                     array('action' => 'ApiStatusesRetweets',
68                           'id' => '[0-9]+',
69                           'format' => '(xml|json)'));
70     }
71
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())
74     {
75         assert($this->isMyActivity($act));
76
77         // The below algorithm is mainly copied from the previous Ostatus_profile->processShare()
78
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.'));
82         }
83
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.'));
88         }
89
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;
96         }
97         if (empty($sharedUri)) {
98             throw new ClientException(_m('Shared activity does not have an id'));
99         }
100
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?
109             try {
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));
117                 }
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());
122                 return null;
123             }
124         }
125
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.
128
129         return true;
130     }
131
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)
136     {
137         if (!$this->isMyNotice($stored)) {
138             return true;
139         }
140
141         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
142         $this->extendActivity($stored, $act, $scoped);
143         return false;
144     }
145
146     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
147     {
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);
156     }
157
158     public function activityObjectFromNotice(Notice $notice)
159     {
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->type    = $notice->object_type;
165         $object->title   = sprintf(_('%1$s repeated a notice by %2$s'),
166                               $object->getProfile()->getNickname(),
167                               $target->getProfile()->getNickname());
168         $object->content = $notice->rendered;
169         return $object;
170     }
171
172     public function deleteRelated(Notice $notice)
173     {
174         try {
175             $fave = Fave::fromStored($notice);
176             $fave->delete();
177         } catch (NoResultException $e) {
178             // Cool, no problem. We wanted to get rid of it anyway.
179         }
180     }
181
182     // API stuff
183
184     /**
185      * Typically just used to fill out Twitter-compatible API status data.
186      *
187      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
188      */
189     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
190     {
191         if ($scoped instanceof Profile) {
192             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
193         } else {
194             $status['favorited'] = false;
195         }
196         return true;
197     }
198
199     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
200     {
201         $userdata['favourites_count'] = Fave::countByProfile($profile);
202     }
203
204     /**
205      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
206      */
207     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
208     {
209         if ($scoped instanceof Profile) {
210             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
211         }
212         return true;
213     }
214
215     public function onNoticeDeleteRelated(Notice $notice)
216     {
217         parent::onNoticeDeleteRelated($notice);
218
219         // The below algorithm is because we want to delete fave
220         // activities on any notice which _has_ faves, and not as
221         // in the parent function only ones that _are_ faves.
222
223         $fave = new Fave();
224         $fave->notice_id = $notice->id;
225
226         if ($fave->find()) {
227             while ($fave->fetch()) {
228                 $fave->delete();
229             }
230         }
231
232         $fave->free();
233     }
234
235     public function onProfileDeleteRelated(Profile $profile, array &$related)
236     {
237         $fave = new Fave();
238         $fave->user_id = $profile->id;
239         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
240         $fave->free();
241
242         Fave::blowCacheForProfileId($profile->id);
243         return true;
244     }
245
246     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
247     {
248         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
249         Fave::fillFaves($notice_ids);
250
251         // DB caching
252         if ($scoped instanceof Profile) {
253             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
254         }
255     }
256
257     /**
258      * show the "favorite" form in the notice options element
259      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
260      *
261      * @return void
262      */
263     public function onStartShowNoticeOptionItems($nli)
264     {
265         if (Event::handle('StartShowFaveForm', array($nli))) {
266             $scoped = Profile::current();
267             if ($scoped instanceof Profile) {
268                 if (Fave::existsForProfile($nli->notice, $scoped)) {
269                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
270                     $disfavor->show();
271                 } else {
272                     $favor = new FavorForm($nli->out, $nli->notice);
273                     $favor->show();
274                 }
275             }
276             Event::handle('EndShowFaveForm', array($nli));
277         }
278     }
279
280     public function showNoticeListItem(NoticeListItem $nli)
281     {
282         // pass
283     }
284     public function openNoticeListItemElement(NoticeListItem $nli)
285     {
286         // pass
287     }
288     public function closeNoticeListItemElement(NoticeListItem $nli)
289     {
290         // pass
291     }
292
293     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
294     {
295         $fave = new Fave();
296         $fave->user_id = $uas->getUser()->id;
297
298         if (!empty($uas->after)) {
299             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
300         }
301
302         if ($fave->find()) {
303             while ($fave->fetch()) {
304                 $objs[] = clone($fave);
305             }
306         }
307
308         return true;
309     }
310
311     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
312     {
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);
316         } else {
317             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
318         }
319         $threadActive = $item->show() || $threadActive;
320         return true;
321     }
322
323     public function onEndFavorNotice(Profile $actor, Notice $target)
324     {
325         try {
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()) {
330                 return true;
331             }
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.
336         }
337     }
338
339     /**
340      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
341      * using the class FavCommand.
342      *
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.
347      *
348      * @return boolean hook value
349      */
350     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
351     {
352         if ($result === false && $cmd == 'fav') {
353             if (empty($arg)) {
354                 $result = null;
355             } else {
356                 list($other, $extra) = CommandInterpreter::split_arg($arg);
357                 if (!empty($extra)) {
358                     $result = null;
359                 } else {
360                     $result = new FavCommand($user, $other);
361                 }
362             }
363             return false;
364         }
365         return true;
366     }
367
368     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
369     {
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'");
374     }
375
376     /**
377      * Are we allowed to perform a certain command over the API?
378      */
379     public function onCommandSupportedAPI(Command $cmd, &$supported)
380     {
381         $supported = $supported || $cmd instanceof FavCommand;
382     }
383
384     // Form stuff (settings etc.)
385
386     public function onEndEmailFormData(Action $action, Profile $scoped)
387     {
388         $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
389
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.'),
394                         $emailfave);
395         $action->elementEnd('li');
396
397         return true;
398     }
399
400     public function onStartEmailSaveForm(Action $action, Profile $scoped)
401     {
402         $emailfave = $action->booleanintstring('email-notify_fave');
403         try {
404             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
405                 // No need to update setting
406                 return true;
407             }
408         } catch (NoResultException $e) {
409             // Apparently there's no previously stored setting, then continue to save it as it is now.
410         }
411
412         $scoped->setPref('email', 'notify_fave', $emailfave);
413
414         return true;
415     }
416
417     // Layout stuff
418
419     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
420     {
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');
430     }
431
432     public function onEndPublicGroupNav(Menu $menu)
433     {
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');
439         }
440     }
441
442     public function onEndShowSections(Action $action)
443     {
444         if (!$action->isAction(array('all', 'public'))) {
445             return true;
446         }
447
448         if (!common_config('performance', 'high')) {
449             $section = new PopularNoticeSection($action, $action->getScoped());
450             $section->show();
451         }
452     }
453
454     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
455     {
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');
461     }
462
463     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
464     {
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. 
468             return false;
469         }
470
471         $exists = Fave::existsForProfile($target, $scoped);
472         $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
473
474         switch (true) {
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))));
480             break;
481         default:
482             // No need to redirect as we are on the correct action already.
483         }
484
485         return false;
486     }
487
488     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
489     {
490         switch (true) {
491         case ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
492             Fave::addNew($scoped, $target);
493             break;
494         case ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
495             Fave::removeEntry($scoped, $target);
496             break;
497         default:
498             throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
499         }
500         return false;
501     }
502
503     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
504     {
505         return Fave::existsForProfile($target, $scoped)
506                 ? new DisfavorForm($action, $target)
507                 : new FavorForm($action, $target);
508     }
509
510     public function onPluginVersion(array &$versions)
511     {
512         $versions[] = array('name' => 'Favorite',
513                             'version' => GNUSOCIAL_VERSION,
514                             'author' => 'Mikael Nordfeldth',
515                             'homepage' => 'http://gnu.io/',
516                             'rawdescription' =>
517                             // TRANS: Plugin description.
518                             _m('Favorites (likes) using ActivityStreams.'));
519
520         return true;
521     }
522 }
523
524 /**
525  * Notify a user that one of their notices has been chosen as a 'fave'
526  *
527  * @param User    $rcpt   The user whose notice was faved
528  * @param Profile $sender The user who faved the notice
529  * @param Notice  $notice The notice that was faved
530  *
531  * @return void
532  */
533 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
534 {
535     if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
536         return;
537     }
538
539     // This test is actually "if the sender is sandboxed"
540     if (!$sender->hasRight(Right::EMAILONFAVE)) {
541         return;
542     }
543
544     if ($rcpt->hasBlocked($sender)) {
545         // If the author has blocked us, don't spam them with a notification.
546         return;
547     }
548
549     // We need the global mail.php for various mail related functions below.
550     require_once INSTALLDIR.'/lib/mail.php';
551
552     $bestname = $sender->getBestName();
553
554     common_switch_locale($rcpt->language);
555
556     // TRANS: Subject for favorite notification e-mail.
557     // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
558     $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
559
560     // TRANS: Body for favorite notification e-mail.
561     // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
562     // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
563     // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
564     // TRANS: %7$s is the adding user's nickname.
565     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
566                       " as one of their favorites.\n\n" .
567                       "The URL of your notice is:\n\n" .
568                       "%3\$s\n\n" .
569                       "The text of your notice is:\n\n" .
570                       "%4\$s\n\n" .
571                       "You can see the list of %1\$s's favorites here:\n\n" .
572                       "%5\$s"),
573                     $bestname,
574                     common_exact_date($notice->created),
575                     common_local_url('shownotice',
576                                      array('notice' => $notice->id)),
577                     $notice->content,
578                     common_local_url('showfavorites',
579                                      array('nickname' => $sender->getNickname())),
580                     common_config('site', 'name'),
581                     $sender->getNickname()) .
582             mail_footer_block();
583
584     $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
585
586     common_switch_locale();
587     mail_to_user($rcpt, $subject, $body, $headers);
588 }