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