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