]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/lib/util.php
Ignore non-local notices as targets
[quix0rs-gnu-social.git] / plugins / Linkback / lib / util.php
1 <?php
2
3 function linkback_lenient_target_match($body, $target) {
4     return strpos(''.$body, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', preg_replace('/\/+$/', '', preg_replace( '/#.*/', '', $target))));
5 }
6
7 function linkback_get_source($source, $target) {
8     $request = HTTPClient::start();
9
10     try {
11         $response = $request->get($source);
12     } catch(Exception $ex) {
13         return NULL;
14     }
15
16     $body = htmlspecialchars_decode($response->getBody());
17     // We're slightly more lenient in our link detection than the spec requires
18     if(!linkback_lenient_target_match($body, $target)) {
19         return NULL;
20     }
21
22     return $response;
23 }
24
25 function linkback_get_target($target) {
26     // TODO: linkback to a user should work for attention
27     // Resolve target (https://github.com/converspace/webmention/issues/43)
28     $request = HTTPClient::start();
29
30     try {
31         $response = $request->head($target);
32     } catch(Exception $ex) {
33         return NULL;
34     }
35
36     try {
37         $notice = Notice::fromUri($response->getEffectiveUrl());
38     } catch(UnknownUriException $ex) {
39         preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
40         $notice = Notice::getKV('id', $match[1]);
41     }
42
43     if($notice instanceof Notice && $notice->isLocal()) {
44         return $notice;
45     }
46
47     return NULL;
48 }
49
50 // Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
51 function linkback_find_entry($mf2, $target) {
52     if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
53         $mf2['items'] = $mf2['items'][0]['children'];
54     }
55
56     $entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
57
58     foreach ($entries as $entry) {
59         foreach ((array)$entry['properties'] as $key => $values) {
60             if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
61                 return $entry['properties'];
62             }
63
64             // check included h-* formats and their links
65             foreach ($values as $obj) {
66                 if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
67                    isset($obj['properties']) && isset($obj['properties']['url']) &&
68                    count(array_filter($obj['properties']['url'],
69                          function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
70                 ) {
71                     return $entry['properties'];
72                 }
73             }
74
75             // check content for the link
76             if ($key == "content" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]['html']), $context)) {
77                 return $entry['properties'];
78             // check summary for the link
79             } elseif ($key == "summary" && preg_match_all("/<a[^>]+?".preg_quote($target, "/")."[^>]*>([^>]+?)<\/a>/i", htmlspecialchars_decode($values[0]), $context)) {
80                 return $entry['properties'];
81             }
82         }
83     }
84
85     // Default to first one
86     if(count($entries) > 0) {
87         return $entries[0]['properties'];
88     }
89
90     return NULL;
91 }
92
93 function linkback_entry_type($entry, $mf2, $target) {
94     if(!$entry) { return 'mention'; }
95
96     if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
97         foreach($mf2['rels']['in-reply-to'] as $url) {
98             if(linkback_lenient_target_match($url, $target)) {
99                 return 'reply';
100             }
101         }
102     }
103
104     $classes = array(
105         'in-reply-to' => 'reply',
106         'repost-of' => 'repost',
107         'like-of' => 'like',
108         'tag-of' => 'tag'
109     );
110
111     foreach((array)$entry as $key => $values) {
112         if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0) {
113             if($classes[$key]) { return $classes[$key]; }
114         }
115
116         foreach ($values as $obj) {
117             if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
118                isset($obj['properties']) && isset($obj['properties']['url']) &&
119                count(array_filter($obj['properties']['url'],
120                      function($x) use ($target) { return linkback_lenient_target_match($x, $target); })) > 0
121             ) {
122                 if($classes[$key]) { return $classes[$key]; }
123             }
124         }
125     }
126
127     return 'mention';
128 }
129
130 function linkback_is_dupe($key, $url) {
131     $dupe = Notice::getKV('uri', $url);
132     if ($dupe instanceof Notice) {
133         common_log(LOG_INFO, "Linkback: ignoring duplicate post: $url");
134         return $dupe;
135     }
136
137     return false;
138 }
139
140
141 function linkback_hcard($mf2, $url) {
142     if(empty($mf2['items'])) {
143         return null;
144     }
145   
146     $hcards = array();
147     foreach($mf2['items'] as $item) {
148         if(!in_array('h-card', $item['type'])) {
149             continue;
150         }
151       
152         // We found a match, return it immediately
153         if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
154             return $item['properties'];
155       
156             // Let's keep all the hcards for later, to return one of them at least
157             $hcards[] = $item['properties'];
158         }
159     }
160   
161     // No match immediately for the url we expected, but there were h-cards found
162     if (count($hcards) > 0) {
163         return $hcards[0];
164     }
165   
166     return null;
167 }
168
169 function linkback_notice($source, $notice, $entry, $author, $mf2) {
170     $content = $entry['content'] ? $entry['content'][0]['html'] :
171               ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
172
173     $rendered = common_purify($content);
174
175     if($entry['type'] == 'mention') {
176         $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
177         $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
178     }
179
180     $content = common_strip_html($rendered);
181     $shortened = common_shorten_links($content);
182     if(Notice::contentTooLong($shortened)) {
183         $content = substr($content,
184                           0,
185                           Notice::maxContent() - (mb_strlen($source) + 2));
186         $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
187         $content .= ' ' . $source;
188     }
189
190     $options = array('is_local' => Notice::REMOTE,
191                     'url' => $entry['url'][0],
192                     'uri' => $source,
193                     'rendered' => $rendered,
194                     'replies' => array(),
195                     'groups' => array(),
196                     'peopletags' => array(),
197                     'tags' => array(),
198                     'urls' => array());
199
200     // TODO: when mentioning a user and not a post, neither of these but set replies above
201     if($entry['type'] == 'repost') {
202         $options['repeat_of'] = $notice->id;
203     } else {
204         $options['reply_to'] = $notice->id;
205     }
206
207     if($entry['published'] || $entry['updated']) {
208         $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
209     }
210
211     if($entry['photo']) {
212         $options['urls'][] = $entry['photo'][0];
213     }
214
215     foreach((array)$entry['category'] as $tag) {
216         $tag = common_canonical_tag($tag);
217         if($tag) { $options['tags'][] = $tag; }
218     }
219
220
221     if($mf2['rels'] && $mf2['rels']['enclosure']) {
222         foreach($mf2['rels']['enclosure'] as $url) {
223             $options['urls'][] = $url;
224         }
225     }
226
227     if($mf2['rels'] && $mf2['rels']['tag']) {
228         foreach($mf2['rels']['tag'] as $url) {
229             preg_match('/\/([^\/]+)\/*$/', $url, $match);
230             $tag = common_canonical_tag($match[1]);
231             if($tag) { $options['tags'][] = $tag; }
232          }
233     }
234
235     if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
236         $options['urls'] = array();
237     }
238
239     return array($content, $options);
240 }
241
242 function linkback_profile($entry, $mf2, $response, $target) {
243     if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
244         $author = $entry['properties']['author'][0]['properties'];
245     } else {
246         $author = linkback_hcard($mf2, $response->getEffectiveUrl());
247     }
248
249     if(!$author) {
250         $author = array('name' => array($entry['name']));
251     }
252
253     if(!$author['url']) {
254         $author['url'] = array($response->getEffectiveUrl());
255     }
256
257     $user = User::getKV('uri', $author['url'][0]);
258     if ($user instanceof User) {
259         common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
260         return true;
261     }
262
263     $profile = Profile::fromUri($author['url'][0]);
264     if(!($profile instanceof Profile)) {
265         $profile = Profile::getKV('profileurl', $author['url'][0]);
266     }
267
268     if(!($profile instanceof Profile)) {
269         $profile = new Profile();
270         $profile->profileurl = $author['url'][0];
271         $profile->fullname = $author['name'][0];
272         $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
273         $profile->created = common_sql_now();
274         $profile->insert();
275     }
276
277     return array($profile, $author);
278 }
279
280 function linkback_save($source, $target, $response, $notice) {
281     if($dupe = linkback_is_dupe('uri', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
282     if($dupe = linkback_is_dupe('url', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
283     if($dupe = linkback_is_dupe('uri', $source)) { return $dupe->getLocalUrl(); }
284     if($dupe = linkback_is_dupe('url', $source)) { return $dupe->getLocalUrl(); }
285
286     $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
287     $mf2 = $mf2->parse();
288
289     $entry = linkback_find_entry($mf2, $target);
290     if(!$entry) {
291         preg_match('/<title>([^<]+)', $response->getBody(), $match);
292         $entry = array(
293             'content' => array('html' => $response->getBody()),
294             'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
295         );
296     }
297
298     if(!$entry['url']) {
299         $entry['url'] = array($response->getEffectiveUrl());
300     }
301
302     if($dupe = linkback_is_dupe('uri', $entry['url'][0])) { return $dupe->getLocalUrl(); }
303     if($dupe = linkback_is_dupe('url', $entry['url'][0])) { return $dupe->getLocalUrl(); }
304
305     $entry['type'] = linkback_entry_type($entry, $mf2, $target);
306     list($profile, $author) =  linkback_profile($entry, $mf2, $response, $target);
307     list($content, $options) = linkback_notice($source, $notice, $entry, $author, $mf2);
308
309     if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
310         $act = new Activity();
311         $act->type    = ActivityObject::ACTIVITY;
312         $act->time    = $options['created'] ? strtotime($options['created']) : time();
313         $act->title   = $entry["name"] ? $entry["name"][0] : _m("Favor");
314         $act->actor   = $profile->asActivityObject();
315         $act->target  = $notice->asActivityObject();
316         $act->objects = array(clone($act->target));
317
318         // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
319         //        notice's nickname and %3$s is the content of the favorited notice.)
320         $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
321                                 $profile->getNickname(), $notice->getProfile()->getNickname(),
322                                 $notice->rendered ?: $notice->content);
323         if($entry['rsvp']) {
324             $act->content = $options['rendered'];
325         }
326
327         $act->verb    = ActivityVerb::FAVORITE;
328         if(strtolower($entry['rsvp'][0]) == 'yes') {
329             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
330         } else if(strtolower($entry['rsvp'][0]) == 'no') {
331             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
332         } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
333             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
334         }
335
336         $act->id = $source;
337         $act->link = $entry['url'][0];
338
339         $options['source'] = 'linkback';
340         $options['mentions'] = $options['replies'];
341         unset($options['reply_to']);
342         unset($options['repeat_of']);
343
344         try {
345             $saved = Notice::saveActivity($act, $profile, $options);
346         } catch (Exception $e) {
347             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
348             return false;
349         }
350         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
351     } else {
352         // Fallback is to make a notice manually
353         try {
354             $saved = Notice::saveNew($profile->id,
355                                      $content,
356                                      'linkback',
357                                      $options);
358         } catch (Exception $e) {
359             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
360             return false;
361         }
362         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
363     }
364
365     return $saved->getLocalUrl();
366 }