]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Share/SharePlugin.php
Share never actually set the repeat_of value
[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         try {
102             // First check if we have the shared activity. This has to be done first, because
103             // we can't use these functions to "ensureActivityObjectProfile" of a local user,
104             // who might be the creator of the shared activity in question.
105             $sharedNotice = Notice::getByUri($sharedUri);
106         } catch (NoResultException $e) {
107             // If no locally stored notice is found, process it!
108             // TODO: Remember to check Deleted_notice!
109             // TODO: If a post is shared that we can't retrieve - what to do?
110             $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
111             $sharedNotice = $other->processActivity($shared, 'push');   // FIXME: push/salmon/what?
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.'), $sharedUri));
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 false;
123         }
124
125         // Setting this here because when the algorithm gets back to
126         // Notice::saveActivity it will update the Notice object.
127         $stored->repeat_of = $sharedNotice->getID();
128
129         // We don't have to save a repeat in a separate table, we can
130         // find repeats by just looking at the notice.repeat_of field.
131
132         // By returning true here instead of something that evaluates
133         // to false, we show that we have processed everything properly.
134         return true;
135     }
136
137     // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
138     //          with the other microapps/activityhandlers as well.
139     //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
140     public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
141     {
142         if (!$this->isMyNotice($stored)) {
143             return true;
144         }
145
146         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
147         $this->extendActivity($stored, $act, $scoped);
148         return false;
149     }
150
151     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
152     {
153         // TODO: How to handle repeats of deleted notices?
154         $target = Notice::getById($stored->repeat_of);
155         // TRANS: A repeat activity's title. %1$s is repeater's nickname
156         //        and %2$s is the repeated user's nickname.
157         $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
158                               $stored->getProfile()->getNickname(),
159                               $target->getProfile()->getNickname());
160         $act->objects[] = $target->asActivity($scoped);
161     }
162
163     public function activityObjectFromNotice(Notice $notice)
164     {
165         // Repeat is a little bit special. As it's an activity, our
166         // ActivityObject is instead turned into an Activity
167         $object          = new Activity();
168         $object->verb    = ActivityVerb::SHARE;
169         $object->content = $notice->rendered;
170         $this->extendActivity($stored, $act);
171
172         return $object;
173     }
174
175     public function deleteRelated(Notice $notice)
176     {
177         // No action needed as we don't have a separate table for share objects.
178         return true;
179     }
180
181     // Layout stuff
182
183     public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
184     {
185         if ($nli instanceof ThreadedNoticeListSubItem) {
186             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
187             $item = new ThreadedNoticeListInlineRepeatsItem($notice, $nli->out);
188         } else {
189             $item = new ThreadedNoticeListRepeatsItem($notice, $nli->out);
190         }
191         $threadActive = $item->show() || $threadActive;
192         return true;
193     }
194
195     /**
196      * show the "repeat" form in the notice options element
197      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
198      *
199      * @return void
200      */
201     public function onEndShowNoticeOptionItems($nli)
202     {
203         // FIXME: Use bitmasks (but be aware that PUBLIC_SCOPE is 0!)
204         if ($nli->notice->scope == Notice::PUBLIC_SCOPE ||
205                 $nli->notice->scope == Notice::SITE_SCOPE) {
206             $scoped = Profile::current();
207             if ($scoped instanceof Profile &&
208                     $scoped->getID() !== $nli->notice->getProfile()->getID()) {
209
210                 if ($scoped->hasRepeated($nli->notice)) {
211                     $nli->out->element('span', array('class' => 'repeated',
212                                                       // TRANS: Title for repeat form status in notice list when a notice has been repeated.
213                                                       'title' => _('Notice repeated.')),
214                                         // TRANS: Repeat form status in notice list when a notice has been repeated.
215                                         _('Repeated'));
216                 } else {
217                     $repeat = new RepeatForm($nli->out, $nli->notice);
218                     $repeat->show();
219                 }
220             }
221         }
222     }
223
224     public function showNoticeListItem(NoticeListItem $nli)
225     {
226         // pass
227     }
228     public function openNoticeListItemElement(NoticeListItem $nli)
229     {
230         // pass
231     }
232     public function closeNoticeListItemElement(NoticeListItem $nli)
233     {
234         // pass
235     }
236
237     /**
238      * EndInterpretCommand for RepeatPlugin will handle the 'repeat' command
239      * using the class RepeatCommand.
240      *
241      * @param string  $cmd     Command being run
242      * @param string  $arg     Rest of the message (including address)
243      * @param User    $user    User sending the message
244      * @param Command &$result The resulting command object to be run.
245      *
246      * @return boolean hook value
247      */
248     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
249     {
250         if ($result === false && in_array($cmd, array('repeat', 'rp', 'rt', 'rd'))) {
251             if (empty($arg)) {
252                 $result = null;
253             } else {
254                 list($other, $extra) = CommandInterpreter::split_arg($arg);
255                 if (!empty($extra)) {
256                     $result = null;
257                 } else {
258                     $result = new RepeatCommand($user, $other);
259                 }
260             }
261             return false;
262         }
263         return true;
264     }
265
266     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
267     {
268         // TRANS: Help message for IM/SMS command "repeat #<notice_id>".
269         $commands['repeat #<notice_id>'] = _m('COMMANDHELP', "repeat a notice with a given id");
270         // TRANS: Help message for IM/SMS command "repeat <nickname>".
271         $commands['repeat <nickname>']   = _m('COMMANDHELP', "repeat the last notice from user");
272     }
273
274     /**
275      * Are we allowed to perform a certain command over the API?
276      */
277     public function onCommandSupportedAPI(Command $cmd, &$supported)
278     {
279         $supported = $supported || $cmd instanceof RepeatCommand;
280     }
281
282     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
283     {
284         // return page title
285     }
286
287     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
288     {
289         // prepare Action?
290     }
291
292     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
293     {
294         // handle repeat POST
295     }
296
297     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
298     {
299         return new RepeatForm($action, $target);
300     }
301
302     public function onPluginVersion(array &$versions)
303     {
304         $versions[] = array('name' => 'Share verb',
305                             'version' => GNUSOCIAL_VERSION,
306                             'author' => 'Mikael Nordfeldth',
307                             'homepage' => 'https://gnu.io/',
308                             'rawdescription' =>
309                             // TRANS: Plugin description.
310                             _m('Shares (repeats) using ActivityStreams.'));
311
312         return true;
313     }
314 }