]> git.mxchange.org Git - friendica.git/blob - include/onepoll.php
Merge remote-tracking branch 'upstream/develop' into 1507-redmatrix-network-name
[friendica.git] / include / onepoll.php
1 <?php
2
3 require_once("boot.php");
4 require_once("include/follow.php");
5
6 function RemoveReply($subject) {
7         while (in_array(strtolower(substr($subject, 0, 3)), array("re:", "aw:")))
8                 $subject = trim(substr($subject, 4));
9
10         return($subject);
11 }
12
13 function onepoll_run(&$argv, &$argc){
14         global $a, $db;
15
16         if(is_null($a)) {
17                 $a = new App;
18         }
19
20         if(is_null($db)) {
21             @include(".htconfig.php");
22         require_once("include/dba.php");
23             $db = new dba($db_host, $db_user, $db_pass, $db_data);
24         unset($db_host, $db_user, $db_pass, $db_data);
25         };
26
27
28         require_once('include/session.php');
29         require_once('include/datetime.php');
30         require_once('library/simplepie/simplepie.inc');
31         require_once('include/items.php');
32         require_once('include/Contact.php');
33         require_once('include/email.php');
34         require_once('include/socgraph.php');
35         require_once('include/pidfile.php');
36         require_once('include/queue_fn.php');
37
38         load_config('config');
39         load_config('system');
40
41         $a->set_baseurl(get_config('system','url'));
42
43         load_hooks();
44
45         logger('onepoll: start');
46
47         $manual_id  = 0;
48         $generation = 0;
49         $hub_update = false;
50         $force      = false;
51         $restart    = false;
52
53         if(($argc > 1) && (intval($argv[1])))
54                 $contact_id = intval($argv[1]);
55
56         if(! $contact_id) {
57                 logger('onepoll: no contact');
58                 return;
59         }
60
61         $lockpath = get_lockpath();
62         if ($lockpath != '') {
63                 $pidfile = new pidfile($lockpath, 'onepoll'.$contact_id);
64                 if ($pidfile->is_already_running()) {
65                         logger("onepoll: Already running for contact ".$contact_id);
66                         if ($pidfile->running_time() > 9*60) {
67                                 $pidfile->kill();
68                                 logger("killed stale process");
69                         }
70                         exit;
71                 }
72         }
73
74         $d = datetime_convert();
75
76         // Only poll from those with suitable relationships,
77         // and which have a polling address and ignore Diaspora since
78         // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
79
80         $contacts = q("SELECT `contact`.* FROM `contact`
81                 WHERE ( `rel` = %d OR `rel` = %d ) AND `poll` != ''
82                 AND NOT `network` IN ( '%s', '%s', '%s' )
83                 AND `contact`.`id` = %d
84                 AND `self` = 0 AND `contact`.`blocked` = 0 AND `contact`.`readonly` = 0
85                 AND `contact`.`archive` = 0 LIMIT 1",
86                 intval(CONTACT_IS_SHARING),
87                 intval(CONTACT_IS_FRIEND),
88                 dbesc(NETWORK_DIASPORA),
89                 dbesc(NETWORK_FACEBOOK),
90                 dbesc(NETWORK_PUMPIO),
91                 intval($contact_id)
92         );
93
94         if(! count($contacts)) {
95                 // Maybe it is a Redmatrix account. Then we can fetch their contacts via poco
96                 $contacts = q("SELECT `id`, `poco` FROM `contact` WHERE `id` = %d AND `poco` != ''", intval($contact_id));
97                 if ($contacts)
98                         poco_load($contacts[0]['id'],$importer_uid,0,$contacts[0]['poco']);
99                 return;
100         }
101
102         $contact = $contacts[0];
103
104         $xml = false;
105
106         $t = $contact['last-update'];
107
108         if($contact['subhub']) {
109                 $poll_interval = get_config('system','pushpoll_frequency');
110                 $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
111                 $hub_update = false;
112
113                 if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
114                                 $hub_update = true;
115         }
116         else
117                 $hub_update = false;
118
119
120         $importer_uid = $contact['uid'];
121
122         $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `contact`.`uid` = `user`.`uid` WHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
123                 intval($importer_uid)
124         );
125         if(! count($r))
126                 return;
127
128         $importer = $r[0];
129
130         logger("onepoll: poll: ({$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
131
132         $last_update = (($contact['last-update'] === '0000-00-00 00:00:00')
133                 ? datetime_convert('UTC','UTC','now - 7 days', ATOM_TIME)
134                 : datetime_convert('UTC','UTC',$contact['last-update'], ATOM_TIME)
135         );
136
137         // Update the contact entry
138         if(($contact['network'] === NETWORK_OSTATUS) || ($contact['network'] === NETWORK_DIASPORA) || ($contact['network'] === NETWORK_DFRN))
139                 update_contact($contact["id"]);
140
141         if($contact['network'] === NETWORK_DFRN) {
142
143
144                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
145                 if(intval($contact['duplex']) && $contact['dfrn-id'])
146                         $idtosend = '0:' . $orig_id;
147                 if(intval($contact['duplex']) && $contact['issued-id'])
148                         $idtosend = '1:' . $orig_id;
149
150                 // they have permission to write to us. We already filtered this in the contact query.
151                 $perm = 'rw';
152
153                 // But this may be our first communication, so set the writable flag if it isn't set already.
154
155                 if(! intval($contact['writable']))
156                         q("update contact set writable = 1 where id = %d", intval($contact['id']));
157
158
159                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
160                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
161                         . '&type=data&last_update=' . $last_update
162                         . '&perm=' . $perm ;
163
164                 $handshake_xml = fetch_url($url);
165                 $html_code = $a->get_curl_code();
166
167                 logger('onepoll: handshake with url ' . $url . ' returns xml: ' . $handshake_xml, LOGGER_DATA);
168
169
170                 if((! strlen($handshake_xml)) || ($html_code >= 400) || (! $html_code)) {
171                         logger("poller: $url appears to be dead - marking for death ");
172
173                         // dead connection - might be a transient event, or this might
174                         // mean the software was uninstalled or the domain expired.
175                         // Will keep trying for one month.
176
177                         mark_for_death($contact);
178
179                         // set the last-update so we don't keep polling
180                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
181                                 dbesc(datetime_convert()),
182                                 intval($contact['id'])
183                         );
184
185                         return;
186                 }
187
188                 if(! strstr($handshake_xml,'<')) {
189                         logger('poller: response from ' . $url . ' did not contain XML.');
190
191                         mark_for_death($contact);
192
193                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
194                                 dbesc(datetime_convert()),
195                                 intval($contact['id'])
196                         );
197                         return;
198                 }
199
200
201                 $res = parse_xml_string($handshake_xml);
202
203                 if(intval($res->status) == 1) {
204                         logger("poller: $url replied status 1 - marking for death ");
205
206                         // we may not be friends anymore. Will keep trying for one month.
207                         // set the last-update so we don't keep polling
208
209
210                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
211                                 dbesc(datetime_convert()),
212                                 intval($contact['id'])
213                         );
214                         mark_for_death($contact);
215                 }
216                 else {
217                         if($contact['term-date'] != '0000-00-00 00:00:00') {
218                                 logger("poller: $url back from the dead - removing mark for death");
219                                 unmark_for_death($contact);
220                         }
221                 }
222
223                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
224                         return;
225
226                 if(((float) $res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
227                         q("update contact set poco = '%s' where id = %d",
228                                 dbesc(str_replace('/profile/','/poco/', $contact['url'])),
229                                 intval($contact['id'])
230                         );
231                 }
232
233                 $postvars = array();
234
235                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
236                 $challenge    = hex2bin((string) $res->challenge);
237
238                 $final_dfrn_id = '';
239
240                 if(($contact['duplex']) && strlen($contact['prvkey'])) {
241                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
242                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
243                 }
244                 else {
245                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
246                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
247                 }
248
249                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
250
251                 if(strpos($final_dfrn_id,':') == 1)
252                         $final_dfrn_id = substr($final_dfrn_id,2);
253
254                 if($final_dfrn_id != $orig_id) {
255                         logger('poller: ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
256                         // did not decode properly - cannot trust this site
257                         return;
258                 }
259
260                 $postvars['dfrn_id'] = $idtosend;
261                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
262                 $postvars['perm'] = 'rw';
263
264                 $xml = post_url($contact['poll'],$postvars);
265
266         }
267         elseif(($contact['network'] === NETWORK_OSTATUS)
268                 || ($contact['network'] === NETWORK_DIASPORA)
269                 || ($contact['network'] === NETWORK_FEED) ) {
270
271                 // Upgrading DB fields from an older Friendica version
272                 // Will only do this once per notify-enabled OStatus contact
273                 // or if relationship changes
274
275                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['rel'] == CONTACT_IS_FRIEND)) ? 1 : 0);
276
277                 // Contacts from OStatus are always writable
278                 if($contact['network'] === NETWORK_OSTATUS)
279                         $stat_writeable = 1;
280
281                 if($stat_writeable != $contact['writable']) {
282                         q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
283                                 intval($stat_writeable),
284                                 intval($contact['id'])
285                         );
286                 }
287
288                 // Are we allowed to import from this person?
289
290                 if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
291                         return;
292
293                 $xml = fetch_url($contact['poll']);
294         }
295         elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
296
297                 logger("Mail: Fetching", LOGGER_DEBUG);
298
299                 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
300                 if($mail_disabled)
301                         return;
302
303                 logger("Mail: Enabled", LOGGER_DEBUG);
304
305                 $mbox = null;
306                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
307                         intval($importer_uid)
308                 );
309                 $mailconf = q("SELECT * FROM `mailacct` WHERE `server` != '' AND `uid` = %d LIMIT 1",
310                         intval($importer_uid)
311                 );
312                 if(count($x) && count($mailconf)) {
313                     $mailbox = construct_mailbox_name($mailconf[0]);
314                         $password = '';
315                         openssl_private_decrypt(hex2bin($mailconf[0]['pass']),$password,$x[0]['prvkey']);
316                         $mbox = email_connect($mailbox,$mailconf[0]['user'],$password);
317                         unset($password);
318                         logger("Mail: Connect to " . $mailconf[0]['user']);
319                         if($mbox) {
320                                 q("UPDATE `mailacct` SET `last_check` = '%s' WHERE `id` = %d AND `uid` = %d",
321                                         dbesc(datetime_convert()),
322                                         intval($mailconf[0]['id']),
323                                         intval($importer_uid)
324                                 );
325                                 logger("Mail: Connected to " . $mailconf[0]['user']);
326                         } else
327                                 logger("Mail: Connection error ".$mailconf[0]['user']." ".print_r(imap_errors()));
328                 }
329                 if($mbox) {
330
331                         $msgs = email_poll($mbox,$contact['addr']);
332
333                         if(count($msgs)) {
334                                 logger("Mail: Parsing ".count($msgs)." mails for ".$mailconf[0]['user'], LOGGER_DEBUG);
335
336                                 $metas = email_msg_meta($mbox,implode(',',$msgs));
337                                 if(count($metas) != count($msgs)) {
338                                         logger("onepoll: for " . $mailconf[0]['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", LOGGER_DEBUG);
339                                 }
340                                 else {
341                                         $msgs = array_combine($msgs, $metas);
342
343                                         foreach($msgs as $msg_uid => $meta) {
344                                                 logger("Mail: Parsing mail ".$msg_uid, LOGGER_DATA);
345
346                                                 $datarray = array();
347                                                 $datarray['verb'] = ACTIVITY_POST;
348                                                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
349         //                                      $meta = email_msg_meta($mbox,$msg_uid);
350         //                                      $headers = email_msg_headers($mbox,$msg_uid);
351
352                                                 $datarray['uri'] = msgid2iri(trim($meta->message_id,'<>'));
353
354                                                 // Have we seen it before?
355                                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
356                                                         intval($importer_uid),
357                                                         dbesc($datarray['uri'])
358                                                 );
359
360                                                 if(count($r)) {
361                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG);
362
363                                                         // Only delete when mails aren't automatically moved or deleted
364                                                         if (($mailconf[0]['action'] != 1) AND ($mailconf[0]['action'] != 3))
365                                                                 if($meta->deleted && ! $r[0]['deleted']) {
366                                                                         q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `id` = %d",
367                                                                                 dbesc(datetime_convert()),
368                                                                                 intval($r[0]['id'])
369                                                                         );
370                                                                 }
371
372                                                         switch ($mailconf[0]['action']) {
373                                                                 case 0:
374                                                                         logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
375                                                                         break;
376                                                                 case 1:
377                                                                         logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
378                                                                         imap_delete($mbox, $msg_uid, FT_UID);
379                                                                         break;
380                                                                 case 2:
381                                                                         logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
382                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
383                                                                         break;
384                                                                 case 3:
385                                                                         logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
386                                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
387                                                                         if ($mailconf[0]['movetofolder'] != "")
388                                                                                 imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
389                                                                         break;
390                                                         }
391                                                         continue;
392                                                 }
393
394
395                                                 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
396
397         //                                      $raw_refs = ((x($headers,'references')) ? str_replace("\t",'',$headers['references']) : '');
398                                                 $raw_refs = ((property_exists($meta,'references')) ? str_replace("\t",'',$meta->references) : '');
399                                                 if(! trim($raw_refs))
400                                                         $raw_refs = ((property_exists($meta,'in_reply_to')) ? str_replace("\t",'',$meta->in_reply_to) : '');
401                                                 $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
402
403                                                 if($raw_refs) {
404                                                         $refs_arr = explode(' ', $raw_refs);
405                                                         if(count($refs_arr)) {
406                                                                 for($x = 0; $x < count($refs_arr); $x ++)
407                                                                         $refs_arr[$x] = "'" . msgid2iri(str_replace(array('<','>',' '),array('','',''),dbesc($refs_arr[$x]))) . "'";
408                                                         }
409                                                         $qstr = implode(',',$refs_arr);
410                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `uri` IN ( $qstr ) AND `uid` = %d LIMIT 1",
411                                                                 intval($importer_uid)
412                                                         );
413                                                         if(count($r))
414                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];  // Set the parent as the top-level item
415         //                                                      $datarray['parent-uri'] = $r[0]['uri'];
416                                                 }
417
418                                                 // Decoding the header
419                                                 $subject = imap_mime_header_decode($meta->subject);
420                                                 $datarray['title'] = "";
421                                                 foreach($subject as $subpart)
422                                                         if ($subpart->charset != "default")
423                                                                 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
424                                                         else
425                                                                 $datarray['title'] .= $subpart->text;
426
427                                                 $datarray['title'] = notags(trim($datarray['title']));
428
429                                                 //$datarray['title'] = notags(trim($meta->subject));
430                                                 $datarray['created'] = datetime_convert('UTC','UTC',$meta->date);
431
432                                                 // Is it a reply?
433                                                 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") or
434                                                         (substr(strtolower($datarray['title']), 0, 3) == "re-") or
435                                                         ($raw_refs != ""));
436
437                                                 // Remove Reply-signs in the subject
438                                                 $datarray['title'] = RemoveReply($datarray['title']);
439
440                                                 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
441                                                 if(!x($datarray,'parent-uri') and $reply) {
442                                                         $r = q("SELECT `uri` , `parent-uri` FROM `item` WHERE `title` = \"%s\" AND `uid` = %d ORDER BY `created` DESC LIMIT 1",
443                                                                 dbesc(protect_sprintf($datarray['title'])),
444                                                                 intval($importer_uid));
445                                                         if(count($r))
446                                                                 $datarray['parent-uri'] = $r[0]['parent-uri'];
447                                                 }
448
449                                                 if(! x($datarray,'parent-uri'))
450                                                         $datarray['parent-uri'] = $datarray['uri'];
451
452
453                                                 $r = email_get_msg($mbox,$msg_uid, $reply);
454                                                 if(! $r) {
455                                                         logger("Mail: can't fetch msg ".$msg_uid." for ".$mailconf[0]['user']);
456                                                         continue;
457                                                 }
458                                                 $datarray['body'] = escape_tags($r['body']);
459                                                 $datarray['body'] = limit_body_size($datarray['body']);
460
461                                                 logger("Mail: Importing ".$msg_uid." for ".$mailconf[0]['user']);
462
463                                                 // some mailing lists have the original author as 'from' - add this sender info to msg body.
464                                                 // todo: adding a gravatar for the original author would be cool
465
466                                                 if(! stristr($meta->from,$contact['addr'])) {
467                                                         $from = imap_mime_header_decode($meta->from);
468                                                         $fromdecoded = "";
469                                                         foreach($from as $frompart)
470                                                                 if ($frompart->charset != "default")
471                                                                         $fromdecoded .= iconv($frompart->charset, 'UTF-8//IGNORE', $frompart->text);
472                                                                 else
473                                                                         $fromdecoded .= $frompart->text;
474
475                                                         $fromarr = imap_rfc822_parse_adrlist($fromdecoded, $a->get_hostname());
476
477                                                         $frommail = $fromarr[0]->mailbox."@".$fromarr[0]->host;
478
479                                                         if (isset($fromarr[0]->personal))
480                                                                 $fromname = $fromarr[0]->personal;
481                                                         else
482                                                                 $fromname = $frommail;
483
484                                                         //$datarray['body'] = "[b]".t('From: ') . escape_tags($fromdecoded) . "[/b]\n\n" . $datarray['body'];
485
486                                                         $datarray['author-name'] = $fromname;
487                                                         $datarray['author-link'] = "mailto:".$frommail;
488                                                         $datarray['author-avatar'] = $contact['photo'];
489
490                                                         $datarray['owner-name'] = $contact['name'];
491                                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
492                                                         $datarray['owner-avatar'] = $contact['photo'];
493
494                                                 } else {
495                                                         $datarray['author-name'] = $contact['name'];
496                                                         $datarray['author-link'] = 'mailbox';
497                                                         $datarray['author-avatar'] = $contact['photo'];
498                                                 }
499
500                                                 $datarray['uid'] = $importer_uid;
501                                                 $datarray['contact-id'] = $contact['id'];
502                                                 if($datarray['parent-uri'] === $datarray['uri'])
503                                                         $datarray['private'] = 1;
504                                                 if(($contact['network'] === NETWORK_MAIL) && (! get_pconfig($importer_uid,'system','allow_public_email_replies'))) {
505                                                         $datarray['private'] = 1;
506                                                         $datarray['allow_cid'] = '<' . $contact['id'] . '>';
507                                                 }
508
509                                                 $stored_item = item_store($datarray);
510                                                 q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d",
511                                                         dbesc($datarray['parent-uri']),
512                                                         intval($importer_uid)
513                                                 );
514                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
515                                                         intval($stored_item)
516                                                 );
517                                                 switch ($mailconf[0]['action']) {
518                                                         case 0:
519                                                                 logger("Mail: Seen before ".$msg_uid." for ".$mailconf[0]['user'].". Doing nothing.", LOGGER_DEBUG);
520                                                                 break;
521                                                         case 1:
522                                                                 logger("Mail: Deleting ".$msg_uid." for ".$mailconf[0]['user']);
523                                                                 imap_delete($mbox, $msg_uid, FT_UID);
524                                                                 break;
525                                                         case 2:
526                                                                 logger("Mail: Mark as seen ".$msg_uid." for ".$mailconf[0]['user']);
527                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
528                                                                 break;
529                                                         case 3:
530                                                                 logger("Mail: Moving ".$msg_uid." to ".$mailconf[0]['movetofolder']." for ".$mailconf[0]['user']);
531                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
532                                                                 if ($mailconf[0]['movetofolder'] != "")
533                                                                         imap_mail_move($mbox, $msg_uid, $mailconf[0]['movetofolder'], FT_UID);
534                                                                 break;
535                                                 }
536                                         }
537                                 }
538                         } else
539                                 logger("Mail: no mails for ".$mailconf[0]['user']);
540
541                         logger("Mail: closing connection for ".$mailconf[0]['user']);
542                         imap_close($mbox);
543                 }
544         }
545         elseif($contact['network'] === NETWORK_FACEBOOK) {
546                 // This is picked up by the Facebook plugin on a cron hook.
547                 // Ignored here.
548         } elseif($contact['network'] === NETWORK_PUMPIO) {
549                 // This is picked up by the pump.io plugin on a cron hook.
550                 // Ignored here.
551         }
552
553         if($xml) {
554                 logger('poller: received xml : ' . $xml, LOGGER_DATA);
555                 if(! strstr($xml,'<')) {
556                         logger('poller: post_handshake: response from ' . $url . ' did not contain XML.');
557                         $r = q("UPDATE `contact` SET `last-update` = '%s' WHERE `id` = %d",
558                                 dbesc(datetime_convert()),
559                                 intval($contact['id'])
560                         );
561                         return;
562                 }
563
564
565                 consume_feed($xml,$importer,$contact,$hub,1,1);
566
567
568                 // do it twice. Ensures that children of parents which may be later in the stream aren't tossed
569
570                 consume_feed($xml,$importer,$contact,$hub,1,2);
571
572                 $hubmode = 'subscribe';
573                 if($contact['network'] === NETWORK_DFRN || $contact['blocked'] || $contact['readonly'])
574                         $hubmode = 'unsubscribe';
575
576                 if(($contact['network'] === NETWORK_OSTATUS ||  $contact['network'] == NETWORK_FEED) && (! $contact['hub-verify']))
577                         $hub_update = true;
578
579                 if((strlen($hub)) && ($hub_update) && (($contact['rel'] != CONTACT_IS_FOLLOWER) || $contact['network'] == NETWORK_FEED) ) {
580                         logger('poller: hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
581                         $hubs = explode(',', $hub);
582                         if(count($hubs)) {
583                                 foreach($hubs as $h) {
584                                         $h = trim($h);
585                                         if(! strlen($h))
586                                                 continue;
587                                         subscribe_to_hub($h,$importer,$contact,$hubmode);
588                                 }
589                         }
590                 }
591         }
592
593         $updated = datetime_convert();
594
595         $r = q("UPDATE `contact` SET `last-update` = '%s', `success_update` = '%s' WHERE `id` = %d",
596                 dbesc($updated),
597                 dbesc($updated),
598                 intval($contact['id'])
599         );
600
601
602         // load current friends if possible.
603
604         if($contact['poco']) {
605                 $r = q("SELECT count(*) as total from glink
606                         where `cid` = %d and updated > UTC_TIMESTAMP() - INTERVAL 1 DAY",
607                         intval($contact['id'])
608                 );
609         }
610         if(count($r)) {
611                 if(! $r[0]['total']) {
612                         poco_load($contact['id'],$importer_uid,0,$contact['poco']);
613                 }
614         }
615
616         return;
617 }
618
619 if (array_search(__file__,get_included_files())===0){
620   onepoll_run($_SERVER["argv"],$_SERVER["argc"]);
621   killme();
622 }