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