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