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