]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Share/SharePlugin.php
7f71adfd8367cf37cce41225eb172769c036e6cb
[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         // 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.
79
80         return true;
81     }
82
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)
87     {
88         if (!$this->isMyNotice($stored)) {
89             return true;
90         }
91
92         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
93         $this->extendActivity($stored, $act, $scoped);
94         return false;
95     }
96
97     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
98     {
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);
107     }
108
109     public function activityObjectFromNotice(Notice $notice)
110     {
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;
120         return $object;
121     }
122
123     public function deleteRelated(Notice $notice)
124     {
125         try {
126             $fave = Fave::fromStored($notice);
127             $fave->delete();
128         } catch (NoResultException $e) {
129             // Cool, no problem. We wanted to get rid of it anyway.
130         }
131     }
132
133     // API stuff
134
135     /**
136      * Typically just used to fill out Twitter-compatible API status data.
137      *
138      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
139      */
140     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
141     {
142         if ($scoped instanceof Profile) {
143             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
144         } else {
145             $status['favorited'] = false;
146         }
147         return true;
148     }
149
150     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
151     {
152         $userdata['favourites_count'] = Fave::countByProfile($profile);
153     }
154
155     /**
156      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
157      */
158     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
159     {
160         if ($scoped instanceof Profile) {
161             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
162         }
163         return true;
164     }
165
166     public function onNoticeDeleteRelated(Notice $notice)
167     {
168         parent::onNoticeDeleteRelated($notice);
169
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.
173
174         $fave = new Fave();
175         $fave->notice_id = $notice->id;
176
177         if ($fave->find()) {
178             while ($fave->fetch()) {
179                 $fave->delete();
180             }
181         }
182
183         $fave->free();
184     }
185
186     public function onProfileDeleteRelated(Profile $profile, array &$related)
187     {
188         $fave = new Fave();
189         $fave->user_id = $profile->id;
190         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
191         $fave->free();
192
193         Fave::blowCacheForProfileId($profile->id);
194         return true;
195     }
196
197     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
198     {
199         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
200         Fave::fillFaves($notice_ids);
201
202         // DB caching
203         if ($scoped instanceof Profile) {
204             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
205         }
206     }
207
208     /**
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)
211      *
212      * @return void
213      */
214     public function onStartShowNoticeOptionItems($nli)
215     {
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);
221                     $disfavor->show();
222                 } else {
223                     $favor = new FavorForm($nli->out, $nli->notice);
224                     $favor->show();
225                 }
226             }
227             Event::handle('EndShowFaveForm', array($nli));
228         }
229     }
230
231     public function showNoticeListItem(NoticeListItem $nli)
232     {
233         // pass
234     }
235     public function openNoticeListItemElement(NoticeListItem $nli)
236     {
237         // pass
238     }
239     public function closeNoticeListItemElement(NoticeListItem $nli)
240     {
241         // pass
242     }
243
244     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
245     {
246         $fave = new Fave();
247         $fave->user_id = $uas->getUser()->id;
248
249         if (!empty($uas->after)) {
250             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
251         }
252
253         if ($fave->find()) {
254             while ($fave->fetch()) {
255                 $objs[] = clone($fave);
256             }
257         }
258
259         return true;
260     }
261
262     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
263     {
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);
267         } else {
268             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
269         }
270         $threadActive = $item->show() || $threadActive;
271         return true;
272     }
273
274     public function onEndFavorNotice(Profile $actor, Notice $target)
275     {
276         try {
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()) {
281                 return true;
282             }
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.
287         }
288     }
289
290     /**
291      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
292      * using the class FavCommand.
293      *
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.
298      *
299      * @return boolean hook value
300      */
301     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
302     {
303         if ($result === false && $cmd == 'fav') {
304             if (empty($arg)) {
305                 $result = null;
306             } else {
307                 list($other, $extra) = CommandInterpreter::split_arg($arg);
308                 if (!empty($extra)) {
309                     $result = null;
310                 } else {
311                     $result = new FavCommand($user, $other);
312                 }
313             }
314             return false;
315         }
316         return true;
317     }
318
319     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
320     {
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'");
325     }
326
327     /**
328      * Are we allowed to perform a certain command over the API?
329      */
330     public function onCommandSupportedAPI(Command $cmd, &$supported)
331     {
332         $supported = $supported || $cmd instanceof FavCommand;
333     }
334
335     // Form stuff (settings etc.)
336
337     public function onEndEmailFormData(Action $action, Profile $scoped)
338     {
339         $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
340
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.'),
345                         $emailfave);
346         $action->elementEnd('li');
347
348         return true;
349     }
350
351     public function onStartEmailSaveForm(Action $action, Profile $scoped)
352     {
353         $emailfave = $action->booleanintstring('email-notify_fave');
354         try {
355             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
356                 // No need to update setting
357                 return true;
358             }
359         } catch (NoResultException $e) {
360             // Apparently there's no previously stored setting, then continue to save it as it is now.
361         }
362
363         $scoped->setPref('email', 'notify_fave', $emailfave);
364
365         return true;
366     }
367
368     // Layout stuff
369
370     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
371     {
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');
381     }
382
383     public function onEndPublicGroupNav(Menu $menu)
384     {
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');
390         }
391     }
392
393     public function onEndShowSections(Action $action)
394     {
395         if (!$action->isAction(array('all', 'public'))) {
396             return true;
397         }
398
399         if (!common_config('performance', 'high')) {
400             $section = new PopularNoticeSection($action, $action->getScoped());
401             $section->show();
402         }
403     }
404
405     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
406     {
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');
412     }
413
414     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
415     {
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. 
419             return false;
420         }
421
422         $exists = Fave::existsForProfile($target, $scoped);
423         $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
424
425         switch (true) {
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))));
431             break;
432         default:
433             // No need to redirect as we are on the correct action already.
434         }
435
436         return false;
437     }
438
439     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
440     {
441         switch (true) {
442         case ActivityUtils::compareTypes($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
443             Fave::addNew($scoped, $target);
444             break;
445         case ActivityUtils::compareTypes($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
446             Fave::removeEntry($scoped, $target);
447             break;
448         default:
449             throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
450         }
451         return false;
452     }
453
454     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
455     {
456         return Fave::existsForProfile($target, $scoped)
457                 ? new DisfavorForm($action, $target)
458                 : new FavorForm($action, $target);
459     }
460
461     public function onPluginVersion(array &$versions)
462     {
463         $versions[] = array('name' => 'Favorite',
464                             'version' => GNUSOCIAL_VERSION,
465                             'author' => 'Mikael Nordfeldth',
466                             'homepage' => 'http://gnu.io/',
467                             'rawdescription' =>
468                             // TRANS: Plugin description.
469                             _m('Favorites (likes) using ActivityStreams.'));
470
471         return true;
472     }
473 }
474
475 /**
476  * Notify a user that one of their notices has been chosen as a 'fave'
477  *
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
481  *
482  * @return void
483  */
484 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
485 {
486     if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
487         return;
488     }
489
490     // This test is actually "if the sender is sandboxed"
491     if (!$sender->hasRight(Right::EMAILONFAVE)) {
492         return;
493     }
494
495     if ($rcpt->hasBlocked($sender)) {
496         // If the author has blocked us, don't spam them with a notification.
497         return;
498     }
499
500     // We need the global mail.php for various mail related functions below.
501     require_once INSTALLDIR.'/lib/mail.php';
502
503     $bestname = $sender->getBestName();
504
505     common_switch_locale($rcpt->language);
506
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());
510
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" .
519                       "%3\$s\n\n" .
520                       "The text of your notice is:\n\n" .
521                       "%4\$s\n\n" .
522                       "You can see the list of %1\$s's favorites here:\n\n" .
523                       "%5\$s"),
524                     $bestname,
525                     common_exact_date($notice->created),
526                     common_local_url('shownotice',
527                                      array('notice' => $notice->id)),
528                     $notice->content,
529                     common_local_url('showfavorites',
530                                      array('nickname' => $sender->getNickname())),
531                     common_config('site', 'name'),
532                     $sender->getNickname()) .
533             mail_footer_block();
534
535     $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
536
537     common_switch_locale();
538     mail_to_user($rcpt, $subject, $body, $headers);
539 }