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