]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Linkback/lib/util.php
Use strpos check properly
[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) === 0) {
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) === FALSE) {
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()) !== FALSE) {
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) !== FALSE; })) > 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) !== FALSE; })) > 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) !== FALSE) {
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) != FALSE; })) > 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) != FALSE; })) > 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 = isset($entry['content']) ? $entry['content'][0]['html'] :
205               (isset($entry['summary']) ? $entry['summary'][0] : $entry['name'][0]);
206
207     $rendered = common_purify($content);
208
209     if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
210         $name = isset($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 (isset($entry['published']) || isset($entry['updated'])) {
245         $options['created'] = isset($entry['published'])
246                                 ? common_sql_date($entry['published'][0])
247                                 : common_sql_date($entry['updated'][0]);
248     }
249
250     if (isset($entry['photo']) && common_valid_http_url($entry['photo'])) {
251         $options['urls'][] = $entry['photo'][0];
252     } elseif (isset($entry['photo'])) {
253         common_debug('Linkback got invalid HTTP URL for photo: '._ve($entry['photo']));
254     }
255
256     foreach((array)$entry['category'] as $tag) {
257         $tag = common_canonical_tag($tag);
258         if($tag) { $options['tags'][] = $tag; }
259     }
260
261
262     if($mf2['rels'] && $mf2['rels']['enclosure']) {
263         foreach($mf2['rels']['enclosure'] as $url) {
264             $options['urls'][] = $url;
265         }
266     }
267
268     if($mf2['rels'] && $mf2['rels']['tag']) {
269         foreach($mf2['rels']['tag'] as $url) {
270             preg_match('/\/([^\/]+)\/*$/', $url, $match);
271             $tag = common_canonical_tag($match[1]);
272             if($tag) { $options['tags'][] = $tag; }
273          }
274     }
275
276     if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
277         $options['urls'] = array();
278     }
279
280     return array($content, $options);
281 }
282
283 function linkback_profile($entry, $mf2, $response, $target) {
284     if(isset($entry['properties']['author']) && isset($entry['properties']['author'][0]['properties'])) {
285         $author = $entry['properties']['author'][0]['properties'];
286     } else {
287         $author = linkback_hcard($mf2, $response->getEffectiveUrl());
288     }
289
290     if(!$author) {
291         $author = array('name' => $entry['name']);
292     }
293
294     if (!isset($author['url']) || empty($author['url'])) {
295         $author['url'] = array($response->getEffectiveUrl());
296     }
297
298     $user = User::getKV('uri', $author['url'][0]);
299     if ($user instanceof User) {
300         common_log(LOG_INFO, "Linkback: ignoring linkback from local user: $url");
301         return true;
302     }
303
304     try {
305         $profile = Profile::fromUri($author['url'][0]);
306     } catch(UnknownUriException $ex) {
307         $profile = Profile::getKV('profileurl', $author['url'][0]);
308     }
309
310     // XXX: Is this a good way to create the profile?
311     if (!$profile instanceof Profile) {
312         $profile = new Profile();
313         $profile->profileurl = $author['url'][0];
314         $profile->fullname = $author['name'][0];
315         $profile->nickname = isset($author['nickname']) ? $author['nickname'][0] : str_replace(' ', '', $author['name'][0]);
316         $profile->created = common_sql_now();
317         $profile->insert();
318     }
319
320     return array($profile, $author);
321 }
322
323 function linkback_save($source, $target, $response, $notice_or_user) {
324     $dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
325     if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
326     if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
327     if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
328
329     $mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
330     $mf2 = $mf2->parse();
331
332     $entry = linkback_find_entry($mf2, $target);
333     if(!$entry) {
334         preg_match('/<title>([^<]+)', $response->getBody(), $match);
335         $entry = array(
336             'content' => array('html' => $response->getBody()),
337             'name' => $match[1] ? htmlspecialchars_decode($match[1]) : $source
338         );
339     }
340
341     if(!$entry['url']) {
342         $entry['url'] = array($response->getEffectiveUrl());
343     }
344
345     if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
346     if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
347
348     $entry['type'] = linkback_entry_type($entry, $mf2, $target);
349     list($profile, $author) =  linkback_profile($entry, $mf2, $response, $target);
350     list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
351
352     if($dupe) {
353         $orig = clone($dupe);
354
355         try {
356             // Ignore duplicate save error
357             try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
358             try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
359             try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
360
361             if($options['reply_to']) { $dupe->reply_to = $options['reply_to']; }
362             if($options['repeat_of']) { $dupe->repeat_of = $options['repeat_of']; }
363             if($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
364                 $parent = Notice::getKV('id', $dupe->repost_of ? $dupe->repost_of : $dupe->reply_to);
365                 if($parent instanceof Notice) {
366                     // If we changed the reply_to or repeat_of we might live in a new conversation now
367                     $dupe->conversation = $parent->conversation;
368                 }
369             }
370             if($dupe->update($orig)) { $saved = $dupe; }
371             if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
372                 // Delete empty conversation
373                 $emptyConversation = Conversation::getKV('id', $orig->conversation);
374                 $emptyConversation->delete();
375             }
376         } catch (Exception $e) {
377             common_log(LOG_ERR, "Linkback update of remote message $source failed: " . $e->getMessage());
378             return false;
379         }
380         common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
381     } else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
382         $act = new Activity();
383         $act->type    = ActivityObject::ACTIVITY;
384         $act->time    = $options['created'] ? strtotime($options['created']) : time();
385         $act->title   = $entry["name"] ? $entry["name"][0] : _m("Favor");
386         $act->actor   = $profile->asActivityObject();
387         $act->target  = $notice_or_user->asActivityObject();
388         $act->objects = array(clone($act->target));
389
390         // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
391         //        notice's nickname and %3$s is the content of the favorited notice.)
392         $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
393                                 $profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
394                                 $notice_or_user->getRendered());
395         if($entry['rsvp']) {
396             $act->content = $options['rendered'];
397         }
398
399         $act->verb    = ActivityVerb::FAVORITE;
400         if(strtolower($entry['rsvp'][0]) == 'yes') {
401             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
402         } else if(strtolower($entry['rsvp'][0]) == 'no') {
403             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
404         } else if(strtolower($entry['rsvp'][0]) == 'maybe') {
405             $act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
406         }
407
408         $act->id = $source;
409         $act->link = $entry['url'][0];
410
411         $options['source'] = 'linkback';
412         $options['mentions'] = $options['replies'];
413         unset($options['reply_to']);
414         unset($options['repeat_of']);
415
416         try {
417             $saved = Notice::saveActivity($act, $profile, $options);
418         } catch (Exception $e) {
419             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
420             return false;
421         }
422         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
423     } else {
424         // Fallback is to make a notice manually
425         try {
426             $saved = Notice::saveNew($profile->id,
427                                      $content,
428                                      'linkback',
429                                      $options);
430         } catch (Exception $e) {
431             common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
432             return false;
433         }
434         common_log(LOG_INFO, "Linkback saved remote message $source as notice id $saved->id");
435     }
436
437     return $saved->getLocalUrl();
438 }