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