]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
App::get_baseurl is now replaced with System::baseUrl
[friendica.git] / include / dfrn.php
1 <?php
2 /**
3  * @file include/dfrn.php
4  * @brief The implementation of the dfrn protocol
5  *
6  * @see https://github.com/friendica/friendica/wiki/Protocol and
7  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
8  */
9
10 use Friendica\App;
11 use Friendica\Core\System;
12
13 require_once("include/Contact.php");
14 require_once("include/ostatus.php");
15 require_once("include/enotify.php");
16 require_once("include/threads.php");
17 require_once("include/socgraph.php");
18 require_once("include/items.php");
19 require_once("include/tags.php");
20 require_once("include/files.php");
21 require_once("include/event.php");
22 require_once("include/text.php");
23 require_once("include/oembed.php");
24 require_once("include/html2bbcode.php");
25 require_once("include/bbcode.php");
26 require_once("include/xml.php");
27
28 /**
29  * @brief This class contain functions to create and send DFRN XML files
30  *
31  */
32 class dfrn {
33
34         const DFRN_TOP_LEVEL = 0;       // Top level posting
35         const DFRN_REPLY = 1;           // Regular reply that is stored locally
36         const DFRN_REPLY_RC = 2;        // Reply that will be relayed
37
38         /**
39          * @brief Generates the atom entries for delivery.php
40          *
41          * This function is used whenever content is transmitted via DFRN.
42          *
43          * @param array $items Item elements
44          * @param array $owner Owner record
45          *
46          * @return string DFRN entries
47          * @todo Add type-hints
48          */
49         public static function entries($items,$owner) {
50
51                 $doc = new DOMDocument('1.0', 'utf-8');
52                 $doc->formatOutput = true;
53
54                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
55
56                 if (! count($items)) {
57                         return trim($doc->saveXML());
58                 }
59
60                 foreach ($items as $item) {
61                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
62                         $root->appendChild($entry);
63                 }
64
65                 return(trim($doc->saveXML()));
66         }
67
68         /**
69          * @brief Generate an atom feed for the given user
70          *
71          * This function is called when another server is pulling data from the user feed.
72          *
73          * @param string $dfrn_id DFRN ID from the requesting party
74          * @param string $owner_nick Owner nick name
75          * @param string $last_update Date of the last update
76          * @param int $direction Can be -1, 0 or 1.
77          * @param boolean $onlyheader Output only the header without content? (Default is "no")
78          *
79          * @return string DFRN feed entries
80          */
81         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
82
83                 $a = get_app();
84
85                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
86                 $public_feed = (($dfrn_id) ? false : true);
87                 $starred     = false;   // not yet implemented, possible security issues
88                 $converse    = false;
89
90                 if ($public_feed && $a->argc > 2) {
91                         for ($x = 2; $x < $a->argc; $x++) {
92                                 if ($a->argv[$x] == 'converse') {
93                                         $converse = true;
94                                 }
95                                 if ($a->argv[$x] == 'starred') {
96                                         $starred = true;
97                                 }
98                                 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
99                                         $category = $a->argv[$x+1];
100                                 }
101                         }
102                 }
103
104
105
106                 // default permissions - anonymous user
107
108                 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
109
110                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
111                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
112                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
113                         dbesc($owner_nick)
114                 );
115
116                 if (! dbm::is_result($r)) {
117                         killme();
118                 }
119
120                 $owner = $r[0];
121                 $owner_id = $owner['uid'];
122                 $owner_nick = $owner['nickname'];
123
124                 $sql_post_table = "";
125
126                 if (! $public_feed) {
127
128                         $sql_extra = '';
129                         switch($direction) {
130                                 case (-1):
131                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
132                                         $my_id = $dfrn_id;
133                                         break;
134                                 case 0:
135                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
136                                         $my_id = '1:' . $dfrn_id;
137                                         break;
138                                 case 1:
139                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
140                                         $my_id = '0:' . $dfrn_id;
141                                         break;
142                                 default:
143                                         return false;
144                                         break; // NOTREACHED
145                         }
146
147                         $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
148                                 intval($owner_id)
149                         );
150
151                         if (! dbm::is_result($r)) {
152                                 killme();
153                         }
154
155                         $contact = $r[0];
156                         require_once('include/security.php');
157                         $groups = init_groups_visitor($contact['id']);
158
159                         if (count($groups)) {
160                                 for ($x = 0; $x < count($groups); $x ++)
161                                         $groups[$x] = '<' . intval($groups[$x]) . '>' ;
162                                 $gs = implode('|', $groups);
163                         } else {
164                                 $gs = '<<>>' ; // Impossible to match
165                         }
166
167                         $sql_extra = sprintf("
168                                 AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
169                                 AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
170                                 AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
171                                 AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
172                         ",
173                                 intval($contact['id']),
174                                 intval($contact['id']),
175                                 dbesc($gs),
176                                 dbesc($gs)
177                         );
178                 }
179
180                 if ($public_feed) {
181                         $sort = 'DESC';
182                 } else {
183                         $sort = 'ASC';
184                 }
185
186                 if (! strlen($last_update)) {
187                         $last_update = 'now -30 days';
188                 }
189
190                 if (isset($category)) {
191                         $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
192                                         dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
193                         //$sql_extra .= file_tag_file_query('item',$category,'category');
194                 }
195
196                 if ($public_feed) {
197                         if (! $converse) {
198                                 $sql_extra .= " AND `contact`.`self` = 1 ";
199                         }
200                 }
201
202                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
203
204                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
205                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
206                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
207                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
208                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
209                         FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
210                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
211                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
212                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
213                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
214                         AND `item`.`wall` AND `item`.`changed` > '%s'
215                         $sql_extra
216                         ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
217                         intval($owner_id),
218                         dbesc($check_date),
219                         dbesc($sort)
220                 );
221
222                 /*
223                  * Will check further below if this actually returned results.
224                  * We will provide an empty feed if that is the case.
225                  */
226
227                 $items = $r;
228
229                 $doc = new DOMDocument('1.0', 'utf-8');
230                 $doc->formatOutput = true;
231
232                 $alternatelink = $owner['url'];
233
234                 if (isset($category)) {
235                         $alternatelink .= "/category/".$category;
236                 }
237
238                 if ($public_feed) {
239                         $author = "dfrn:owner";
240                 } else {
241                         $author = "author";
242                 }
243
244                 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
245
246                 /// @TODO This hook can't work anymore
247                 //      call_hooks('atom_feed', $atom);
248
249                 if (!dbm::is_result($items) || $onlyheader) {
250                         $atom = trim($doc->saveXML());
251
252                         call_hooks('atom_feed_end', $atom);
253
254                         return $atom;
255                 }
256
257                 foreach ($items as $item) {
258
259                         // prevent private email from leaking.
260                         if ($item['network'] == NETWORK_MAIL) {
261                                 continue;
262                         }
263
264                         // public feeds get html, our own nodes use bbcode
265
266                         if ($public_feed) {
267                                 $type = 'html';
268                                 // catch any email that's in a public conversation and make sure it doesn't leak
269                                 if ($item['private']) {
270                                         continue;
271                                 }
272                         } else {
273                                 $type = 'text';
274                         }
275
276                         $entry = self::entry($doc, $type, $item, $owner, true);
277                         $root->appendChild($entry);
278
279                 }
280
281                 $atom = trim($doc->saveXML());
282
283                 call_hooks('atom_feed_end', $atom);
284
285                 return $atom;
286         }
287
288         /**
289          * @brief Generate an atom entry for a given item id
290          *
291          * @param int $item_id The item id
292          *
293          * @return string DFRN feed entry
294          */
295         public static function itemFeed($item_id) {
296                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
297                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
298                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
299                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
300                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
301                         FROM `item`
302                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
303                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
304                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
305                         WHERE `item`.`id` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
306                         AND `item`.`wall` AND NOT `item`.`private`",
307                         intval($item_id)
308                 );
309
310                 if (!dbm::is_result($r)) {
311                         killme();
312                 }
313
314                 $item = $r[0];
315
316                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
317                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
318                         WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
319                         intval($item['uid'])
320                 );
321
322                 if (!dbm::is_result($r)) {
323                         killme();
324                 }
325
326                 $owner = $r[0];
327
328                 $doc = new DOMDocument('1.0', 'utf-8');
329                 $doc->formatOutput = true;
330
331                 $alternatelink = $owner['url'];
332
333                 $root = self::add_header($doc, $owner, 'dfrn:owner', $alternatelink, true);
334
335                 $type = 'html';
336
337                 $entry = self::entry($doc, $type, $item, $owner, true);
338                 $root->appendChild($entry);
339
340                 $atom = trim($doc->saveXML());
341                 return $atom;
342         }
343
344         /**
345          * @brief Create XML text for DFRN mails
346          *
347          * @param array $item message elements
348          * @param array $owner Owner record
349          *
350          * @return string DFRN mail
351          * @todo Add type-hints
352          */
353         public static function mail($item, $owner) {
354                 $doc = new DOMDocument('1.0', 'utf-8');
355                 $doc->formatOutput = true;
356
357                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
358
359                 $mail = $doc->createElement("dfrn:mail");
360                 $sender = $doc->createElement("dfrn:sender");
361
362                 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
363                 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
364                 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
365
366                 $mail->appendChild($sender);
367
368                 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
369                 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
370                 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
371                 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
372                 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
373
374                 $root->appendChild($mail);
375
376                 return(trim($doc->saveXML()));
377         }
378
379         /**
380          * @brief Create XML text for DFRN friend suggestions
381          *
382          * @param array $item suggestion elements
383          * @param array $owner Owner record
384          *
385          * @return string DFRN suggestions
386          * @todo Add type-hints
387          */
388         public static function fsuggest($item, $owner) {
389                 $doc = new DOMDocument('1.0', 'utf-8');
390                 $doc->formatOutput = true;
391
392                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
393
394                 $suggest = $doc->createElement("dfrn:suggest");
395
396                 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
397                 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
398                 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
399                 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
400                 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
401
402                 $root->appendChild($suggest);
403
404                 return(trim($doc->saveXML()));
405         }
406
407         /**
408          * @brief Create XML text for DFRN relocations
409          *
410          * @param array $owner Owner record
411          * @param int $uid User ID
412          *
413          * @return string DFRN relocations
414          * @todo Add type-hints
415          */
416         public static function relocate($owner, $uid) {
417
418                 /* get site pubkey. this could be a new installation with no site keys*/
419                 $pubkey = get_config('system','site_pubkey');
420                 if (! $pubkey) {
421                         $res = new_keypair(1024);
422                         set_config('system','site_prvkey', $res['prvkey']);
423                         set_config('system','site_pubkey', $res['pubkey']);
424                 }
425
426                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
427                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
428                 $photos = array();
429                 $ext = Photo::supportedTypes();
430
431                 foreach ($rp as $p) {
432                         $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
433                 }
434
435                 unset($rp, $ext);
436
437                 $doc = new DOMDocument('1.0', 'utf-8');
438                 $doc->formatOutput = true;
439
440                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
441
442                 $relocate = $doc->createElement("dfrn:relocate");
443
444                 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
445                 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
446                 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
447                 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
448                 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
449                 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
450                 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
451                 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
452                 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
453                 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
454                 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
455                 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
456
457                 $root->appendChild($relocate);
458
459                 return(trim($doc->saveXML()));
460         }
461
462         /**
463          * @brief Adds the header elements for the DFRN protocol
464          *
465          * @param object $doc XML document
466          * @param array $owner Owner record
467          * @param string $authorelement Element name for the author
468          * @param string $alternatelink link to profile or category
469          * @param bool $public Is it a header for public posts?
470          *
471          * @return object XML root object
472          * @todo Add type-hints
473          */
474         private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
475
476                 if ($alternatelink == "") {
477                         $alternatelink = $owner['url'];
478                 }
479
480                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
481                 $doc->appendChild($root);
482
483                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
484                 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
485                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
486                 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
487                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
488                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
489                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
490                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
491                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
492
493                 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
494                 xml::add_element($doc, $root, "title", $owner["name"]);
495
496                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
497                 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
498
499                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
500                 xml::add_element($doc, $root, "link", "", $attributes);
501
502                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
503                 xml::add_element($doc, $root, "link", "", $attributes);
504
505
506                 if ($public) {
507                         // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
508                         ostatus::hublinks($doc, $root, $owner["nick"]);
509
510                         $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
511                         xml::add_element($doc, $root, "link", "", $attributes);
512
513                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
514                         xml::add_element($doc, $root, "link", "", $attributes);
515
516                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
517                         xml::add_element($doc, $root, "link", "", $attributes);
518                 }
519
520                 // For backward compatibility we keep this element
521                 if ($owner['page-flags'] == PAGE_COMMUNITY) {
522                         xml::add_element($doc, $root, "dfrn:community", 1);
523                 }
524
525                 // The former element is replaced by this one
526                 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
527
528                 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
529
530                 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
531
532                 $author = self::add_author($doc, $owner, $authorelement, $public);
533                 $root->appendChild($author);
534
535                 return $root;
536         }
537
538         /**
539          * @brief Adds the author element in the header for the DFRN protocol
540          *
541          * @param object $doc XML document
542          * @param array $owner Owner record
543          * @param string $authorelement Element name for the author
544          *
545          * @return object XML author object
546          * @todo Add type-hints
547          */
548         private static function add_author($doc, $owner, $authorelement, $public) {
549
550                 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
551                 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
552                                 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
553                         intval($owner['uid']));
554                 if (dbm::is_result($r)) {
555                         $hidewall = true;
556                 } else {
557                         $hidewall = false;
558                 }
559
560                 $author = $doc->createElement($authorelement);
561
562                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
563                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
564                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
565
566                 $attributes = array();
567
568                 if (!$public || !$hidewall) {
569                         $attributes = array("dfrn:updated" => $namdate);
570                 }
571
572                 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
573                 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
574                 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
575
576                 $attributes = array("rel" => "photo", "type" => "image/jpeg",
577                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
578
579                 if (!$public || !$hidewall) {
580                         $attributes["dfrn:updated"] = $picdate;
581                 }
582
583                 xml::add_element($doc, $author, "link", "", $attributes);
584
585                 $attributes["rel"] = "avatar";
586                 xml::add_element($doc, $author, "link", "", $attributes);
587
588                 if ($hidewall) {
589                         xml::add_element($doc, $author, "dfrn:hide", "true");
590                 }
591
592                 // The following fields will only be generated if the data isn't meant for a public feed
593                 if ($public) {
594                         return $author;
595                 }
596
597                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
598
599                 if ($birthday)
600                         xml::add_element($doc, $author, "dfrn:birthday", $birthday);
601
602                 // Only show contact details when we are allowed to
603                 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
604                                 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
605                                 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
606                         FROM `profile`
607                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
608                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
609                         intval($owner['uid']));
610                 if (dbm::is_result($r)) {
611                         $profile = $r[0];
612
613                         xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
614                         xml::add_element($doc, $author, "poco:updated", $namdate);
615
616                         if (trim($profile["dob"]) > '0001-01-01') {
617                                 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
618                         }
619
620                         xml::add_element($doc, $author, "poco:note", $profile["about"]);
621                         xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
622
623                         $savetz = date_default_timezone_get();
624                         date_default_timezone_set($profile["timezone"]);
625                         xml::add_element($doc, $author, "poco:utcOffset", date("P"));
626                         date_default_timezone_set($savetz);
627
628                         if (trim($profile["homepage"]) != "") {
629                                 $urls = $doc->createElement("poco:urls");
630                                 xml::add_element($doc, $urls, "poco:type", "homepage");
631                                 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
632                                 xml::add_element($doc, $urls, "poco:primary", "true");
633                                 $author->appendChild($urls);
634                         }
635
636                         if (trim($profile["pub_keywords"]) != "") {
637                                 $keywords = explode(",", $profile["pub_keywords"]);
638
639                                 foreach ($keywords AS $keyword) {
640                                         xml::add_element($doc, $author, "poco:tags", trim($keyword));
641                                 }
642
643                         }
644
645                         if (trim($profile["xmpp"]) != "") {
646                                 $ims = $doc->createElement("poco:ims");
647                                 xml::add_element($doc, $ims, "poco:type", "xmpp");
648                                 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
649                                 xml::add_element($doc, $ims, "poco:primary", "true");
650                                 $author->appendChild($ims);
651                         }
652
653                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
654                                 $element = $doc->createElement("poco:address");
655
656                                 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
657
658                                 if (trim($profile["locality"]) != "") {
659                                         xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
660                                 }
661
662                                 if (trim($profile["region"]) != "") {
663                                         xml::add_element($doc, $element, "poco:region", $profile["region"]);
664                                 }
665
666                                 if (trim($profile["country-name"]) != "") {
667                                         xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
668                                 }
669
670                                 $author->appendChild($element);
671                         }
672                 }
673
674                 return $author;
675         }
676
677         /**
678          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
679          *
680          * @param object $doc XML document
681          * @param string $element Element name for the author
682          * @param string $contact_url Link of the contact
683          * @param array $items Item elements
684          *
685          * @return object XML author object
686          * @todo Add type-hints
687          */
688         private static function add_entry_author($doc, $element, $contact_url, $item) {
689
690                 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
691
692                 $author = $doc->createElement($element);
693                 xml::add_element($doc, $author, "name", $contact["name"]);
694                 xml::add_element($doc, $author, "uri", $contact["url"]);
695                 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
696
697                 /// @Todo
698                 /// - Check real image type and image size
699                 /// - Check which of these boths elements we should use
700                 $attributes = array(
701                                 "rel" => "photo",
702                                 "type" => "image/jpeg",
703                                 "media:width" => 80,
704                                 "media:height" => 80,
705                                 "href" => $contact["photo"]);
706                 xml::add_element($doc, $author, "link", "", $attributes);
707
708                 $attributes = array(
709                                 "rel" => "avatar",
710                                 "type" => "image/jpeg",
711                                 "media:width" => 80,
712                                 "media:height" => 80,
713                                 "href" => $contact["photo"]);
714                 xml::add_element($doc, $author, "link", "", $attributes);
715
716                 return $author;
717         }
718
719         /**
720          * @brief Adds the activity elements
721          *
722          * @param object $doc XML document
723          * @param string $element Element name for the activity
724          * @param string $activity activity value
725          *
726          * @return object XML activity object
727          * @todo Add type-hints
728          */
729         private static function create_activity($doc, $element, $activity) {
730
731                 if ($activity) {
732                         $entry = $doc->createElement($element);
733
734                         $r = parse_xml_string($activity, false);
735                         if (!$r) {
736                                 return false;
737                         }
738                         if ($r->type) {
739                                 xml::add_element($doc, $entry, "activity:object-type", $r->type);
740                         }
741                         if ($r->id) {
742                                 xml::add_element($doc, $entry, "id", $r->id);
743                         }
744                         if ($r->title) {
745                                 xml::add_element($doc, $entry, "title", $r->title);
746                         }
747
748                         if ($r->link) {
749                                 if (substr($r->link, 0, 1) == '<') {
750                                         if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
751                                                 $r->link = str_replace('&', '&amp;', $r->link);
752                                         }
753
754                                         $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
755
756                                         // XML does need a single element as root element so we add a dummy element here
757                                         $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
758                                         if (is_object($data)) {
759                                                 foreach ($data->link AS $link) {
760                                                         $attributes = array();
761                                                         foreach ($link->attributes() AS $parameter => $value) {
762                                                                 $attributes[$parameter] = $value;
763                                                         }
764                                                         xml::add_element($doc, $entry, "link", "", $attributes);
765                                                 }
766                                         }
767                                 } else {
768                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
769                                         xml::add_element($doc, $entry, "link", "", $attributes);
770                                 }
771                         }
772                         if ($r->content) {
773                                 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
774                         }
775
776                         return $entry;
777                 }
778
779                 return false;
780         }
781
782         /**
783          * @brief Adds the elements for attachments
784          *
785          * @param object $doc XML document
786          * @param object $root XML root
787          * @param array $item Item element
788          *
789          * @return object XML attachment object
790          * @todo Add type-hints
791          */
792         private static function get_attachment($doc, $root, $item) {
793                 $arr = explode('[/attach],',$item['attach']);
794                 if (count($arr)) {
795                         foreach ($arr as $r) {
796                                 $matches = false;
797                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
798                                 if ($cnt) {
799                                         $attributes = array("rel" => "enclosure",
800                                                         "href" => $matches[1],
801                                                         "type" => $matches[3]);
802
803                                         if (intval($matches[2])) {
804                                                 $attributes["length"] = intval($matches[2]);
805                                         }
806
807                                         if (trim($matches[4]) != "") {
808                                                 $attributes["title"] = trim($matches[4]);
809                                         }
810
811                                         xml::add_element($doc, $root, "link", "", $attributes);
812                                 }
813                         }
814                 }
815         }
816
817         /**
818          * @brief Adds the "entry" elements for the DFRN protocol
819          *
820          * @param object $doc XML document
821          * @param string $type "text" or "html"
822          * @param array $item Item element
823          * @param array $owner Owner record
824          * @param bool $comment Trigger the sending of the "comment" element
825          * @param int $cid Contact ID of the recipient
826          *
827          * @return object XML entry object
828          * @todo Add type-hints
829          */
830         private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
831
832                 $mentioned = array();
833
834                 if (!$item['parent']) {
835                         return;
836                 }
837
838                 if ($item['deleted']) {
839                         $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
840                         return xml::create_element($doc, "at:deleted-entry", "", $attributes);
841                 }
842
843                 $entry = $doc->createElement("entry");
844
845                 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
846                         $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
847                 } else {
848                         $body = $item['body'];
849                 }
850
851                 // Remove the abstract element. It is only locally important.
852                 $body = remove_abstract($body);
853
854                 if ($type == 'html') {
855                         $htmlbody = $body;
856
857                         if ($item['title'] != "") {
858                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
859                         }
860
861                         $htmlbody = bbcode($htmlbody, false, false, 7);
862                 }
863
864                 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
865                 $entry->appendChild($author);
866
867                 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
868                 $entry->appendChild($dfrnowner);
869
870                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
871                         $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
872                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
873                         $attributes = array("ref" => $parent_item, "type" => "text/html",
874                                                 "href" => System::baseUrl().'/display/'.$parent[0]['guid'],
875                                                 "dfrn:diaspora_guid" => $parent[0]['guid']);
876                         xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
877                 }
878
879                 // Add conversation data. This is used for OStatus
880                 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
881                 $conversation_uri = $conversation_href;
882
883                 if (isset($parent_item)) {
884                         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
885                         if (dbm::is_result($r)) {
886                                 if ($r['conversation-uri'] != '') {
887                                         $conversation_uri = $r['conversation-uri'];
888                                 }
889                                 if ($r['conversation-href'] != '') {
890                                         $conversation_href = $r['conversation-href'];
891                                 }
892                         }
893                 }
894
895                 $attributes = array(
896                                 "href" => $conversation_href,
897                                 "ref" => $conversation_uri);
898
899                 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
900
901                 xml::add_element($doc, $entry, "id", $item["uri"]);
902                 xml::add_element($doc, $entry, "title", $item["title"]);
903
904                 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
905                 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
906
907                 // "dfrn:env" is used to read the content
908                 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
909
910                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
911                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
912                 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
913
914                 // We save this value in "plink". Maybe we should read it from there as well?
915                 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
916                                                                 "href" => System::baseUrl()."/display/".$item["guid"]));
917
918                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
919                 // It is included in the rewritten code for completeness
920                 if ($comment) {
921                         xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
922                 }
923
924                 if ($item['location']) {
925                         xml::add_element($doc, $entry, "dfrn:location", $item['location']);
926                 }
927
928                 if ($item['coord']) {
929                         xml::add_element($doc, $entry, "georss:point", $item['coord']);
930                 }
931
932                 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
933                         xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
934                 }
935
936                 if ($item['extid']) {
937                         xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
938                 }
939
940                 if ($item['bookmark']) {
941                         xml::add_element($doc, $entry, "dfrn:bookmark", "true");
942                 }
943
944                 if ($item['app']) {
945                         xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
946                 }
947
948                 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
949
950                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
951                 // It is needed for relayed comments to Diaspora.
952                 if ($item['signed_text']) {
953                         $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
954                         xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
955                 }
956
957                 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
958
959                 if ($item['object-type'] != "") {
960                         xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
961                 } elseif ($item['id'] == $item['parent']) {
962                         xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
963                 } else {
964                         xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
965                 }
966
967                 $actobj = self::create_activity($doc, "activity:object", $item['object']);
968                 if ($actobj) {
969                         $entry->appendChild($actobj);
970                 }
971
972                 $actarg = self::create_activity($doc, "activity:target", $item['target']);
973                 if ($actarg) {
974                         $entry->appendChild($actarg);
975                 }
976
977                 $tags = item_getfeedtags($item);
978
979                 if (count($tags)) {
980                         foreach ($tags as $t) {
981                                 if (($type != 'html') || ($t[0] != "@")) {
982                                         xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
983                                 }
984                         }
985                 }
986
987                 if (count($tags)) {
988                         foreach ($tags as $t) {
989                                 if ($t[0] == "@") {
990                                         $mentioned[$t[1]] = $t[1];
991                                 }
992                         }
993                 }
994
995                 foreach ($mentioned AS $mention) {
996                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
997                                 intval($owner["uid"]),
998                                 dbesc(normalise_link($mention)));
999
1000                         if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1001                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1002                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1003                                                                                         "href" => $mention));
1004                         } else {
1005                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1006                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1007                                                                                         "href" => $mention));
1008                         }
1009                 }
1010
1011                 self::get_attachment($doc, $entry, $item);
1012
1013                 return $entry;
1014         }
1015
1016         /**
1017          * @brief encrypts data via AES
1018          *
1019          * @param string $data The data that is to be encrypted
1020          * @param string $key The AES key
1021          *
1022          * @return string encrypted data
1023          */
1024         private static function aes_encrypt($data, $key) {
1025                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1026         }
1027
1028         /**
1029          * @brief decrypts data via AES
1030          *
1031          * @param string $encrypted The encrypted data
1032          * @param string $key The AES key
1033          *
1034          * @return string decrypted data
1035          */
1036         public static function aes_decrypt($encrypted, $key) {
1037                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1038         }
1039
1040         /**
1041          * @brief Delivers the atom content to the contacts
1042          *
1043          * @param array $owner Owner record
1044          * @param array $contactr Contact record of the receiver
1045          * @param string $atom Content that will be transmitted
1046          * @param bool $dissolve (to be documented)
1047          *
1048          * @return int Deliver status. -1 means an error.
1049          * @todo Add array type-hint for $owner, $contact
1050          */
1051         public static function deliver($owner,$contact,$atom, $dissolve = false) {
1052
1053                 $a = get_app();
1054
1055                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1056
1057                 if ($contact['duplex'] && $contact['dfrn-id']) {
1058                         $idtosend = '0:' . $orig_id;
1059                 }
1060                 if ($contact['duplex'] && $contact['issued-id']) {
1061                         $idtosend = '1:' . $orig_id;
1062                 }
1063
1064                 $rino = get_config('system', 'rino_encrypt');
1065                 $rino = intval($rino);
1066
1067                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1068
1069                 $ssl_val = intval(get_config('system','ssl_policy'));
1070                 $ssl_policy = '';
1071
1072                 switch ($ssl_val) {
1073                         case SSL_POLICY_FULL:
1074                                 $ssl_policy = 'full';
1075                                 break;
1076                         case SSL_POLICY_SELFSIGN:
1077                                 $ssl_policy = 'self';
1078                                 break;
1079                         case SSL_POLICY_NONE:
1080                         default:
1081                                 $ssl_policy = 'none';
1082                                 break;
1083                 }
1084
1085                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1086
1087                 logger('dfrn_deliver: ' . $url);
1088
1089                 $ret = z_fetch_url($url);
1090
1091                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1092                         return -2; // timed out
1093                 }
1094
1095                 $xml = $ret['body'];
1096
1097                 $curl_stat = $a->get_curl_code();
1098                 if (!$curl_stat) {
1099                         return -3; // timed out
1100                 }
1101
1102                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1103
1104                 if (! $xml) {
1105                         return 3;
1106                 }
1107
1108                 if (strpos($xml,'<?xml') === false) {
1109                         logger('dfrn_deliver: no valid XML returned');
1110                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1111                         return 3;
1112                 }
1113
1114                 $res = parse_xml_string($xml);
1115
1116                 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1117                         return (($res->status) ? $res->status : 3);
1118                 }
1119
1120                 $postvars     = array();
1121                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1122                 $challenge    = hex2bin((string) $res->challenge);
1123                 $perm         = (($res->perm) ? $res->perm : null);
1124                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1125                 $rino_remote_version = intval($res->rino);
1126                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1127
1128                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1129
1130                 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1131                         $page = 2;
1132                 }
1133
1134                 $final_dfrn_id = '';
1135
1136                 if ($perm) {
1137                         if ((($perm == 'rw') && (! intval($contact['writable'])))
1138                                 || (($perm == 'r') && (intval($contact['writable'])))) {
1139                                 q("update contact set writable = %d where id = %d",
1140                                         intval(($perm == 'rw') ? 1 : 0),
1141                                         intval($contact['id'])
1142                                 );
1143                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1144                         }
1145                 }
1146
1147                 if (($contact['duplex'] && strlen($contact['pubkey']))
1148                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1149                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1150                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1151                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1152                 } else {
1153                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1154                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1155                 }
1156
1157                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1158
1159                 if (strpos($final_dfrn_id,':') == 1) {
1160                         $final_dfrn_id = substr($final_dfrn_id,2);
1161                 }
1162
1163                 if ($final_dfrn_id != $orig_id) {
1164                         logger('dfrn_deliver: wrong dfrn_id.');
1165                         // did not decode properly - cannot trust this site
1166                         return 3;
1167                 }
1168
1169                 $postvars['dfrn_id']      = $idtosend;
1170                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1171                 if ($dissolve) {
1172                         $postvars['dissolve'] = '1';
1173                 }
1174
1175
1176                 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1177                         $postvars['data'] = $atom;
1178                         $postvars['perm'] = 'rw';
1179                 } else {
1180                         $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1181                         $postvars['perm'] = 'r';
1182                 }
1183
1184                 $postvars['ssl_policy'] = $ssl_policy;
1185
1186                 if ($page) {
1187                         $postvars['page'] = $page;
1188                 }
1189
1190
1191                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1192                         logger('rino version: '. $rino_remote_version);
1193
1194                         switch ($rino_remote_version) {
1195                                 case 1:
1196                                         // Deprecated rino version!
1197                                         $key = openssl_random_pseudo_bytes(16);
1198                                         $data = self::aes_encrypt($postvars['data'], $key);
1199                                         break;
1200                                 case 2:
1201                                         // RINO 2 based on php-encryption
1202                                         try {
1203                                                 $key = Crypto::createNewRandomKey();
1204                                         } catch (CryptoTestFailed $ex) {
1205                                                 logger('Cannot safely create a key');
1206                                                 return -4;
1207                                         } catch (CannotPerformOperation $ex) {
1208                                                 logger('Cannot safely create a key');
1209                                                 return -5;
1210                                         }
1211                                         try {
1212                                                 $data = Crypto::encrypt($postvars['data'], $key);
1213                                         } catch (CryptoTestFailed $ex) {
1214                                                 logger('Cannot safely perform encryption');
1215                                                 return -6;
1216                                         } catch (CannotPerformOperation $ex) {
1217                                                 logger('Cannot safely perform encryption');
1218                                                 return -7;
1219                                         }
1220                                         break;
1221                                 default:
1222                                         logger("rino: invalid requested verision '$rino_remote_version'");
1223                                         return -8;
1224                         }
1225
1226                         $postvars['rino'] = $rino_remote_version;
1227                         $postvars['data'] = bin2hex($data);
1228
1229                         //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1230
1231
1232                         if ($dfrn_version >= 2.1) {
1233                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1234                                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1235                                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1236                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1237                                 } else {
1238                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1239                                 }
1240
1241                         } else {
1242                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1243                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1244                                 } else {
1245                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1246                                 }
1247
1248                         }
1249
1250                         logger('md5 rawkey ' . md5($postvars['key']));
1251
1252                         $postvars['key'] = bin2hex($postvars['key']);
1253                 }
1254
1255
1256                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1257
1258                 $xml = post_url($contact['notify'], $postvars);
1259
1260                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1261
1262                 $curl_stat = $a->get_curl_code();
1263                 if ((!$curl_stat) || (!strlen($xml))) {
1264                         return -9; // timed out
1265                 }
1266
1267                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1268                         return -10;
1269                 }
1270
1271                 if (strpos($xml,'<?xml') === false) {
1272                         logger('dfrn_deliver: phase 2: no valid XML returned');
1273                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1274                         return 3;
1275                 }
1276
1277                 if ($contact['term-date'] > NULL_DATE) {
1278                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1279                         require_once('include/Contact.php');
1280                         unmark_for_death($contact);
1281                 }
1282
1283                 $res = parse_xml_string($xml);
1284
1285                 if (!isset($res->status)) {
1286                         return -11;
1287                 }
1288
1289                 if (!empty($res->message)) {
1290                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1291                 }
1292
1293                 return intval($res->status);
1294         }
1295
1296         /**
1297          * @brief Add new birthday event for this person
1298          *
1299          * @param array $contact Contact record
1300          * @param string $birthday Birthday of the contact
1301          * @todo Add array type-hint for $contact
1302          */
1303         private static function birthday_event($contact, $birthday) {
1304
1305                 // Check for duplicates
1306                 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1307                         intval($contact["uid"]),
1308                         intval($contact["id"]),
1309                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1310                         dbesc("birthday"));
1311
1312                 if (dbm::is_result($r)) {
1313                         return;
1314                 }
1315
1316                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1317
1318                 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1319                 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1320
1321                 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1322                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1323                         intval($contact["uid"]),
1324                         intval($contact["id"]),
1325                         dbesc(datetime_convert()),
1326                         dbesc(datetime_convert()),
1327                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1328                         dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1329                         dbesc($bdtext),
1330                         dbesc($bdtext2),
1331                         dbesc("birthday")
1332                 );
1333         }
1334
1335         /**
1336          * @brief Fetch the author data from head or entry items
1337          *
1338          * @param object $xpath XPath object
1339          * @param object $context In which context should the data be searched
1340          * @param array $importer Record of the importer user mixed with contact of the content
1341          * @param string $element Element name from which the data is fetched
1342          * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1343          *
1344          * @return Returns an array with relevant data of the author
1345          * @todo Find good type-hints for all parameter
1346          */
1347         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1348
1349                 $author = array();
1350                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1351                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1352
1353                 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1354                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1355                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1356                         intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1357
1358                 if (dbm::is_result($r)) {
1359                         $contact = $r[0];
1360                         $author["contact-id"] = $r[0]["id"];
1361                         $author["network"] = $r[0]["network"];
1362                 } else {
1363                         if (!$onlyfetch) {
1364                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1365                         }
1366
1367                         $author["contact-id"] = $importer["id"];
1368                         $author["network"] = $importer["network"];
1369                         $onlyfetch = true;
1370                 }
1371
1372                 // Until now we aren't serving different sizes - but maybe later
1373                 $avatarlist = array();
1374                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1375                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1376                 foreach ($avatars AS $avatar) {
1377                         $href = "";
1378                         $width = 0;
1379                         foreach ($avatar->attributes AS $attributes) {
1380                                 /// @TODO Rewrite these similar if () to one switch
1381                                 if ($attributes->name == "href") {
1382                                         $href = $attributes->textContent;
1383                                 }
1384                                 if ($attributes->name == "width") {
1385                                         $width = $attributes->textContent;
1386                                 }
1387                                 if ($attributes->name == "updated") {
1388                                         $contact["avatar-date"] = $attributes->textContent;
1389                                 }
1390                         }
1391                         if (($width > 0) && ($href != "")) {
1392                                 $avatarlist[$width] = $href;
1393                         }
1394                 }
1395                 if (count($avatarlist) > 0) {
1396                         krsort($avatarlist);
1397                         $author["avatar"] = current($avatarlist);
1398                 }
1399
1400                 if (dbm::is_result($r) && !$onlyfetch) {
1401                         logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1402
1403                         $poco = array("url" => $contact["url"]);
1404
1405                         // When was the last change to name or uri?
1406                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1407                         foreach ($name_element->attributes AS $attributes) {
1408                                 if ($attributes->name == "updated") {
1409                                         $poco["name-date"] = $attributes->textContent;
1410                                 }
1411                         }
1412
1413                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1414                         foreach ($link_element->attributes AS $attributes) {
1415                                 if ($attributes->name == "updated") {
1416                                         $poco["uri-date"] = $attributes->textContent;
1417                                 }
1418                         }
1419
1420                         // Update contact data
1421                         $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1422                         if ($value != "") {
1423                                 $poco["addr"] = $value;
1424                         }
1425
1426                         $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1427                         if ($value != "") {
1428                                 $poco["name"] = $value;
1429                         }
1430
1431                         $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1432                         if ($value != "") {
1433                                 $poco["nick"] = $value;
1434                         }
1435
1436                         $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1437                         if ($value != "") {
1438                                 $poco["about"] = $value;
1439                         }
1440
1441                         $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1442                         if ($value != "") {
1443                                 $poco["location"] = $value;
1444                         }
1445
1446                         /// @todo Only search for elements with "poco:type" = "xmpp"
1447                         $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1448                         if ($value != "") {
1449                                 $poco["xmpp"] = $value;
1450                         }
1451
1452                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1453                         /// - poco:utcOffset
1454                         /// - poco:urls
1455                         /// - poco:locality
1456                         /// - poco:region
1457                         /// - poco:country
1458
1459                         // If the "hide" element is present then the profile isn't searchable.
1460                         $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1461
1462                         logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1463
1464                         // If the contact isn't searchable then set the contact to "hidden".
1465                         // Problem: This can be manually overridden by the user.
1466                         if ($hide) {
1467                                 $contact["hidden"] = true;
1468                         }
1469
1470                         // Save the keywords into the contact table
1471                         $tags = array();
1472                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1473                         foreach ($tagelements AS $tag) {
1474                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1475                         }
1476
1477                         if (count($tags)) {
1478                                 $poco["keywords"] = implode(", ", $tags);
1479                         }
1480
1481                         // "dfrn:birthday" contains the birthday converted to UTC
1482                         $old_bdyear = $contact["bdyear"];
1483
1484                         $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1485
1486                         if (strtotime($birthday) > time()) {
1487                                 $bd_timestamp = strtotime($birthday);
1488
1489                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1490                         }
1491
1492                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1493                         $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1494
1495                         if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1496                                 $bdyear = date("Y");
1497                                 $value = str_replace("0000", $bdyear, $value);
1498
1499                                 if (strtotime($value) < time()) {
1500                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1501                                         $bdyear = $bdyear + 1;
1502                                 }
1503
1504                                 $poco["bd"] = $value;
1505                         }
1506
1507                         $contact = array_merge($contact, $poco);
1508
1509                         if ($old_bdyear != $contact["bdyear"]) {
1510                                 self::birthday_event($contact, $birthday);
1511                         }
1512
1513                         // Get all field names
1514                         $fields = array();
1515                         foreach ($r[0] AS $field => $data) {
1516                                 $fields[$field] = $data;
1517                         }
1518
1519                         unset($fields["id"]);
1520                         unset($fields["uid"]);
1521                         unset($fields["url"]);
1522                         unset($fields["avatar-date"]);
1523                         unset($fields["name-date"]);
1524                         unset($fields["uri-date"]);
1525
1526                         // Update check for this field has to be done differently
1527                         $datefields = array("name-date", "uri-date");
1528                         foreach ($datefields AS $field) {
1529                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1530                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1531                                         $update = true;
1532                                 }
1533                         }
1534
1535                         foreach ($fields AS $field => $data) {
1536                                 if ($contact[$field] != $r[0][$field]) {
1537                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1538                                         $update = true;
1539                                 }
1540                         }
1541
1542                         if ($update) {
1543                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1544
1545                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1546                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1547                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1548                                         WHERE `id` = %d AND `network` = '%s'",
1549                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1550                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1551                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1552                                         dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1553                                         intval($contact["id"]), dbesc($contact["network"]));
1554                         }
1555
1556                         update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1557                                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1558
1559                         /*
1560                          * The generation is a sign for the reliability of the provided data.
1561                          * It is used in the socgraph.php to prevent that old contact data
1562                          * that was relayed over several servers can overwrite contact
1563                          * data that we received directly.
1564                          */
1565
1566                         $poco["generation"] = 2;
1567                         $poco["photo"] = $author["avatar"];
1568                         $poco["hide"] = $hide;
1569                         $poco["contact-type"] = $contact["contact-type"];
1570                         $gcid = update_gcontact($poco);
1571
1572                         link_gcontact($gcid, $importer["uid"], $contact["id"]);
1573                 }
1574
1575                 return($author);
1576         }
1577
1578         /**
1579          * @brief Transforms activity objects into an XML string
1580          *
1581          * @param object $xpath XPath object
1582          * @param object $activity Activity object
1583          * @param text $element element name
1584          *
1585          * @return string XML string
1586          * @todo Find good type-hints for all parameter
1587          */
1588         private static function transform_activity($xpath, $activity, $element) {
1589                 if (!is_object($activity)) {
1590                         return "";
1591                 }
1592
1593                 $obj_doc = new DOMDocument("1.0", "utf-8");
1594                 $obj_doc->formatOutput = true;
1595
1596                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1597
1598                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1599                 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1600
1601                 $id = $xpath->query("atom:id", $activity)->item(0);
1602                 if (is_object($id)) {
1603                         $obj_element->appendChild($obj_doc->importNode($id, true));
1604                 }
1605
1606                 $title = $xpath->query("atom:title", $activity)->item(0);
1607                 if (is_object($title)) {
1608                         $obj_element->appendChild($obj_doc->importNode($title, true));
1609                 }
1610
1611                 $links = $xpath->query("atom:link", $activity);
1612                 if (is_object($links)) {
1613                         foreach ($links AS $link) {
1614                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1615                         }
1616                 }
1617
1618                 $content = $xpath->query("atom:content", $activity)->item(0);
1619                 if (is_object($content)) {
1620                         $obj_element->appendChild($obj_doc->importNode($content, true));
1621                 }
1622
1623                 $obj_doc->appendChild($obj_element);
1624
1625                 $objxml = $obj_doc->saveXML($obj_element);
1626
1627                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1628                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1629                 return($objxml);
1630         }
1631
1632         /**
1633          * @brief Processes the mail elements
1634          *
1635          * @param object $xpath XPath object
1636          * @param object $mail mail elements
1637          * @param array $importer Record of the importer user mixed with contact of the content
1638          * @todo Find good type-hints for all parameter
1639          */
1640         private static function process_mail($xpath, $mail, $importer) {
1641
1642                 logger("Processing mails");
1643
1644                 /// @TODO Rewrite this to one statement
1645                 $msg = array();
1646                 $msg["uid"] = $importer["importer_uid"];
1647                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1648                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1649                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1650                 $msg["contact-id"] = $importer["id"];
1651                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1652                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1653                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1654                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1655                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1656                 $msg["seen"] = 0;
1657                 $msg["replied"] = 0;
1658
1659                 dbm::esc_array($msg, true);
1660
1661                 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
1662
1663                 // send notifications.
1664                 /// @TODO Arange this mess
1665                 $notif_params = array(
1666                         "type" => NOTIFY_MAIL,
1667                         "notify_flags" => $importer["notify-flags"],
1668                         "language" => $importer["language"],
1669                         "to_name" => $importer["username"],
1670                         "to_email" => $importer["email"],
1671                         "uid" => $importer["importer_uid"],
1672                         "item" => $msg,
1673                         "source_name" => $msg["from-name"],
1674                         "source_link" => $importer["url"],
1675                         "source_photo" => $importer["thumb"],
1676                         "verb" => ACTIVITY_POST,
1677                         "otype" => "mail"
1678                 );
1679
1680                 notification($notif_params);
1681
1682                 logger("Mail is processed, notification was sent.");
1683         }
1684
1685         /**
1686          * @brief Processes the suggestion elements
1687          *
1688          * @param object $xpath XPath object
1689          * @param object $suggestion suggestion elements
1690          * @param array $importer Record of the importer user mixed with contact of the content
1691          * @todo Find good type-hints for all parameter
1692          */
1693         private static function process_suggestion($xpath, $suggestion, $importer) {
1694                 $a = get_app();
1695
1696                 logger("Processing suggestions");
1697
1698                 /// @TODO Rewrite this to one statement
1699                 $suggest = array();
1700                 $suggest["uid"] = $importer["importer_uid"];
1701                 $suggest["cid"] = $importer["id"];
1702                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1703                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1704                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1705                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1706                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1707
1708                 // Does our member already have a friend matching this description?
1709
1710                 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1711                         dbesc($suggest["name"]),
1712                         dbesc(normalise_link($suggest["url"])),
1713                         intval($suggest["uid"])
1714                 );
1715
1716                 /*
1717                  * The valid result means the friend we're about to send a friend
1718                  * suggestion already has them in their contact, which means no further
1719                  * action is required.
1720                  *
1721                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1722                  */
1723                 if (dbm::is_result($r)) {
1724                         return false;
1725                 }
1726
1727                 // Do we already have an fcontact record for this person?
1728
1729                 $fid = 0;
1730                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1731                         dbesc($suggest["url"]),
1732                         dbesc($suggest["name"]),
1733                         dbesc($suggest["request"])
1734                 );
1735                 if (dbm::is_result($r)) {
1736                         $fid = $r[0]["id"];
1737
1738                         // OK, we do. Do we already have an introduction for this person ?
1739                         $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1740                                 intval($suggest["uid"]),
1741                                 intval($fid)
1742                         );
1743
1744                         /*
1745                          * The valid result means the friend we're about to send a friend
1746                          * suggestion already has them in their contact, which means no further
1747                          * action is required.
1748                          *
1749                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1750                          */
1751                         if (dbm::is_result($r)) {
1752                                 return false;
1753                         }
1754                 }
1755                 if (!$fid) {
1756                         $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1757                                 dbesc($suggest["name"]),
1758                                 dbesc($suggest["url"]),
1759                                 dbesc($suggest["photo"]),
1760                                 dbesc($suggest["request"])
1761                         );
1762                 }
1763                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1764                         dbesc($suggest["url"]),
1765                         dbesc($suggest["name"]),
1766                         dbesc($suggest["request"])
1767                 );
1768
1769                 /*
1770                  * If no record in fcontact is found, below INSERT statement will not
1771                  * link an introduction to it.
1772                  */
1773                 if (!dbm::is_result($r)) {
1774                         // database record did not get created. Quietly give up.
1775                         killme();
1776                 }
1777
1778                 $fid = $r[0]["id"];
1779
1780                 $hash = random_string();
1781
1782                 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1783                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1784                         intval($suggest["uid"]),
1785                         intval($fid),
1786                         intval($suggest["cid"]),
1787                         dbesc($suggest["body"]),
1788                         dbesc($hash),
1789                         dbesc(datetime_convert()),
1790                         intval(0)
1791                 );
1792
1793                 notification(array(
1794                         "type"         => NOTIFY_SUGGEST,
1795                         "notify_flags" => $importer["notify-flags"],
1796                         "language"     => $importer["language"],
1797                         "to_name"      => $importer["username"],
1798                         "to_email"     => $importer["email"],
1799                         "uid"          => $importer["importer_uid"],
1800                         "item"         => $suggest,
1801                         "link"         => System::baseUrl()."/notifications/intros",
1802                         "source_name"  => $importer["name"],
1803                         "source_link"  => $importer["url"],
1804                         "source_photo" => $importer["photo"],
1805                         "verb"         => ACTIVITY_REQ_FRIEND,
1806                         "otype"        => "intro"
1807                 ));
1808
1809                 return true;
1810
1811         }
1812
1813         /**
1814          * @brief Processes the relocation elements
1815          *
1816          * @param object $xpath XPath object
1817          * @param object $relocation relocation elements
1818          * @param array $importer Record of the importer user mixed with contact of the content
1819          * @todo Find good type-hints for all parameter
1820          */
1821         private static function process_relocation($xpath, $relocation, $importer) {
1822
1823                 logger("Processing relocations");
1824
1825                 /// @TODO Rewrite this to one statement
1826                 $relocate = array();
1827                 $relocate["uid"] = $importer["importer_uid"];
1828                 $relocate["cid"] = $importer["id"];
1829                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1830                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1831                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1832                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1833                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1834                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1835                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1836                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1837                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1838                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1839                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1840                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1841
1842                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1843                         $relocate["avatar"] = $relocate["photo"];
1844                 }
1845
1846                 if ($relocate["addr"] == "") {
1847                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1848                 }
1849
1850                 // update contact
1851                 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1852                         intval($importer["id"]),
1853                         intval($importer["importer_uid"]));
1854
1855                 if (!dbm::is_result($r)) {
1856                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
1857                         return false;
1858                 }
1859
1860                 $old = $r[0];
1861
1862                 // Update the gcontact entry
1863                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1864
1865                 $x = q("UPDATE `gcontact` SET
1866                                         `name` = '%s',
1867                                         `photo` = '%s',
1868                                         `url` = '%s',
1869                                         `nurl` = '%s',
1870                                         `addr` = '%s',
1871                                         `connect` = '%s',
1872                                         `notify` = '%s',
1873                                         `server_url` = '%s'
1874                         WHERE `nurl` = '%s';",
1875                                         dbesc($relocate["name"]),
1876                                         dbesc($relocate["avatar"]),
1877                                         dbesc($relocate["url"]),
1878                                         dbesc(normalise_link($relocate["url"])),
1879                                         dbesc($relocate["addr"]),
1880                                         dbesc($relocate["addr"]),
1881                                         dbesc($relocate["notify"]),
1882                                         dbesc($relocate["server_url"]),
1883                                         dbesc(normalise_link($old["url"])));
1884
1885                 // Update the contact table. We try to find every entry.
1886                 $x = q("UPDATE `contact` SET
1887                                         `name` = '%s',
1888                                         `avatar` = '%s',
1889                                         `url` = '%s',
1890                                         `nurl` = '%s',
1891                                         `addr` = '%s',
1892                                         `request` = '%s',
1893                                         `confirm` = '%s',
1894                                         `notify` = '%s',
1895                                         `poll` = '%s',
1896                                         `site-pubkey` = '%s'
1897                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1898                                         dbesc($relocate["name"]),
1899                                         dbesc($relocate["avatar"]),
1900                                         dbesc($relocate["url"]),
1901                                         dbesc(normalise_link($relocate["url"])),
1902                                         dbesc($relocate["addr"]),
1903                                         dbesc($relocate["request"]),
1904                                         dbesc($relocate["confirm"]),
1905                                         dbesc($relocate["notify"]),
1906                                         dbesc($relocate["poll"]),
1907                                         dbesc($relocate["sitepubkey"]),
1908                                         intval($importer["id"]),
1909                                         intval($importer["importer_uid"]),
1910                                         dbesc(normalise_link($old["url"])));
1911
1912                 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1913
1914                 if ($x === false) {
1915                         return false;
1916                 }
1917
1918                 // update items
1919                 /// @todo This is an extreme performance killer
1920                 $fields = array(
1921                         'owner-link' => array($old["url"], $relocate["url"]),
1922                         'author-link' => array($old["url"], $relocate["url"]),
1923                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1924                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
1925                 );
1926                 foreach ($fields as $n=>$f) {
1927                         $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1928                                         $n, dbesc($f[0]),
1929                                         intval($importer["importer_uid"]));
1930
1931                         if (dbm::is_result($r)) {
1932                                 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1933                                                 $n, dbesc($f[1]),
1934                                                 $n, dbesc($f[0]),
1935                                                 intval($importer["importer_uid"]));
1936
1937                                         if ($x === false) {
1938                                                 return false;
1939                                         }
1940                         }
1941                 }
1942
1943                 /// @TODO
1944                 /// merge with current record, current contents have priority
1945                 /// update record, set url-updated
1946                 /// update profile photos
1947                 /// schedule a scan?
1948                 return true;
1949         }
1950
1951         /**
1952          * @brief Updates an item
1953          *
1954          * @param array $current the current item record
1955          * @param array $item the new item record
1956          * @param array $importer Record of the importer user mixed with contact of the content
1957          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1958          * @todo set proper type-hints (array?)
1959          */
1960         private static function update_content($current, $item, $importer, $entrytype) {
1961                 $changed = false;
1962
1963                 if (edited_timestamp_is_newer($current, $item)) {
1964
1965                         // do not accept (ignore) an earlier edit than one we currently have.
1966                         if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
1967                                 return false;
1968                         }
1969
1970                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
1971                                 dbesc($item["title"]),
1972                                 dbesc($item["body"]),
1973                                 dbesc($item["tag"]),
1974                                 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1975                                 dbesc(datetime_convert()),
1976                                 dbesc($item["uri"]),
1977                                 intval($importer["importer_uid"])
1978                         );
1979                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1980                         update_thread_uri($item["uri"], $importer["importer_uid"]);
1981
1982                         $changed = true;
1983
1984                         if ($entrytype == DFRN_REPLY_RC) {
1985                                 proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
1986                         }
1987                 }
1988
1989                 // update last-child if it changes
1990                 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
1991                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
1992                                 dbesc(datetime_convert()),
1993                                 dbesc($item["parent-uri"]),
1994                                 intval($importer["importer_uid"])
1995                         );
1996                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
1997                                 intval($item["last-child"]),
1998                                 dbesc(datetime_convert()),
1999                                 dbesc($item["uri"]),
2000                                 intval($importer["importer_uid"])
2001                         );
2002                 }
2003                 return $changed;
2004         }
2005
2006         /**
2007          * @brief Detects the entry type of the item
2008          *
2009          * @param array $importer Record of the importer user mixed with contact of the content
2010          * @param array $item the new item record
2011          *
2012          * @return int Is it a toplevel entry, a comment or a relayed comment?
2013          * @todo set proper type-hints (array?)
2014          */
2015         private static function get_entry_type($importer, $item) {
2016                 if ($item["parent-uri"] != $item["uri"]) {
2017                         $community = false;
2018
2019                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2020                                 $sql_extra = "";
2021                                 $community = true;
2022                                 logger("possible community action");
2023                         } else {
2024                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2025                         }
2026
2027                         // was the top-level post for this action written by somebody on this site?
2028                         // Specifically, the recipient?
2029
2030                         $is_a_remote_action = false;
2031
2032                         $r = q("SELECT `item`.`parent-uri` FROM `item`
2033                                 WHERE `item`.`uri` = '%s'
2034                                 LIMIT 1",
2035                                 dbesc($item["parent-uri"])
2036                         );
2037                         if (dbm::is_result($r)) {
2038                                 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2039                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2040                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2041                                         AND `item`.`uid` = %d
2042                                         $sql_extra
2043                                         LIMIT 1",
2044                                         dbesc($r[0]["parent-uri"]),
2045                                         dbesc($r[0]["parent-uri"]),
2046                                         dbesc($r[0]["parent-uri"]),
2047                                         intval($importer["importer_uid"])
2048                                 );
2049                                 if (dbm::is_result($r)) {
2050                                         $is_a_remote_action = true;
2051                                 }
2052                         }
2053
2054                         /*
2055                          * Does this have the characteristics of a community or private group action?
2056                          * If it's an action to a wall post on a community/prvgroup page it's a
2057                          * valid community action. Also forum_mode makes it valid for sure.
2058                          * If neither, it's not.
2059                          */
2060
2061                         /// @TODO Maybe merge these if() blocks into one?
2062                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2063                                 $is_a_remote_action = false;
2064                                 logger("not a community action");
2065                         }
2066
2067                         if ($is_a_remote_action) {
2068                                 return DFRN_REPLY_RC;
2069                         } else {
2070                                 return DFRN_REPLY;
2071                         }
2072                 } else {
2073                         return DFRN_TOP_LEVEL;
2074                 }
2075
2076         }
2077
2078         /**
2079          * @brief Send a "poke"
2080          *
2081          * @param array $item the new item record
2082          * @param array $importer Record of the importer user mixed with contact of the content
2083          * @param int $posted_id The record number of item record that was just posted
2084          * @todo set proper type-hints (array?)
2085          */
2086         private static function do_poke($item, $importer, $posted_id) {
2087                 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2088                 if (!$verb) {
2089                         return;
2090                 }
2091                 $xo = parse_xml_string($item["object"],false);
2092
2093                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2094
2095                         // somebody was poked/prodded. Was it me?
2096                         foreach ($xo->link as $l) {
2097                                 $atts = $l->attributes();
2098                                 switch ($atts["rel"]) {
2099                                         case "alternate":
2100                                                 $Blink = $atts["href"];
2101                                                 break;
2102                                         default:
2103                                                 break;
2104                                 }
2105                         }
2106
2107                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2108
2109                                 // send a notification
2110                                 notification(array(
2111                                         "type"         => NOTIFY_POKE,
2112                                         "notify_flags" => $importer["notify-flags"],
2113                                         "language"     => $importer["language"],
2114                                         "to_name"      => $importer["username"],
2115                                         "to_email"     => $importer["email"],
2116                                         "uid"          => $importer["importer_uid"],
2117                                         "item"         => $item,
2118                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2119                                         "source_name"  => stripslashes($item["author-name"]),
2120                                         "source_link"  => $item["author-link"],
2121                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2122                                                 ? $importer["thumb"] : $item["author-avatar"]),
2123                                         "verb"         => $item["verb"],
2124                                         "otype"        => "person",
2125                                         "activity"     => $verb,
2126                                         "parent"       => $item["parent"]
2127                                 ));
2128                         }
2129                 }
2130         }
2131
2132         /**
2133          * @brief Processes several actions, depending on the verb
2134          *
2135          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2136          * @param array $importer Record of the importer user mixed with contact of the content
2137          * @param array $item the new item record
2138          * @param bool $is_like Is the verb a "like"?
2139          *
2140          * @return bool Should the processing of the entries be continued?
2141          * @todo set proper type-hints (array?)
2142          */
2143         private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2144
2145                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2146
2147                 if (($entrytype == DFRN_TOP_LEVEL)) {
2148                         // The filling of the the "contact" variable is done for legcy reasons
2149                         // The functions below are partly used by ostatus.php as well - where we have this variable
2150                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2151                         $contact = $r[0];
2152                         $nickname = $contact["nick"];
2153
2154                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2155                         // This function once was responsible for DFRN and OStatus.
2156                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2157                                 logger("New follower");
2158                                 new_follower($importer, $contact, $item, $nickname);
2159                                 return false;
2160                         }
2161                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW))  {
2162                                 logger("Lost follower");
2163                                 lose_follower($importer, $contact, $item);
2164                                 return false;
2165                         }
2166                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2167                                 logger("New friend request");
2168                                 new_follower($importer, $contact, $item, $nickname, true);
2169                                 return false;
2170                         }
2171                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND))  {
2172                                 logger("Lost sharer");
2173                                 lose_sharer($importer, $contact, $item);
2174                                 return false;
2175                         }
2176                 } else {
2177                         if (($item["verb"] == ACTIVITY_LIKE)
2178                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2179                                 || ($item["verb"] == ACTIVITY_ATTEND)
2180                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2181                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2182                                 $is_like = true;
2183                                 $item["type"] = "activity";
2184                                 $item["gravity"] = GRAVITY_LIKE;
2185                                 // only one like or dislike per person
2186                                 // splitted into two queries for performance issues
2187                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2188                                         intval($item["uid"]),
2189                                         dbesc($item["author-link"]),
2190                                         dbesc($item["verb"]),
2191                                         dbesc($item["parent-uri"])
2192                                 );
2193                                 if (dbm::is_result($r)) {
2194                                         return false;
2195                                 }
2196
2197                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2198                                         intval($item["uid"]),
2199                                         dbesc($item["author-link"]),
2200                                         dbesc($item["verb"]),
2201                                         dbesc($item["parent-uri"])
2202                                 );
2203                                 if (dbm::is_result($r)) {
2204                                         return false;
2205                                 }
2206                         } else {
2207                                 $is_like = false;
2208                         }
2209
2210                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2211
2212                                 $xo = parse_xml_string($item["object"],false);
2213                                 $xt = parse_xml_string($item["target"],false);
2214
2215                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2216                                         $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2217                                                 dbesc($xt->id),
2218                                                 intval($importer["importer_uid"])
2219                                         );
2220
2221                                         if (!dbm::is_result($r)) {
2222                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2223                                                 return false;
2224                                         }
2225
2226                                         // extract tag, if not duplicate, add to parent item
2227                                         if ($xo->content) {
2228                                                 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2229                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2230                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2231                                                                 intval($r[0]["id"])
2232                                                         );
2233                                                         create_tags_from_item($r[0]["id"]);
2234                                                 }
2235                                         }
2236                                 }
2237                         }
2238                 }
2239                 return true;
2240         }
2241
2242         /**
2243          * @brief Processes the link elements
2244          *
2245          * @param object $links link elements
2246          * @param array $item the item record
2247          * @todo set proper type-hints
2248          */
2249         private static function parse_links($links, &$item) {
2250                 $rel = "";
2251                 $href = "";
2252                 $type = "";
2253                 $length = "0";
2254                 $title = "";
2255                 foreach ($links AS $link) {
2256                         foreach ($link->attributes AS $attributes) {
2257                                 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2258                                 if ($attributes->name == "href") {
2259                                         $href = $attributes->textContent;
2260                                 }
2261                                 if ($attributes->name == "rel") {
2262                                         $rel = $attributes->textContent;
2263                                 }
2264                                 if ($attributes->name == "type") {
2265                                         $type = $attributes->textContent;
2266                                 }
2267                                 if ($attributes->name == "length") {
2268                                         $length = $attributes->textContent;
2269                                 }
2270                                 if ($attributes->name == "title") {
2271                                         $title = $attributes->textContent;
2272                                 }
2273                         }
2274                         if (($rel != "") && ($href != "")) {
2275                                 switch ($rel) {
2276                                         case "alternate":
2277                                                 $item["plink"] = $href;
2278                                                 break;
2279                                         case "enclosure":
2280                                                 $enclosure = $href;
2281                                                 if (strlen($item["attach"])) {
2282                                                         $item["attach"] .= ",";
2283                                                 }
2284
2285                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2286                                                 break;
2287                                 }
2288                         }
2289                 }
2290         }
2291
2292         /**
2293          * @brief Processes the entry elements which contain the items and comments
2294          *
2295          * @param array $header Array of the header elements that always stay the same
2296          * @param object $xpath XPath object
2297          * @param object $entry entry elements
2298          * @param array $importer Record of the importer user mixed with contact of the content
2299          * @todo Add type-hints
2300          */
2301         private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2302
2303                 logger("Processing entries");
2304
2305                 $item = $header;
2306
2307                 $item["protocol"] = PROTOCOL_DFRN;
2308
2309                 $item["source"] = $xml;
2310
2311                 // Get the uri
2312                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2313
2314                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2315
2316                 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2317                         dbesc($item["uri"]),
2318                         intval($importer["importer_uid"])
2319                 );
2320
2321                 // Is there an existing item?
2322                 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2323                         (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2324                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2325                         return;
2326                 }
2327
2328                 // Fetch the owner
2329                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2330
2331                 $item["owner-name"] = $owner["name"];
2332                 $item["owner-link"] = $owner["link"];
2333                 $item["owner-avatar"] = $owner["avatar"];
2334
2335                 // fetch the author
2336                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2337
2338                 $item["author-name"] = $author["name"];
2339                 $item["author-link"] = $author["link"];
2340                 $item["author-avatar"] = $author["avatar"];
2341
2342                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2343
2344                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2345
2346                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2347                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2348                 // make sure nobody is trying to sneak some html tags by us
2349                 $item["body"] = notags(base64url_decode($item["body"]));
2350
2351                 $item["body"] = limit_body_size($item["body"]);
2352
2353                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2354                 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2355
2356                         $item['body'] = reltoabs($item['body'],$base_url);
2357
2358                         $item['body'] = html2bb_video($item['body']);
2359
2360                         $item['body'] = oembed_html2bbcode($item['body']);
2361
2362                         $config = HTMLPurifier_Config::createDefault();
2363                         $config->set('Cache.DefinitionImpl', null);
2364
2365                         // we shouldn't need a whitelist, because the bbcode converter
2366                         // will strip out any unsupported tags.
2367
2368                         $purifier = new HTMLPurifier($config);
2369                         $item['body'] = $purifier->purify($item['body']);
2370
2371                         $item['body'] = @html2bbcode($item['body']);
2372                 }
2373
2374                 /// @todo We should check for a repeated post and if we know the repeated author.
2375
2376                 // We don't need the content element since "dfrn:env" is always present
2377                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2378
2379                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2380                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2381
2382                 $georsspoint = $xpath->query("georss:point", $entry);
2383                 if ($georsspoint) {
2384                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2385                 }
2386
2387                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2388
2389                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2390
2391                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2392                         $item["bookmark"] = true;
2393                 }
2394
2395                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2396                 if ($notice_info && ($notice_info->length > 0)) {
2397                         foreach ($notice_info->item(0)->attributes AS $attributes) {
2398                                 if ($attributes->name == "source") {
2399                                         $item["app"] = strip_tags($attributes->textContent);
2400                                 }
2401                         }
2402                 }
2403
2404                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2405
2406                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2407                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2408                 if ($dsprsig != "") {
2409                         $item["dsprsig"] = $dsprsig;
2410                 }
2411
2412                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2413
2414                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2415                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2416                 }
2417
2418                 $object = $xpath->query("activity:object", $entry)->item(0);
2419                 $item["object"] = self::transform_activity($xpath, $object, "object");
2420
2421                 if (trim($item["object"]) != "") {
2422                         $r = parse_xml_string($item["object"], false);
2423                         if (isset($r->type)) {
2424                                 $item["object-type"] = $r->type;
2425                         }
2426                 }
2427
2428                 $target = $xpath->query("activity:target", $entry)->item(0);
2429                 $item["target"] = self::transform_activity($xpath, $target, "target");
2430
2431                 $categories = $xpath->query("atom:category", $entry);
2432                 if ($categories) {
2433                         foreach ($categories AS $category) {
2434                                 $term = "";
2435                                 $scheme = "";
2436                                 foreach ($category->attributes AS $attributes) {
2437                                         if ($attributes->name == "term") {
2438                                                 $term = $attributes->textContent;
2439                                         }
2440
2441                                         if ($attributes->name == "scheme") {
2442                                                 $scheme = $attributes->textContent;
2443                                         }
2444                                 }
2445
2446                                 if (($term != "") && ($scheme != "")) {
2447                                         $parts = explode(":", $scheme);
2448                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2449                                                 $termhash = array_shift($parts);
2450                                                 $termurl = implode(":", $parts);
2451
2452                                                 if (strlen($item["tag"])) {
2453                                                         $item["tag"] .= ",";
2454                                                 }
2455
2456                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2457                                         }
2458                                 }
2459                         }
2460                 }
2461
2462                 $enclosure = "";
2463
2464                 $links = $xpath->query("atom:link", $entry);
2465                 if ($links) {
2466                         self::parse_links($links, $item);
2467                 }
2468
2469                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2470
2471                 $conv = $xpath->query('ostatus:conversation', $entry);
2472                 if (is_object($conv->item(0))) {
2473                         foreach ($conv->item(0)->attributes AS $attributes) {
2474                                 if ($attributes->name == "ref") {
2475                                         $item['conversation-uri'] = $attributes->textContent;
2476                                 }
2477                                 if ($attributes->name == "href") {
2478                                         $item['conversation-href'] = $attributes->textContent;
2479                                 }
2480                         }
2481                 }
2482
2483                 // Is it a reply or a top level posting?
2484                 $item["parent-uri"] = $item["uri"];
2485
2486                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2487                 if (is_object($inreplyto->item(0))) {
2488                         foreach ($inreplyto->item(0)->attributes AS $attributes) {
2489                                 if ($attributes->name == "ref") {
2490                                         $item["parent-uri"] = $attributes->textContent;
2491                                 }
2492                         }
2493                 }
2494
2495                 // Get the type of the item (Top level post, reply or remote reply)
2496                 $entrytype = self::get_entry_type($importer, $item);
2497
2498                 // Now assign the rest of the values that depend on the type of the message
2499                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2500                         if (!isset($item["object-type"])) {
2501                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2502                         }
2503
2504                         if ($item["contact-id"] != $owner["contact-id"]) {
2505                                 $item["contact-id"] = $owner["contact-id"];
2506                         }
2507
2508                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2509                                 $item["network"] = $owner["network"];
2510                         }
2511
2512                         if ($item["contact-id"] != $author["contact-id"]) {
2513                                 $item["contact-id"] = $author["contact-id"];
2514                         }
2515
2516                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2517                                 $item["network"] = $author["network"];
2518                         }
2519
2520                         /// @TODO maybe remove this old-lost code then?
2521                         // This code was taken from the old DFRN code
2522                         // When activated, forums don't work.
2523                         // And: Why should we disallow commenting by followers?
2524                         // the behaviour is now similar to the Diaspora part.
2525                         //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2526                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2527                         //      return;
2528                         //}
2529                 }
2530
2531                 if ($entrytype == DFRN_REPLY_RC) {
2532                         $item["type"] = "remote-comment";
2533                         $item["wall"] = 1;
2534                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2535                         if (!isset($item["object-type"])) {
2536                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2537                         }
2538
2539                         // Is it an event?
2540                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2541                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2542                                 $ev = bbtoevent($item["body"]);
2543                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2544                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2545                                         /// @TODO Mixure of "/' ahead ...
2546                                         $ev["cid"] = $importer["id"];
2547                                         $ev["uid"] = $importer["uid"];
2548                                         $ev["uri"] = $item["uri"];
2549                                         $ev["edited"] = $item["edited"];
2550                                         $ev['private'] = $item['private'];
2551                                         $ev["guid"] = $item["guid"];
2552
2553                                         $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2554                                                 dbesc($item["uri"]),
2555                                                 intval($importer["uid"])
2556                                         );
2557                                         if (dbm::is_result($r)) {
2558                                                 $ev["id"] = $r[0]["id"];
2559                                         }
2560
2561                                         $event_id = event_store($ev);
2562                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2563                                         return;
2564                                 }
2565                         }
2566                 }
2567
2568                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2569                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2570                         return;
2571                 }
2572
2573                 // Update content if 'updated' changes
2574                 if (dbm::is_result($current)) {
2575                         if (self::update_content($r[0], $item, $importer, $entrytype)) {
2576                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2577                         } else {
2578                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2579                         }
2580                         return;
2581                 }
2582
2583                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2584                         $posted_id = item_store($item);
2585                         $parent = 0;
2586
2587                         if ($posted_id) {
2588
2589                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2590
2591                                 $item["id"] = $posted_id;
2592
2593                                 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2594                                         intval($posted_id),
2595                                         intval($importer["importer_uid"])
2596                                 );
2597                                 if (dbm::is_result($r)) {
2598                                         $parent = $r[0]["parent"];
2599                                         $parent_uri = $r[0]["parent-uri"];
2600                                 }
2601
2602                                 if (!$is_like) {
2603                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2604                                                 dbesc(datetime_convert()),
2605                                                 intval($importer["importer_uid"]),
2606                                                 intval($r[0]["parent"])
2607                                         );
2608
2609                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2610                                                 dbesc(datetime_convert()),
2611                                                 intval($importer["importer_uid"]),
2612                                                 intval($posted_id)
2613                                         );
2614                                 }
2615
2616                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2617                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2618                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
2619                                 }
2620
2621                                 return true;
2622                         }
2623                 } else { // $entrytype == DFRN_TOP_LEVEL
2624                         if (!link_compare($item["owner-link"],$importer["url"])) {
2625                                 /*
2626                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2627                                  * but otherwise there's a possible data mixup on the sender's system.
2628                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2629                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2630                                  */
2631                                 logger('Correcting item owner.', LOGGER_DEBUG);
2632                                 $item["owner-name"]   = $importer["senderName"];
2633                                 $item["owner-link"]   = $importer["url"];
2634                                 $item["owner-avatar"] = $importer["thumb"];
2635                         }
2636
2637                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2638                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2639                                 return;
2640                         }
2641
2642                         // This is my contact on another system, but it's really me.
2643                         // Turn this into a wall post.
2644                         $notify = item_is_remote_self($importer, $item);
2645
2646                         $posted_id = item_store($item, false, $notify);
2647
2648                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2649
2650                         if (stristr($item["verb"],ACTIVITY_POKE))
2651                                 self::do_poke($item, $importer, $posted_id);
2652                 }
2653         }
2654
2655         /**
2656          * @brief Deletes items
2657          *
2658          * @param object $xpath XPath object
2659          * @param object $deletion deletion elements
2660          * @param array $importer Record of the importer user mixed with contact of the content
2661          * @todo set proper type-hints
2662          */
2663         private static function process_deletion($xpath, $deletion, $importer) {
2664
2665                 logger("Processing deletions");
2666
2667                 foreach ($deletion->attributes AS $attributes) {
2668                         if ($attributes->name == "ref") {
2669                                 $uri = $attributes->textContent;
2670                         }
2671                         if ($attributes->name == "when") {
2672                                 $when = $attributes->textContent;
2673                         }
2674                 }
2675                 if ($when) {
2676                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2677                 } else {
2678                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2679                 }
2680
2681                 if (!$uri || !$importer["id"]) {
2682                         return false;
2683                 }
2684
2685                 /// @todo Only select the used fields
2686                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2687                                 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2688                                 dbesc($uri),
2689                                 intval($importer["uid"]),
2690                                 intval($importer["id"])
2691                         );
2692                 if (!dbm::is_result($r)) {
2693                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2694                         return;
2695                 } else {
2696
2697                         $item = $r[0];
2698
2699                         $entrytype = self::get_entry_type($importer, $item);
2700
2701                         if (!$item["deleted"]) {
2702                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2703                         } else {
2704                                 return;
2705                         }
2706
2707                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2708                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2709                                 event_delete($item["event-id"]);
2710                         }
2711
2712                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2713
2714                                 $xo = parse_xml_string($item["object"],false);
2715                                 $xt = parse_xml_string($item["target"],false);
2716
2717                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2718                                         $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2719                                                 dbesc($xt->id),
2720                                                 intval($importer["importer_uid"])
2721                                         );
2722                                         if (dbm::is_result($i)) {
2723
2724                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2725
2726                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2727                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2728                                                 $author_copy = (($item["origin"]) ? true : false);
2729
2730                                                 if ($owner_remove && $author_copy) {
2731                                                         return;
2732                                                 }
2733                                                 if ($author_remove || $owner_remove) {
2734                                                         $tags = explode(',',$i[0]["tag"]);
2735                                                         $newtags = array();
2736                                                         if (count($tags)) {
2737                                                                 foreach ($tags as $tag) {
2738                                                                         if (trim($tag) !== trim($xo->body)) {
2739                                                                                 $newtags[] = trim($tag);
2740                                                                         }
2741                                                                 }
2742                                                         }
2743                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2744                                                                 dbesc(implode(',', $newtags)),
2745                                                                 intval($i[0]["id"])
2746                                                         );
2747                                                         create_tags_from_item($i[0]["id"]);
2748                                                 }
2749                                         }
2750                                 }
2751                         }
2752
2753                         if ($entrytype == DFRN_TOP_LEVEL) {
2754                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2755                                                 `body` = '', `title` = ''
2756                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2757                                                 dbesc($when),
2758                                                 dbesc(datetime_convert()),
2759                                                 dbesc($uri),
2760                                                 intval($importer["uid"])
2761                                         );
2762                                 create_tags_from_itemuri($uri, $importer["uid"]);
2763                                 create_files_from_itemuri($uri, $importer["uid"]);
2764                                 update_thread_uri($uri, $importer["uid"]);
2765                         } else {
2766                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2767                                                 `body` = '', `title` = ''
2768                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2769                                                 dbesc($when),
2770                                                 dbesc(datetime_convert()),
2771                                                 dbesc($uri),
2772                                                 intval($importer["uid"])
2773                                         );
2774                                 create_tags_from_itemuri($uri, $importer["uid"]);
2775                                 create_files_from_itemuri($uri, $importer["uid"]);
2776                                 update_thread_uri($uri, $importer["importer_uid"]);
2777                                 if ($item["last-child"]) {
2778                                         // ensure that last-child is set in case the comment that had it just got wiped.
2779                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2780                                                 dbesc(datetime_convert()),
2781                                                 dbesc($item["parent-uri"]),
2782                                                 intval($item["uid"])
2783                                         );
2784                                         // who is the last child now?
2785                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2786                                                 ORDER BY `created` DESC LIMIT 1",
2787                                                         dbesc($item["parent-uri"]),
2788                                                         intval($importer["uid"])
2789                                         );
2790                                         if (dbm::is_result($r)) {
2791                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2792                                                         intval($r[0]["id"])
2793                                                 );
2794                                         }
2795                                 }
2796                                 // if this is a relayed delete, propagate it to other recipients
2797
2798                                 if ($entrytype == DFRN_REPLY_RC) {
2799                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2800                                         proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
2801                                 }
2802                         }
2803                 }
2804         }
2805
2806         /**
2807          * @brief Imports a DFRN message
2808          *
2809          * @param text $xml The DFRN message
2810          * @param array $importer Record of the importer user mixed with contact of the content
2811          * @param bool $sort_by_date Is used when feeds are polled
2812          * @return integer Import status
2813          * @todo set proper type-hints
2814          */
2815         public static function import($xml, $importer, $sort_by_date = false) {
2816
2817                 if ($xml == "") {
2818                         return 400;
2819                 }
2820
2821                 if ($importer["readonly"]) {
2822                         // We aren't receiving stuff from this person. But we will quietly ignore them
2823                         // rather than a blatant "go away" message.
2824                         logger('ignoring contact '.$importer["id"]);
2825                         return 403;
2826                 }
2827
2828                 $doc = new DOMDocument();
2829                 @$doc->loadXML($xml);
2830
2831                 $xpath = new DomXPath($doc);
2832                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2833                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2834                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2835                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2836                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2837                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2838                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2839                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2840                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2841                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2842
2843                 $header = array();
2844                 $header["uid"] = $importer["uid"];
2845                 $header["network"] = NETWORK_DFRN;
2846                 $header["type"] = "remote";
2847                 $header["wall"] = 0;
2848                 $header["origin"] = 0;
2849                 $header["contact-id"] = $importer["id"];
2850
2851                 // Update the contact table if the data has changed
2852
2853                 // The "atom:author" is only present in feeds
2854                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2855                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2856                 }
2857
2858                 // Only the "dfrn:owner" in the head section contains all data
2859                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2860                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2861                 }
2862
2863                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2864
2865                 // The account type is new since 3.5.1
2866                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2867                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2868
2869                         if ($accounttype != $importer["contact-type"]) {
2870                                 /// @TODO this way is the norm or putting ); at the end of the line?
2871                                 q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
2872                                         intval($accounttype),
2873                                         intval($importer["id"])
2874                                 );
2875                         }
2876                 }
2877
2878                 // is it a public forum? Private forums aren't supported with this method
2879                 // This is deprecated since 3.5.1
2880                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2881
2882                 if ($forum != $importer["forum"]) {
2883                         q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2884                                 intval($forum), intval($forum),
2885                                 intval($importer["id"])
2886                         );
2887                 }
2888
2889                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2890                 foreach ($mails AS $mail) {
2891                         self::process_mail($xpath, $mail, $importer);
2892                 }
2893
2894                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2895                 foreach ($suggestions AS $suggestion) {
2896                         self::process_suggestion($xpath, $suggestion, $importer);
2897                 }
2898
2899                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2900                 foreach ($relocations AS $relocation) {
2901                         self::process_relocation($xpath, $relocation, $importer);
2902                 }
2903
2904                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2905                 foreach ($deletions AS $deletion) {
2906                         self::process_deletion($xpath, $deletion, $importer);
2907                 }
2908
2909                 if (!$sort_by_date) {
2910                         $entries = $xpath->query("/atom:feed/atom:entry");
2911                         foreach ($entries AS $entry) {
2912                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2913                         }
2914                 } else {
2915                         $newentries = array();
2916                         $entries = $xpath->query("/atom:feed/atom:entry");
2917                         foreach ($entries AS $entry) {
2918                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2919                                 $newentries[strtotime($created)] = $entry;
2920                         }
2921
2922                         // Now sort after the publishing date
2923                         ksort($newentries);
2924
2925                         foreach ($newentries AS $entry) {
2926                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2927                         }
2928                 }
2929                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2930                 return 200;
2931         }
2932 }