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