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