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