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