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