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