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