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