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