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