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