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