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