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