]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/lib/util.php
Linkback to user should work
[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('uri', $url);
146     if ($dupe instanceof Notice) {
147         common_log(LOG_INFO, "Linkback: ignoring duplicate post: $url");
148         return $dupe;
149     }
150
151     return false;
152 }
153
154
155 function linkback_hcard($mf2, $url) {
156     if(empty($mf2['items'])) {
157         return null;
158     }
159   
160     $hcards = array();
161     foreach($mf2['items'] as $item) {
162         if(!in_array('h-card', $item['type'])) {
163             continue;
164         }
165       
166         // We found a match, return it immediately
167         if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
168             return $item['properties'];
169       
170             // Let's keep all the hcards for later, to return one of them at least
171             $hcards[] = $item['properties'];
172         }
173     }
174   
175     // No match immediately for the url we expected, but there were h-cards found
176     if (count($hcards) > 0) {
177         return $hcards[0];
178     }
179   
180     return null;
181 }
182
183 function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
184     $content = $entry['content'] ? $entry['content'][0]['html'] :
185               ($entry['summary'] ? $entry['sumary'][0] : $entry['name'][0]);
186
187     $rendered = common_purify($content);
188
189     if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
190         $name = $entry['name'] ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
191         $rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
192     }
193
194     $content = common_strip_html($rendered);
195     $shortened = common_shorten_links($content);
196     if(Notice::contentTooLong($shortened)) {
197         $content = substr($content,
198                           0,
199                           Notice::maxContent() - (mb_strlen($source) + 2));
200         $rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
201         $content .= ' ' . $source;
202     }
203
204     $options = array('is_local' => Notice::REMOTE,
205                     'url' => $entry['url'][0],
206                     'uri' => $source,
207                     'rendered' => $rendered,
208                     'replies' => array(),
209                     'groups' => array(),
210                     'peopletags' => array(),
211                     'tags' => array(),
212                     'urls' => array());
213
214     if($notice_or_user instanceof User) {
215         $options['replies'][] = $notice_or_user->getUri();
216     } else {
217         if($entry['type'] == 'repost') {
218             $options['repeat_of'] = $notice_or_user->id;
219         } else {
220             $options['reply_to'] = $notice_or_user->id;
221         }
222     }
223
224     if($entry['published'] || $entry['updated']) {
225         $options['created'] = $entry['published'] ? common_sql_date($entry['published'][0]) : common_sql_date($entry['updated'][0]);
226     }
227
228     if($entry['photo']) {
229         $options['urls'][] = $entry['photo'][0];
230     }
231
232     foreach((array)$entry['category'] as $tag) {
233         $tag = common_canonical_tag($tag);
234         if($tag) { $options['tags'][] = $tag; }
235     }
236
237
238     if($mf2['rels'] && $mf2['rels']['enclosure']) {
239         foreach($mf2['rels']['enclosure'] as $url) {
240             $options['urls'][] = $url;
241         }
242     }
243
244     if($mf2['rels'] && $mf2['rels']['tag']) {
245         foreach($mf2['rels']['tag'] as $url) {
246             preg_match('/\/([^\/]+)\/*$/', $url, $match);
247             $tag = common_canonical_tag($match[1]);
248             if($tag) { $options['tags'][] = $tag; }
249          }
250     }
251
252     if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
253         $options['urls'] = array();
254     }
255
256     return array($content, $options);
257 }
258
259 function linkback_profile($entry, $mf2, $response, $target) {
260     if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
261         $author = $entry['properties']['author'][0]['properties'];
262     } else {
263         $author = linkback_hcard($mf2, $response->getEffectiveUrl());
264     }
265
266     if(!$author) {
267         $author = array('name' => array($entry['name']));
268     }
269
270     if(!$author['url']) {
271         $author['url'] = array($response->getEffectiveUrl());
272     }
273
274     $user = User::getKV('uri', $author['url'][0]);
275     if ($user instanceof User) {
276         common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
277         return true;
278     }
279
280     $profile = Profile::fromUri($author['url'][0]);
281     if(!($profile instanceof Profile)) {
282         $profile = Profile::getKV('profileurl', $author['url'][0]);
283     }
284
285     if(!($profile instanceof Profile)) {
286         $profile = new Profile();
287         $profile->profileurl = $author['url'][0];
288         $profile->fullname = $author['name'][0];
289         $profile->nickname = $author['nickname'] ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
290         $profile->created = common_sql_now();
291         $profile->insert();
292     }
293
294     return array($profile, $author);
295 }
296
297 function linkback_save($source, $target, $response, $notice_or_user) {
298     if($dupe = linkback_is_dupe('uri', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
299     if($dupe = linkback_is_dupe('url', $response->getEffectiveUrl())) { return $dupe->getLocalUrl(); }
300     if($dupe = linkback_is_dupe('uri', $source)) { return $dupe->getLocalUrl(); }
301     if($dupe = linkback_is_dupe('url', $source)) { return $dupe->getLocalUrl(); }
302
303     $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
304     $mf2 = $mf2->parse();
305
306     $entry = linkback_find_entry($mf2, $target);
307     if(!$entry) {
308         preg_match('/<title>([^<]+)', $response->getBody(), $match);
309         $entry = array(
310             'content' => array('html' => $response->getBody()),
311             'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
312         );
313     }
314
315     if(!$entry['url']) {
316         $entry['url'] = array($response->getEffectiveUrl());
317     }
318
319     if($dupe = linkback_is_dupe('uri', $entry['url'][0])) { return $dupe->getLocalUrl(); }
320     if($dupe = linkback_is_dupe('url', $entry['url'][0])) { return $dupe->getLocalUrl(); }
321
322     $entry['type'] = linkback_entry_type($entry, $mf2, $target);
323     list($profile, $author) =  linkback_profile($entry, $mf2, $response, $target);
324     list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
325
326     if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
327         $act = new Activity();
328         $act->type    = ActivityObject::ACTIVITY;
329         $act->time    = $options['created'] ? strtotime($options['created']) : time();
330         $act->title   = $entry["name"] ? $entry["name"][0] : _m("Favor");
331         $act->actor   = $profile->asActivityObject();
332         $act->target  = $notice_or_user->asActivityObject();
333         $act->objects = array(clone($act->target));
334
335         // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
336         //        notice's nickname and %3$s is the content of the favorited notice.)
337         $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
338                                 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
339                                 $notice_or_user->rendered ?: $notice_or_user->content);
340         if($entry['rsvp']) {
341             $act->content = $options['rendered'];
342         }
343
344         $act->verb    = ActivityVerb::FAVORITE;
345         if(strtolower($entry['rsvp'][0]) == 'yes') {
346             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
347         } else if(strtolower($entry['rsvp'][0]) == 'no') {
348             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
349         } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
350             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
351         }
352
353         $act->id = $source;
354         $act->link = $entry['url'][0];
355
356         $options['source'] = 'linkback';
357         $options['mentions'] = $options['replies'];
358         unset($options['reply_to']);
359         unset($options['repeat_of']);
360
361         try {
362             $saved = Notice::saveActivity($act, $profile, $options);
363         } catch (Exception $e) {
364             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
365             return false;
366         }
367         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
368     } else {
369         // Fallback is to make a notice manually
370         try {
371             $saved = Notice::saveNew($profile->id,
372                                      $content,
373                                      'linkback',
374                                      $options);
375         } catch (Exception $e) {
376             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
377             return false;
378         }
379         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
380     }
381
382     return $saved->getLocalUrl();
383 }