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