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