]> git.mxchange.org Git - friendica.git/blob - include/Scrape.php
Merge branch 'master' of git://github.com/friendika/friendika
[friendica.git] / include / Scrape.php
1 <?php
2
3 require_once('library/HTML5/Parser.php');
4
5 if(! function_exists('scrape_dfrn')) {
6 function scrape_dfrn($url) {
7
8         $a = get_app();
9
10         $ret = array();
11
12         logger('scrape_dfrn: url=' . $url);
13
14         $s = fetch_url($url);
15
16         if(! $s) 
17                 return $ret;
18
19         $headers = $a->get_curl_headers();
20         logger('scrape_dfrn: headers=' . $headers, LOGGER_DEBUG);
21
22
23         $lines = explode("\n",$headers);
24         if(count($lines)) {
25                 foreach($lines as $line) {                              
26                         // don't try and run feeds through the html5 parser
27                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
28                                 return ret;
29                 }
30         }
31
32
33         $dom = HTML5_Parser::parse($s);
34
35         if(! $dom)
36                 return $ret;
37
38         $items = $dom->getElementsByTagName('link');
39
40         // get DFRN link elements
41
42         foreach($items as $item) {
43                 $x = $item->getAttribute('rel');
44                 if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml'))
45                         $ret['feed_atom'] = $item->getAttribute('href');
46                 if(substr($x,0,5) == "dfrn-")
47                         $ret[$x] = $item->getAttribute('href');
48                 if($x === 'lrdd') {
49                         $decoded = urldecode($item->getAttribute('href'));
50                         if(preg_match('/acct:([^@]*)@/',$decoded,$matches))
51                                 $ret['nick'] = $matches[1];
52                 }
53         }
54
55         // Pull out hCard profile elements
56
57         $items = $dom->getElementsByTagName('*');
58         foreach($items as $item) {
59                 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
60                         $level2 = $item->getElementsByTagName('*');
61                         foreach($level2 as $x) {
62                                 if(attribute_contains($x->getAttribute('class'),'fn'))
63                                         $ret['fn'] = $x->textContent;
64                                 if(attribute_contains($x->getAttribute('class'),'photo'))
65                                         $ret['photo'] = $x->getAttribute('src');
66                                 if(attribute_contains($x->getAttribute('class'),'key'))
67                                         $ret['key'] = $x->textContent;
68                         }
69                 }
70         }
71
72         return $ret;
73 }}
74
75
76
77
78
79
80 if(! function_exists('validate_dfrn')) {
81 function validate_dfrn($a) {
82         $errors = 0;
83         if(! x($a,'key'))
84                 $errors ++;
85         if(! x($a,'dfrn-request'))
86                 $errors ++;
87         if(! x($a,'dfrn-confirm'))
88                 $errors ++;
89         if(! x($a,'dfrn-notify'))
90                 $errors ++;
91         if(! x($a,'dfrn-poll'))
92                 $errors ++;
93         return $errors;
94 }}
95
96 if(! function_exists('scrape_meta')) {
97 function scrape_meta($url) {
98
99         $a = get_app();
100
101         $ret = array();
102
103         logger('scrape_meta: url=' . $url);
104
105         $s = fetch_url($url);
106
107         if(! $s) 
108                 return $ret;
109
110         $headers = $a->get_curl_headers();
111         logger('scrape_meta: headers=' . $headers, LOGGER_DEBUG);
112
113         $lines = explode("\n",$headers);
114         if(count($lines)) {
115                 foreach($lines as $line) {                              
116                         // don't try and run feeds through the html5 parser
117                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
118                                 return ret;
119                 }
120         }
121
122
123
124         $dom = HTML5_Parser::parse($s);
125
126         if(! $dom)
127                 return $ret;
128
129         $items = $dom->getElementsByTagName('meta');
130
131         // get DFRN link elements
132
133         foreach($items as $item) {
134                 $x = $item->getAttribute('name');
135                 if(substr($x,0,5) == "dfrn-")
136                         $ret[$x] = $item->getAttribute('content');
137         }
138
139         return $ret;
140 }}
141
142
143 if(! function_exists('scrape_vcard')) {
144 function scrape_vcard($url) {
145
146         $a = get_app();
147
148         $ret = array();
149
150         logger('scrape_vcard: url=' . $url);
151
152         $s = fetch_url($url);
153
154         if(! $s) 
155                 return $ret;
156
157         $headers = $a->get_curl_headers();
158         $lines = explode("\n",$headers);
159         if(count($lines)) {
160                 foreach($lines as $line) {                              
161                         // don't try and run feeds through the html5 parser
162                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
163                                 return ret;
164                 }
165         }
166
167         $dom = HTML5_Parser::parse($s);
168
169         if(! $dom)
170                 return $ret;
171
172         // Pull out hCard profile elements
173
174         $items = $dom->getElementsByTagName('*');
175         foreach($items as $item) {
176                 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
177                         $level2 = $item->getElementsByTagName('*');
178                         foreach($level2 as $x) {
179                                 if(attribute_contains($x->getAttribute('class'),'fn'))
180                                         $ret['fn'] = $x->textContent;
181                                 if((attribute_contains($x->getAttribute('class'),'photo'))
182                                         || (attribute_contains($x->getAttribute('class'),'avatar')))
183                                         $ret['photo'] = $x->getAttribute('src');
184                                 if((attribute_contains($x->getAttribute('class'),'nickname'))
185                                         || (attribute_contains($x->getAttribute('class'),'uid')))
186                                         $ret['nick'] = $x->textContent;
187                         }
188                 }
189         }
190
191         return $ret;
192 }}
193
194
195 if(! function_exists('scrape_feed')) {
196 function scrape_feed($url) {
197
198         $a = get_app();
199
200         $ret = array();
201         $s = fetch_url($url);
202
203         if(! $s) 
204                 return $ret;
205
206         $headers = $a->get_curl_headers();
207         logger('scrape_feed: headers=' . $headers, LOGGER_DEBUG);
208
209         $lines = explode("\n",$headers);
210         if(count($lines)) {
211                 foreach($lines as $line) {                              
212                         if(stristr($line,'content-type:')) {
213                                 if(stristr($line,'application/atom+xml') || stristr($s,'<feed')) {
214                                         $ret['feed_atom'] = $url;
215                                         return $ret;
216                                 }
217                                 if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
218                                         $ret['feed_rss'] = $url;
219                                         return $ret;
220                                 }
221                         }
222                 }
223         }
224
225         $dom = HTML5_Parser::parse($s);
226
227         if(! $dom)
228                 return $ret;
229
230
231         $items = $dom->getElementsByTagName('img');
232
233         // get img elements (twitter)
234
235         if($items) {
236                 foreach($items as $item) {
237                         $x = $item->getAttribute('id');
238                         if($x === 'profile-image') {
239                                 $ret['photo'] = $item->getAttribute('src');
240                         }
241                 }
242         }
243
244
245         $head = $dom->getElementsByTagName('base');
246         if($head) {
247                 foreach($head as $head0) {
248                         $basename = $head0->getAttribute('href');
249                         break;
250                 }
251         }
252         if(! $basename)
253                 $basename = substr($url,0,strrpos($url,'/')) . '/';
254
255         $items = $dom->getElementsByTagName('link');
256
257         // get Atom/RSS link elements, take the first one of either.
258
259         if($items) {
260                 foreach($items as $item) {
261                         $x = $item->getAttribute('rel');
262                         if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml')) {
263                                 if(! x($ret,'feed_atom'))
264                                         $ret['feed_atom'] = $item->getAttribute('href');
265                         }
266                         if(($x === 'alternate') && ($item->getAttribute('type') === 'application/rss+xml')) {
267                                 if(! x($ret,'feed_rss'))
268                                         $ret['feed_rss'] = $item->getAttribute('href');
269                         }
270                 }       
271         }
272
273         // Drupal and perhaps others only provide relative URL's. Turn them into absolute.
274
275         if(x($ret,'feed_atom') && (! strstr($ret['feed_atom'],'://')))
276                 $ret['feed_atom'] = $basename . $ret['feed_atom'];
277         if(x($ret,'feed_rss') && (! strstr($ret['feed_rss'],'://')))
278                 $ret['feed_rss'] = $basename . $ret['feed_rss'];
279
280         return $ret;
281 }}
282
283
284 function probe_url($url) {
285         require_once('include/email.php');
286
287         $result = array();
288
289         if(! $url)
290                 return $result;
291
292         $diaspora = false;      
293         $email_conversant = false;
294
295         $twitter = ((strpos($url,'twitter.com') !== false) ? true : false);
296
297         if(! $twitter) {
298                 $links = lrdd($url);
299
300                 if(count($links)) {
301                         logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
302                         foreach($links as $link) {
303                                 if($link['@attributes']['rel'] === NAMESPACE_ZOT)
304                                         $zot = unamp($link['@attributes']['href']);
305                                 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
306                                         $dfrn = unamp($link['@attributes']['href']);
307                                 if($link['@attributes']['rel'] === 'salmon')
308                                         $notify = unamp($link['@attributes']['href']);
309                                 if($link['@attributes']['rel'] === NAMESPACE_FEED)
310                                         $poll = unamp($link['@attributes']['href']);
311                                 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
312                                         $hcard = unamp($link['@attributes']['href']);
313                                 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
314                                         $profile = unamp($link['@attributes']['href']);
315                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location')
316                                         $diaspora = true;
317                         }
318
319                         // Status.Net can have more than one profile URL. We need to match the profile URL
320                         // to a contact on incoming messages to prevent spam, and we won't know which one
321                         // to match. So in case of two, one of them is stored as an alias. Only store URL's
322                         // and not webfinger user@host aliases. If they've got more than two non-email style
323                         // aliases, let's hope we're lucky and get one that matches the feed author-uri because 
324                         // otherwise we're screwed.
325
326                         foreach($links as $link) {
327                                 if($link['@attributes']['rel'] === 'alias') {
328                                         if(strpos($link['@attributes']['href'],'@') === false) {
329                                                 if(isset($profile)) {
330                                                         if($link['@attributes']['href'] !== $profile)
331                                                                 $alias = unamp($link['@attributes']['href']);
332                                                 }
333                                                 else
334                                                         $profile = unamp($link['@attributes']['href']);
335                                         }
336                                 }
337                         }
338                 }
339                 else {
340
341                         // Check email
342
343                         $orig_url = $url;
344                         if((strpos($orig_url,'@')) && validate_email($orig_url)) {
345                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
346                                         intval(local_user())
347                                 );
348                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
349                                         intval(local_user())
350                                 );
351                                 if(count($x) && count($r)) {
352                                     $mailbox = construct_mailbox_name($r[0]);
353                                         $password = '';
354                                         openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
355                                         $mbox = email_connect($mailbox,$r[0]['user'],$password);
356                                         unset($password);
357                                 }
358                                 if($mbox) {
359                                         $msgs = email_poll($mbox,$orig_url);
360                                         if(count($msgs)) {
361                                                 $addr = $orig_url;
362                                                 $network = NETWORK_MAIL;
363                                                 $name = substr($url,0,strpos($url,'@'));
364                                                 $profile = 'http://' . substr($url,strpos($url,'@')+1);
365                                                 // fix nick character range
366                                                 $vcard = array('fn' => $name, 'nick' => $name, 'photo' => gravatar_img($url));
367                                                 $notify = 'smtp ' . random_string();
368                                                 $poll = 'email ' . random_string();
369                                                 $priority = 0;
370                                                 $x = email_msg_meta($mbox,$msgs[0]);
371                                                 if(stristr($x->from,$orig_url))
372                                                         $adr = imap_rfc822_parse_adrlist($x->from,'');
373                                                 elseif(stristr($x->to,$orig_url))
374                                                         $adr = imap_rfc822_parse_adrlist($x->to,'');
375                                                 if(isset($adr) && strlen($adr[0]->personal))
376                                                         $vcard['fn'] = notags($adr[0]->personal);
377                                         }
378                                         imap_close($mbox);
379                                 }
380                         }
381                 }
382         }       
383
384         if(strlen($zot)) {
385                 $s = fetch_url($zot);
386                 if($s) {
387                         $j = json_decode($s);
388                         if($j) {
389                                 $network = NETWORK_ZOT;
390                                 $vcard   = array(
391                                         'fn'    => $j->fullname, 
392                                         'nick'  => $j->nickname, 
393                                         'photo' => $j->photo
394                                 );
395                                 $profile  = $j->url;
396                                 $notify   = $j->post;
397                                 $pubkey   = $j->pubkey;
398                                 $poll     = 'N/A';
399                         }
400                 }
401         }
402
403         if(strlen($dfrn)) {
404                 $ret = scrape_dfrn($dfrn);
405                 if(is_array($ret) && x($ret,'dfrn-request')) {
406                         $network = NETWORK_DFRN;
407                         $request = $ret['dfrn-request'];
408                         $confirm = $ret['dfrn-confirm'];
409                         $notify  = $ret['dfrn-notify'];
410                         $poll    = $ret['dfrn-poll'];
411                 }
412         }
413
414         if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
415                 $network  = NETWORK_OSTATUS;
416                 $priority = 0;
417
418                 if($hcard) {
419                         $vcard = scrape_vcard($hcard);
420
421                         // Google doesn't use absolute url in profile photos
422         
423                         if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
424                                 $h = @parse_url($hcard);
425                                 if($h)
426                                         $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
427                         }
428                 
429                         logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
430                 }
431
432                 if(! $profile) {
433                         if($diaspora)
434                                 $profile = $hcard;
435                         else
436                                 $profile = $url;
437                 }
438
439                 if($twitter) {          
440                         logger('twitter: setup');
441                         $tid = basename($url);
442                         $tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
443                         if(intval($tid))
444                                 $poll = $tapi . '?user_id=' . $tid;
445                         else
446                                 $poll = $tapi . '?screen_name=' . $tid;
447                         $profile = 'http://twitter.com/#!/' . $tid;
448                 }
449
450                 if(! x($vcard,'fn'))
451                         if(x($vcard,'nick'))
452                                 $vcard['fn'] = $vcard['nick'];
453
454         
455                 if(((! isset($vcard)) && (! $poll)) || ($twitter)) {
456
457                         $feedret = scrape_feed($url);
458                         logger('probe_url: scrape_feed returns: ' . print_r($feedret,true), LOGGER_DATA);
459                         if(count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
460                                 $poll = ((x($feedret,'feed_atom')) ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']));
461                                 $vcard = array();
462                         }
463
464                         if(x($feedret,'photo'))
465                                 $vcard['photo'] = $feedret['photo'];
466                         require_once('library/simplepie/simplepie.inc');
467                     $feed = new SimplePie();
468                         $xml = fetch_url($poll);
469
470                         logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
471                         $a = get_app();
472
473                         logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), $LOGGER_DATA);
474
475                         $feed->set_raw_data($xml);
476
477                     $feed->init();
478                         if($feed->error())
479                                 logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
480
481                         if(! x($vcard,'photo'))
482                                 $vcard['photo'] = $feed->get_image_url();
483                         $author = $feed->get_author();
484                         if($author) {                   
485                                 $vcard['fn'] = unxmlify(trim($author->get_name()));
486                                 if(! $vcard['fn'])
487                                         $vcard['fn'] = trim(unxmlify($author->get_email()));
488                                 if(strpos($vcard['fn'],'@') !== false)
489                                         $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
490                                 $email = unxmlify($author->get_email());
491                                 if(! $vcard['photo']) {
492                                         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
493                                 if($rawtags) {
494                                                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
495                                                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
496                                                         $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
497                                 }
498                                 }
499                         }
500                         else {
501                                 $item = $feed->get_item(0);
502                                 if($item) {
503                                         $author = $item->get_author();
504                                         if($author) {                   
505                                                 $vcard['fn'] = trim(unxmlify($author->get_name()));
506                                                 if(! $vcard['fn'])
507                                                         $vcard['fn'] = trim(unxmlify($author->get_email()));
508                                                 if(strpos($vcard['fn'],'@') !== false)
509                                                         $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
510                                                 $email = unxmlify($author->get_email());
511                                         }
512                                         if(! $vcard['photo']) {
513                                                 $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/','thumbnail');
514                                                 if($rawmedia && $rawmedia[0]['attribs']['']['url'])
515                                                         $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
516                                         }
517                                         if(! $vcard['photo']) {
518                                                 $rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
519                                         if($rawtags) {
520                                                         $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
521                                                         if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
522                                                                 $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
523                                         }
524                                         }
525                                 }
526                         }
527                         if((! $vcard['photo']) && strlen($email))
528                                 $vcard['photo'] = gravatar_img($email);
529                         if($poll === $profile)
530                                 $lnk = $feed->get_permalink();
531                         if(isset($lnk) && strlen($lnk))
532                                 $profile = $lnk;        
533
534                         if(! (x($vcard,'fn')))
535                                 $vcard['fn'] = notags($feed->get_title());
536                         if(! (x($vcard,'fn')))
537                                 $vcard['fn'] = notags($feed->get_description());
538
539                         if(strpos($vcard['fn'],'Twitter / ') !== false) {
540                                 $vcard['fn'] = substr($vcard['fn'],strpos($vcard['fn'],'/')+1);
541                                 $vcard['fn'] = trim($vcard['fn']);
542                         }
543                         if(! x($vcard,'nick')) {
544                                 $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
545                                 if(strpos($vcard['nick'],' '))
546                                         $vcard['nick'] = trim(substr($vcard['nick'],0,strpos($vcard['nick'],' ')));
547                         }
548                         $network = 'feed';
549                         $priority = 2;
550                 }
551         }
552
553         if(! x($vcard,'photo')) {
554                 $a = get_app();
555                 $vcard['photo'] = $a->get_baseurl() . '/images/default-profile.jpg' ; 
556         }
557         $vcard['fn'] = notags($vcard['fn']);
558         $vcard['nick'] = notags($vcard['nick']);
559
560
561         $result['name'] = $vcard['fn'];
562         $result['nick'] = $vcard['nick'];
563         $result['url'] = $profile;
564         $result['addr'] = $addr;
565         $result['notify'] = $notify;
566         $result['poll'] = $poll;
567         $result['request'] = $request;
568         $result['confirm'] = $confirm;
569         $result['photo'] = $vcard['photo'];
570         $result['priority'] = $priority;
571         $result['network'] = $network;
572         $result['alias'] = $alias;
573         $result['pubkey'] = $pubkey;
574
575         logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
576
577         return $result;
578 }