]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Share/SharePlugin.php
Moving some more repeat stuff into the Share plugin
[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     // Share is a bit special and $act->objects[0] should be an Activity
44     // instead of ActivityObject! Therefore also $act->objects[0]->type is not set.
45     public function isMyActivity(Activity $act) {
46         return (count($act->objects) == 1
47             && ($act->objects[0] instanceof Activity)
48             && $this->isMyVerb($act->verb));
49     }
50
51     public function onRouterInitialized(URLMapper $m)
52     {
53         // Web UI actions
54         $m->connect('main/repeat', array('action' => 'repeat'));
55
56         // Share for Twitter API ("Retweet")
57         $m->connect('api/statuses/retweeted_by_me.:format',
58                     array('action' => 'ApiTimelineRetweetedByMe',
59                           'format' => '(xml|json|atom|as)'));
60
61         $m->connect('api/statuses/retweeted_to_me.:format',
62                     array('action' => 'ApiTimelineRetweetedToMe',
63                           'format' => '(xml|json|atom|as)'));
64
65         $m->connect('api/statuses/retweets_of_me.:format',
66                     array('action' => 'ApiTimelineRetweetsOfMe',
67                           'format' => '(xml|json|atom|as)'));
68
69         $m->connect('api/statuses/retweet/:id.:format',
70                     array('action' => 'ApiStatusesRetweet',
71                           'id' => '[0-9]+',
72                           'format' => '(xml|json)'));
73
74         $m->connect('api/statuses/retweets/:id.:format',
75                     array('action' => 'ApiStatusesRetweets',
76                           'id' => '[0-9]+',
77                           'format' => '(xml|json)'));
78     }
79
80     // FIXME: Set this to abstract public in lib/activityhandlerplugin.php when all plugins have migrated!
81     protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
82     {
83         assert($this->isMyActivity($act));
84
85         // The below algorithm is mainly copied from the previous Ostatus_profile->processShare()
86
87         if (count($act->objects) !== 1) {
88             // TRANS: Client exception thrown when trying to share multiple activities at once.
89             throw new ClientException(_m('Can only handle share activities with exactly one object.'));
90         }
91
92         $shared = $act->objects[0];
93         if (!$shared instanceof Activity) {
94             // TRANS: Client exception thrown when trying to share a non-activity object.
95             throw new ClientException(_m('Can only handle shared activities.'));
96         }
97
98         $sharedUri = $shared->id;
99         if (!empty($shared->objects[0]->id)) {
100             // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
101             // fucks up federation, because the URI is no longer recognised by the origin.
102             // So we set it to the object ID if it exists, otherwise we trust $shared->id
103             $sharedUri = $shared->objects[0]->id;
104         }
105         if (empty($sharedUri)) {
106             throw new ClientException(_m('Shared activity does not have an id'));
107         }
108
109         try {
110             // First check if we have the shared activity. This has to be done first, because
111             // we can't use these functions to "ensureActivityObjectProfile" of a local user,
112             // who might be the creator of the shared activity in question.
113             $sharedNotice = Notice::getByUri($sharedUri);
114         } catch (NoResultException $e) {
115             // If no locally stored notice is found, process it!
116             // TODO: Remember to check Deleted_notice!
117             // TODO: If a post is shared that we can't retrieve - what to do?
118             $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
119             $sharedNotice = $other->processActivity($shared, 'push');   // FIXME: push/salmon/what?
120             if (!$sharedNotice instanceof Notice) {
121                 // And if we apparently can't get the shared notice, we'll abort the whole thing.
122                 // TRANS: Client exception thrown when saving an activity share fails.
123                 // TRANS: %s is a share ID.
124                 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedUri));
125             }
126         } catch (FeedSubException $e) {
127             // Remote feed could not be found or verified, should we
128             // transform this into an "RT @user Blah, blah, blah..."?
129             common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
130             return false;
131         }
132
133         // Setting this here because when the algorithm gets back to
134         // Notice::saveActivity it will update the Notice object.
135         $stored->repeat_of = $sharedNotice->getID();
136         $stored->conversation = $sharedNotice->conversation;
137         $stored->object_type = ActivityUtils::resolveUri(ActivityObject::ACTIVITY, true);
138
139         // We don't have to save a repeat in a separate table, we can
140         // find repeats by just looking at the notice.repeat_of field.
141
142         // By returning true here instead of something that evaluates
143         // to false, we show that we have processed everything properly.
144         return true;
145     }
146
147     // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
148     //          with the other microapps/activityhandlers as well.
149     //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
150     public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
151     {
152         if (!$this->isMyNotice($stored)) {
153             return true;
154         }
155
156         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
157         $this->extendActivity($stored, $act, $scoped);
158         return false;
159     }
160
161     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
162     {
163         // TODO: How to handle repeats of deleted notices?
164         $target = Notice::getById($stored->repeat_of);
165         // TRANS: A repeat activity's title. %1$s is repeater's nickname
166         //        and %2$s is the repeated user's nickname.
167         $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
168                               $stored->getProfile()->getNickname(),
169                               $target->getProfile()->getNickname());
170         $act->objects[] = $target->asActivity($scoped);
171     }
172
173     public function activityObjectFromNotice(Notice $notice)
174     {
175         // Repeat is a little bit special. As it's an activity, our
176         // ActivityObject is instead turned into an Activity
177         $object          = new Activity();
178         $object->verb    = ActivityVerb::SHARE;
179         $object->content = $notice->rendered;
180         $this->extendActivity($stored, $act);
181
182         return $object;
183     }
184
185     public function deleteRelated(Notice $notice)
186     {
187         // No action needed as we don't have a separate table for share objects.
188         return true;
189     }
190
191     // Layout stuff
192
193     /**
194      * show a link to the author of repeat
195      *
196      * FIXME: Some repeat stuff still in lib/noticelistitem.php! ($nli->repeat etc.)
197      */
198     public function onEndShowNoticeInfo(NoticeListItem $nli)
199     {
200         if (!empty($nli->repeat)) {
201             $repeater = $nli->repeat->getProfile();
202
203             $attrs = array('href' => $repeater->getUrl(),
204                            'class' => 'h-card p-author',
205                            'title' => $repeater->getFancyName());
206
207             $nli->out->elementStart('span', 'repeat h-entry');
208
209             // TRANS: Addition in notice list item if notice was repeated. Followed by a span with a nickname.
210             $nli->out->raw(_('Repeated by').' ');
211
212             $nli->out->element('a', $attrs, $repeater->getNickname());
213
214             $nli->out->elementEnd('span');
215         }
216     }
217
218     public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
219     {
220         if ($nli instanceof ThreadedNoticeListSubItem) {
221             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
222             $item = new ThreadedNoticeListInlineRepeatsItem($notice, $nli->out);
223         } else {
224             $item = new ThreadedNoticeListRepeatsItem($notice, $nli->out);
225         }
226         $threadActive = $item->show() || $threadActive;
227         return true;
228     }
229
230     /**
231      * show the "repeat" form in the notice options element
232      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
233      *
234      * @return void
235      */
236     public function onEndShowNoticeOptionItems($nli)
237     {
238         // FIXME: Use bitmasks (but be aware that PUBLIC_SCOPE is 0!)
239         if ($nli->notice->scope == Notice::PUBLIC_SCOPE ||
240                 $nli->notice->scope == Notice::SITE_SCOPE) {
241             $scoped = Profile::current();
242             if ($scoped instanceof Profile &&
243                     $scoped->getID() !== $nli->notice->getProfile()->getID()) {
244
245                 if ($scoped->hasRepeated($nli->notice)) {
246                     $nli->out->element('span', array('class' => 'repeated',
247                                                       // TRANS: Title for repeat form status in notice list when a notice has been repeated.
248                                                       'title' => _('Notice repeated.')),
249                                         // TRANS: Repeat form status in notice list when a notice has been repeated.
250                                         _('Repeated'));
251                 } else {
252                     $repeat = new RepeatForm($nli->out, $nli->notice);
253                     $repeat->show();
254                 }
255             }
256         }
257     }
258
259     public function showNoticeListItem(NoticeListItem $nli)
260     {
261         // pass
262     }
263     public function openNoticeListItemElement(NoticeListItem $nli)
264     {
265         // pass
266     }
267     public function closeNoticeListItemElement(NoticeListItem $nli)
268     {
269         // pass
270     }
271
272     // API stuff
273
274     /**
275      * Typically just used to fill out Twitter-compatible API status data.
276      *
277      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
278      */
279     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
280     {
281         if ($scoped instanceof Profile) {
282             $status['repeated'] = $scoped->hasRepeated($notice);
283         } else {
284             $status['repeated'] = false;
285         }
286     }
287
288     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
289     {
290         $userdata['favourites_count'] = Fave::countByProfile($profile);
291     }
292
293     // Command stuff
294
295     /**
296      * EndInterpretCommand for RepeatPlugin will handle the 'repeat' command
297      * using the class RepeatCommand.
298      *
299      * @param string  $cmd     Command being run
300      * @param string  $arg     Rest of the message (including address)
301      * @param User    $user    User sending the message
302      * @param Command &$result The resulting command object to be run.
303      *
304      * @return boolean hook value
305      */
306     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
307     {
308         if ($result === false && in_array($cmd, array('repeat', 'rp', 'rt', 'rd'))) {
309             if (empty($arg)) {
310                 $result = null;
311             } else {
312                 list($other, $extra) = CommandInterpreter::split_arg($arg);
313                 if (!empty($extra)) {
314                     $result = null;
315                 } else {
316                     $result = new RepeatCommand($user, $other);
317                 }
318             }
319             return false;
320         }
321         return true;
322     }
323
324     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
325     {
326         // TRANS: Help message for IM/SMS command "repeat #<notice_id>".
327         $commands['repeat #<notice_id>'] = _m('COMMANDHELP', "repeat a notice with a given id");
328         // TRANS: Help message for IM/SMS command "repeat <nickname>".
329         $commands['repeat <nickname>']   = _m('COMMANDHELP', "repeat the last notice from user");
330     }
331
332     /**
333      * Are we allowed to perform a certain command over the API?
334      */
335     public function onCommandSupportedAPI(Command $cmd, &$supported)
336     {
337         $supported = $supported || $cmd instanceof RepeatCommand;
338     }
339
340     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
341     {
342         // return page title
343     }
344
345     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
346     {
347         // prepare Action?
348     }
349
350     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
351     {
352         // handle repeat POST
353     }
354
355     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
356     {
357         return new RepeatForm($action, $target);
358     }
359
360     public function onPluginVersion(array &$versions)
361     {
362         $versions[] = array('name' => 'Share verb',
363                             'version' => GNUSOCIAL_VERSION,
364                             'author' => 'Mikael Nordfeldth',
365                             'homepage' => 'https://gnu.io/',
366                             'rawdescription' =>
367                             // TRANS: Plugin description.
368                             _m('Shares (repeats) using ActivityStreams.'));
369
370         return true;
371     }
372 }