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