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