]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Share/SharePlugin.php
Introduced common_location_shared() to check if location sharing is always,
[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 = Notice::saveActivity($shared, $other->localProfile(), array('source'=>'share'));
120         } catch (FeedSubException $e) {
121             // Remote feed could not be found or verified, should we
122             // transform this into an "RT @user Blah, blah, blah..."?
123             common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
124             return false;
125         }
126
127         // Setting this here because when the algorithm gets back to
128         // Notice::saveActivity it will update the Notice object.
129         $stored->repeat_of = $sharedNotice->getID();
130         $stored->conversation = $sharedNotice->conversation;
131
132         // We don't have to save a repeat in a separate table, we can
133         // find repeats by just looking at the notice.repeat_of field.
134
135         // By returning true here instead of something that evaluates
136         // to false, we show that we have processed everything properly.
137         return true;
138     }
139
140     // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
141     //          with the other microapps/activityhandlers as well.
142     //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
143     public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
144     {
145         if (!$this->isMyNotice($stored)) {
146             return true;
147         }
148
149         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
150         $this->extendActivity($stored, $act, $scoped);
151         return false;
152     }
153
154     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
155     {
156         // TODO: How to handle repeats of deleted notices?
157         $target = Notice::getByID($stored->repeat_of);
158         // TRANS: A repeat activity's title. %1$s is repeater's nickname
159         //        and %2$s is the repeated user's nickname.
160         $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
161                               $stored->getProfile()->getNickname(),
162                               $target->getProfile()->getNickname());
163         $act->objects[] = $target->asActivity($scoped);
164     }
165
166     public function activityObjectFromNotice(Notice $stored)
167     {
168         // Repeat is a little bit special. As it's an activity, our
169         // ActivityObject is instead turned into an Activity
170         $object          = new Activity();
171         $object->actor   = $stored->getProfile()->asActivityObject();
172         $object->verb    = ActivityVerb::SHARE;
173         $object->content = $stored->getRendered();
174         $this->extendActivity($stored, $object);
175
176         return $object;
177     }
178
179     public function deleteRelated(Notice $notice)
180     {
181         // No action needed as we don't have a separate table for share objects.
182         return true;
183     }
184
185     // Layout stuff
186
187     /**
188      * show a link to the author of repeat
189      *
190      * FIXME: Some repeat stuff still in lib/noticelistitem.php! ($nli->repeat etc.)
191      */
192     public function onEndShowNoticeInfo(NoticeListItem $nli)
193     {
194         if (!empty($nli->repeat)) {
195             $repeater = $nli->repeat->getProfile();
196
197             $attrs = array('href' => $repeater->getUrl(),
198                            'class' => 'h-card p-author',
199                            'title' => $repeater->getFancyName());
200
201             $nli->out->elementStart('span', 'repeat');
202
203             // TRANS: Addition in notice list item if notice was repeated. Followed by a span with a nickname.
204             $nli->out->raw(_('Repeated by').' ');
205
206             $nli->out->element('a', $attrs, $repeater->getNickname());
207
208             $nli->out->elementEnd('span');
209         }
210     }
211
212     public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
213     {
214         if ($nli instanceof ThreadedNoticeListSubItem) {
215             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
216             $item = new ThreadedNoticeListInlineRepeatsItem($notice, $nli->out);
217         } else {
218             $item = new ThreadedNoticeListRepeatsItem($notice, $nli->out);
219         }
220         $threadActive = $item->show() || $threadActive;
221         return true;
222     }
223
224     /**
225      * show the "repeat" form in the notice options element
226      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
227      *
228      * @return void
229      */
230     public function onEndShowNoticeOptionItems($nli)
231     {
232         // FIXME: Use bitmasks (but be aware that PUBLIC_SCOPE is 0!)
233         // Also: AHHH, $scope and $scoped are scarily similar looking.
234         $scope = $nli->notice->getScope();
235         if ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE) {
236             $scoped = Profile::current();
237             if ($scoped instanceof Profile &&
238                     $scoped->getID() !== $nli->notice->getProfile()->getID()) {
239
240                 if ($scoped->hasRepeated($nli->notice)) {
241                     $nli->out->element('span', array('class' => 'repeated',
242                                                       // TRANS: Title for repeat form status in notice list when a notice has been repeated.
243                                                       'title' => _('Notice repeated.')),
244                                         // TRANS: Repeat form status in notice list when a notice has been repeated.
245                                         _('Repeated'));
246                 } else {
247                     $repeat = new RepeatForm($nli->out, $nli->notice);
248                     $repeat->show();
249                 }
250             }
251         }
252     }
253
254     protected function showNoticeListItem(NoticeListItem $nli)
255     {
256         // pass
257     }
258     public function openNoticeListItemElement(NoticeListItem $nli)
259     {
260         // pass
261     }
262     public function closeNoticeListItemElement(NoticeListItem $nli)
263     {
264         // pass
265     }
266
267     // API stuff
268
269     /**
270      * Typically just used to fill out Twitter-compatible API status data.
271      *
272      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
273      */
274     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
275     {
276         $status['repeated'] = $scoped instanceof Profile
277                             ? $scoped->hasRepeated($notice)
278                             : false;
279
280         if ($status['repeated'] === true) {
281             // Qvitter API wants the "repeated_id" value set too.
282             $repeated = Notice::pkeyGet(array('profile_id' => $scoped->getID(),
283                                               'repeat_of' => $notice->getID(),
284                                               'verb' => ActivityVerb::SHARE));
285             $status['repeated_id'] = $repeated->getID();
286         }
287     }
288
289     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
290     {
291         $userdata['favourites_count'] = Fave::countByProfile($profile);
292     }
293
294     // Command stuff
295
296     /**
297      * EndInterpretCommand for RepeatPlugin will handle the 'repeat' command
298      * using the class RepeatCommand.
299      *
300      * @param string  $cmd     Command being run
301      * @param string  $arg     Rest of the message (including address)
302      * @param User    $user    User sending the message
303      * @param Command &$result The resulting command object to be run.
304      *
305      * @return boolean hook value
306      */
307     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
308     {
309         if ($result === false && in_array($cmd, array('repeat', 'rp', 'rt', 'rd'))) {
310             if (empty($arg)) {
311                 $result = null;
312             } else {
313                 list($other, $extra) = CommandInterpreter::split_arg($arg);
314                 if (!empty($extra)) {
315                     $result = null;
316                 } else {
317                     $result = new RepeatCommand($user, $other);
318                 }
319             }
320             return false;
321         }
322         return true;
323     }
324
325     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
326     {
327         // TRANS: Help message for IM/SMS command "repeat #<notice_id>".
328         $commands['repeat #<notice_id>'] = _m('COMMANDHELP', "repeat a notice with a given id");
329         // TRANS: Help message for IM/SMS command "repeat <nickname>".
330         $commands['repeat <nickname>']   = _m('COMMANDHELP', "repeat the last notice from user");
331     }
332
333     /**
334      * Are we allowed to perform a certain command over the API?
335      */
336     public function onCommandSupportedAPI(Command $cmd, &$supported)
337     {
338         $supported = $supported || $cmd instanceof RepeatCommand;
339     }
340
341     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
342     {
343         // return page title
344     }
345
346     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
347     {
348         // prepare Action?
349     }
350
351     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
352     {
353         // handle repeat POST
354     }
355
356     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
357     {
358         return new RepeatForm($action, $target);
359     }
360
361     public function onPluginVersion(array &$versions)
362     {
363         $versions[] = array('name' => 'Share verb',
364                             'version' => GNUSOCIAL_VERSION,
365                             'author' => 'Mikael Nordfeldth',
366                             'homepage' => 'https://gnu.io/',
367                             'rawdescription' =>
368                             // TRANS: Plugin description.
369                             _m('Shares (repeats) using ActivityStreams.'));
370
371         return true;
372     }
373 }