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