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