]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
Switched to static methods for DFRN
[friendica.git] / include / dfrn.php
1 <?php
2 require_once('include/items.php');
3 require_once('include/Contact.php');
4 require_once('include/ostatus.php');
5
6 class dfrn {
7
8         /**
9          * @brief Generates the atom entries for delivery.php
10          *
11          * This function is used whenever content is transmitted via DFRN.
12          *
13          * @param array $items Item elements
14          * @param array $owner Owner record
15          *
16          * @return string DFRN entries
17          */
18         function entries($items,$owner) {
19
20                 $doc = new DOMDocument('1.0', 'utf-8');
21                 $doc->formatOutput = true;
22
23                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
24
25                 if(! count($items))
26                         return trim($doc->saveXML());
27
28                 foreach($items as $item) {
29                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
30                         $root->appendChild($entry);
31                 }
32
33                 return(trim($doc->saveXML()));
34         }
35
36         /**
37          * @brief Generate an atom feed for the given user
38          *
39          * This function is called when another server is pulling data from the user feed.
40          *
41          * @param string $dfrn_id DFRN ID from the requesting party
42          * @param string $owner_nick Owner nick name
43          * @param string $last_update Date of the last update
44          * @param int $direction Can be -1, 0 or 1.
45          *
46          * @return string DFRN feed entries
47          */
48         function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) {
49
50                 $a = get_app();
51
52                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
53                 $public_feed = (($dfrn_id) ? false : true);
54                 $starred     = false;   // not yet implemented, possible security issues
55                 $converse    = false;
56
57                 if($public_feed && $a->argc > 2) {
58                         for($x = 2; $x < $a->argc; $x++) {
59                                 if($a->argv[$x] == 'converse')
60                                         $converse = true;
61                                 if($a->argv[$x] == 'starred')
62                                         $starred = true;
63                                 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
64                                         $category = $a->argv[$x+1];
65                         }
66                 }
67
68
69
70                 // default permissions - anonymous user
71
72                 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
73
74                 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
75                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
76                         WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
77                         dbesc($owner_nick)
78                 );
79
80                 if(! count($r))
81                         killme();
82
83                 $owner = $r[0];
84                 $owner_id = $owner['user_uid'];
85                 $owner_nick = $owner['nickname'];
86
87                 $sql_post_table = "";
88                 $visibility = "";
89
90                 if(! $public_feed) {
91
92                         $sql_extra = '';
93                         switch($direction) {
94                                 case (-1):
95                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
96                                         $my_id = $dfrn_id;
97                                         break;
98                                 case 0:
99                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
100                                         $my_id = '1:' . $dfrn_id;
101                                         break;
102                                 case 1:
103                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
104                                         $my_id = '0:' . $dfrn_id;
105                                         break;
106                                 default:
107                                         return false;
108                                         break; // NOTREACHED
109                         }
110
111                         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
112                                 intval($owner_id)
113                         );
114
115                         if(! count($r))
116                                 killme();
117
118                         $contact = $r[0];
119                         require_once('include/security.php');
120                         $groups = init_groups_visitor($contact['id']);
121
122                         if(count($groups)) {
123                                 for($x = 0; $x < count($groups); $x ++)
124                                         $groups[$x] = '<' . intval($groups[$x]) . '>' ;
125                                 $gs = implode('|', $groups);
126                         } else
127                                 $gs = '<<>>' ; // Impossible to match
128
129                         $sql_extra = sprintf("
130                                 AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
131                                 AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
132                                 AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
133                                 AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
134                         ",
135                                 intval($contact['id']),
136                                 intval($contact['id']),
137                                 dbesc($gs),
138                                 dbesc($gs)
139                         );
140                 }
141
142                 if($public_feed)
143                         $sort = 'DESC';
144                 else
145                         $sort = 'ASC';
146
147                 $date_field = "`changed`";
148                 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
149
150                 if(! strlen($last_update))
151                         $last_update = 'now -30 days';
152
153                 if(isset($category)) {
154                         $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` ",
155                                         dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
156                         //$sql_extra .= file_tag_file_query('item',$category,'category');
157                 }
158
159                 if($public_feed) {
160                         if(! $converse)
161                                 $sql_extra .= " AND `contact`.`self` = 1 ";
162                 }
163
164                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
165
166                 //      AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
167                 //      dbesc($check_date),
168
169                 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
170                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
171                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
172                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
173                         `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
174                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
175                         FROM `item` $sql_post_table
176                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
177                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
178                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
179                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
180                         AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
181                         $sql_extra
182                         ORDER BY $sql_order LIMIT 0, 300",
183                         intval($owner_id),
184                         dbesc($check_date),
185                         dbesc($sort)
186                 );
187
188                 // Will check further below if this actually returned results.
189                 // We will provide an empty feed if that is the case.
190
191                 $items = $r;
192
193                 $doc = new DOMDocument('1.0', 'utf-8');
194                 $doc->formatOutput = true;
195
196                 $alternatelink = $owner['url'];
197
198                 if(isset($category))
199                         $alternatelink .= "/category/".$category;
200
201                 if ($public_feed)
202                         $author = "dfrn:owner";
203                 else
204                         $author = "author";
205
206                 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
207
208                 // This hook can't work anymore
209                 //      call_hooks('atom_feed', $atom);
210
211                 if(! count($items)) {
212                         $atom = trim($doc->saveXML());
213
214                         call_hooks('atom_feed_end', $atom);
215
216                         return $atom;
217                 }
218
219                 foreach($items as $item) {
220
221                         // prevent private email from leaking.
222                         if($item['network'] === NETWORK_MAIL)
223                                 continue;
224
225                         // public feeds get html, our own nodes use bbcode
226
227                         if($public_feed) {
228                                 $type = 'html';
229                                 // catch any email that's in a public conversation and make sure it doesn't leak
230                                 if($item['private'])
231                                         continue;
232                         } else
233                                 $type = 'text';
234
235                         $entry = self::entry($doc, $type, $item, $owner, true);
236                         $root->appendChild($entry);
237
238                 }
239
240                 $atom = trim($doc->saveXML());
241
242                 call_hooks('atom_feed_end', $atom);
243
244                 return $atom;
245         }
246
247         /**
248          * @brief Create XML text for DFRN mails
249          *
250          * @param array $item message elements
251          * @param array $owner Owner record
252          *
253          * @return string DFRN mail
254          */
255         function mail($item, $owner) {
256                 $doc = new DOMDocument('1.0', 'utf-8');
257                 $doc->formatOutput = true;
258
259                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
260
261                 $mail = $doc->createElement("dfrn:mail");
262                 $sender = $doc->createElement("dfrn:sender");
263
264                 xml_add_element($doc, $sender, "dfrn:name", $owner['name']);
265                 xml_add_element($doc, $sender, "dfrn:uri", $owner['url']);
266                 xml_add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
267
268                 $mail->appendChild($sender);
269
270                 xml_add_element($doc, $mail, "dfrn:id", $item['uri']);
271                 xml_add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
272                 xml_add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
273                 xml_add_element($doc, $mail, "dfrn:subject", $item['title']);
274                 xml_add_element($doc, $mail, "dfrn:content", $item['body']);
275
276                 $root->appendChild($mail);
277
278                 return(trim($doc->saveXML()));
279         }
280
281         /**
282          * @brief Create XML text for DFRN friend suggestions
283          *
284          * @param array $item suggestion elements
285          * @param array $owner Owner record
286          *
287          * @return string DFRN suggestions
288          */
289         function fsuggest($item, $owner) {
290                 $doc = new DOMDocument('1.0', 'utf-8');
291                 $doc->formatOutput = true;
292
293                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
294
295                 $suggest = $doc->createElement("dfrn:suggest");
296
297                 xml_add_element($doc, $suggest, "dfrn:url", $item['url']);
298                 xml_add_element($doc, $suggest, "dfrn:name", $item['name']);
299                 xml_add_element($doc, $suggest, "dfrn:photo", $item['photo']);
300                 xml_add_element($doc, $suggest, "dfrn:request", $item['request']);
301                 xml_add_element($doc, $suggest, "dfrn:note", $item['note']);
302
303                 $root->appendChild($suggest);
304
305                 return(trim($doc->saveXML()));
306         }
307
308         /**
309          * @brief Create XML text for DFRN relocations
310          *
311          * @param array $owner Owner record
312          * @param int $uid User ID
313          *
314          * @return string DFRN relocations
315          */
316         function relocate($owner, $uid) {
317
318                 /* get site pubkey. this could be a new installation with no site keys*/
319                 $pubkey = get_config('system','site_pubkey');
320                 if(! $pubkey) {
321                         $res = new_keypair(1024);
322                         set_config('system','site_prvkey', $res['prvkey']);
323                         set_config('system','site_pubkey', $res['pubkey']);
324                 }
325
326                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
327                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
328                 $photos = array();
329                 $ext = Photo::supportedTypes();
330
331                 foreach($rp as $p)
332                         $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
333
334                 unset($rp, $ext);
335
336                 $doc = new DOMDocument('1.0', 'utf-8');
337                 $doc->formatOutput = true;
338
339                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
340
341                 $relocate = $doc->createElement("dfrn:relocate");
342
343                 xml_add_element($doc, $relocate, "dfrn:url", $owner['url']);
344                 xml_add_element($doc, $relocate, "dfrn:name", $owner['name']);
345                 xml_add_element($doc, $relocate, "dfrn:photo", $photos[4]);
346                 xml_add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
347                 xml_add_element($doc, $relocate, "dfrn:micro", $photos[6]);
348                 xml_add_element($doc, $relocate, "dfrn:request", $owner['request']);
349                 xml_add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
350                 xml_add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
351                 xml_add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
352                 xml_add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
353
354                 $root->appendChild($relocate);
355
356                 return(trim($doc->saveXML()));
357         }
358
359         /**
360          * @brief Adds the header elements for the DFRN protocol
361          *
362          * @param object $doc XML document
363          * @param array $owner Owner record
364          * @param string $authorelement Element name for the author
365          * @param string $alternatelink link to profile or category
366          * @param bool $public Is it a header for public posts?
367          *
368          * @return object XML root object
369          */
370         private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
371
372                 if ($alternatelink == "")
373                         $alternatelink = $owner['url'];
374
375                 $root = $doc->createElementNS(NS_ATOM, 'feed');
376                 $doc->appendChild($root);
377
378                 $root->setAttribute("xmlns:thr", NS_THR);
379                 $root->setAttribute("xmlns:at", "http://purl.org/atompub/tombstones/1.0");
380                 $root->setAttribute("xmlns:media", NS_MEDIA);
381                 $root->setAttribute("xmlns:dfrn", "http://purl.org/macgirvin/dfrn/1.0");
382                 $root->setAttribute("xmlns:activity", NS_ACTIVITY);
383                 $root->setAttribute("xmlns:georss", NS_GEORSS);
384                 $root->setAttribute("xmlns:poco", NS_POCO);
385                 $root->setAttribute("xmlns:ostatus", NS_OSTATUS);
386                 $root->setAttribute("xmlns:statusnet", NS_STATUSNET);
387
388                 //xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
389                 xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
390                 xml_add_element($doc, $root, "title", $owner["name"]);
391
392                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
393                 xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
394
395                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
396                 xml_add_element($doc, $root, "link", "", $attributes);
397
398                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
399                 xml_add_element($doc, $root, "link", "", $attributes);
400
401                 ostatus_hublinks($doc, $root);
402
403                 if ($public) {
404                         $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
405                         xml_add_element($doc, $root, "link", "", $attributes);
406
407                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
408                         xml_add_element($doc, $root, "link", "", $attributes);
409
410                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
411                         xml_add_element($doc, $root, "link", "", $attributes);
412                 }
413
414                 if ($owner['page-flags'] == PAGE_COMMUNITY)
415                         xml_add_element($doc, $root, "dfrn:community", 1);
416
417                 xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
418
419                 $author = self::add_author($doc, $owner, $authorelement, $public);
420                 $root->appendChild($author);
421
422                 return $root;
423         }
424
425         /**
426          * @brief Adds the author element in the header for the DFRN protocol
427          *
428          * @param object $doc XML document
429          * @param array $owner Owner record
430          * @param string $authorelement Element name for the author
431          *
432          * @return object XML author object
433          */
434         private function add_author($doc, $owner, $authorelement, $public) {
435
436                 $author = $doc->createElement($authorelement);
437
438                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME);
439                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
440                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
441
442                 $attributes = array("dfrn:updated" => $namdate);
443                 xml_add_element($doc, $author, "name", $owner["name"], $attributes);
444
445                 $attributes = array("dfrn:updated" => $namdate);
446                 xml_add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
447
448                 $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate,
449                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
450                 xml_add_element($doc, $author, "link", "", $attributes);
451
452                 $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate,
453                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
454                 xml_add_element($doc, $author, "link", "", $attributes);
455
456                 $birthday = feed_birthday($owner['user_uid'], $owner['timezone']);
457
458                 if ($birthday)
459                         xml_add_element($doc, $author, "dfrn:birthday", $birthday);
460
461                 // The following fields will only be generated if this isn't for a public feed
462                 if ($public)
463                         return $author;
464
465                 // Only show contact details when we are allowed to
466                 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`,
467                                 `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob`
468                         FROM `profile`
469                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
470                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
471                         intval($owner['user_uid']));
472                 if ($r) {
473                         $profile = $r[0];
474                         xml_add_element($doc, $author, "poco:displayName", $profile["name"]);
475                         xml_add_element($doc, $author, "poco:updated", $namdate);
476
477                         if (trim($profile["dob"]) != "0000-00-00")
478                                 xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
479
480                         xml_add_element($doc, $author, "poco:note", $profile["about"]);
481                         xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
482
483                         $savetz = date_default_timezone_get();
484                         date_default_timezone_set($profile["timezone"]);
485                         xml_add_element($doc, $author, "poco:utcOffset", date("P"));
486                         date_default_timezone_set($savetz);
487
488                         if (trim($profile["homepage"]) != "") {
489                                 $urls = $doc->createElement("poco:urls");
490                                 xml_add_element($doc, $urls, "poco:type", "homepage");
491                                 xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
492                                 xml_add_element($doc, $urls, "poco:primary", "true");
493                                 $author->appendChild($urls);
494                         }
495
496                         if (trim($profile["pub_keywords"]) != "") {
497                                 $keywords = explode(",", $profile["pub_keywords"]);
498
499                                 foreach ($keywords AS $keyword)
500                                         xml_add_element($doc, $author, "poco:tags", trim($keyword));
501
502                         }
503
504                         /// @todo When we are having the XMPP address in the profile we should propagate it here
505                         $xmpp = "";
506                         if (trim($xmpp) != "") {
507                                 $ims = $doc->createElement("poco:ims");
508                                 xml_add_element($doc, $ims, "poco:type", "xmpp");
509                                 xml_add_element($doc, $ims, "poco:value", $xmpp);
510                                 xml_add_element($doc, $ims, "poco:primary", "true");
511                                 $author->appendChild($ims);
512                         }
513
514                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
515                                 $element = $doc->createElement("poco:address");
516
517                                 xml_add_element($doc, $element, "poco:formatted", formatted_location($profile));
518
519                                 if (trim($profile["locality"]) != "")
520                                         xml_add_element($doc, $element, "poco:locality", $profile["locality"]);
521
522                                 if (trim($profile["region"]) != "")
523                                         xml_add_element($doc, $element, "poco:region", $profile["region"]);
524
525                                 if (trim($profile["country-name"]) != "")
526                                         xml_add_element($doc, $element, "poco:country", $profile["country-name"]);
527
528                                 $author->appendChild($element);
529                         }
530                 }
531
532                 return $author;
533         }
534
535         /**
536          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
537          *
538          * @param object $doc XML document
539          * @param string $element Element name for the author
540          * @param string $contact_url Link of the contact
541          * @param array $items Item elements
542          *
543          * @return object XML author object
544          */
545         private function add_entry_author($doc, $element, $contact_url, $item) {
546
547                 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
548
549                 $author = $doc->createElement($element);
550                 xml_add_element($doc, $author, "name", $contact["name"]);
551                 xml_add_element($doc, $author, "uri", $contact["url"]);
552
553                 /// @Todo
554                 /// - Check real image type and image size
555                 /// - Check which of these boths elements we should use
556                 $attributes = array(
557                                 "rel" => "photo",
558                                 "type" => "image/jpeg",
559                                 "media:width" => 80,
560                                 "media:height" => 80,
561                                 "href" => $contact["photo"]);
562                 xml_add_element($doc, $author, "link", "", $attributes);
563
564                 $attributes = array(
565                                 "rel" => "avatar",
566                                 "type" => "image/jpeg",
567                                 "media:width" => 80,
568                                 "media:height" => 80,
569                                 "href" => $contact["photo"]);
570                 xml_add_element($doc, $author, "link", "", $attributes);
571
572                 return $author;
573         }
574
575         /**
576          * @brief Adds the activity elements
577          *
578          * @param object $doc XML document
579          * @param string $element Element name for the activity
580          * @param string $activity activity value
581          *
582          * @return object XML activity object
583          */
584         private function create_activity($doc, $element, $activity) {
585
586                 if($activity) {
587                         $entry = $doc->createElement($element);
588
589                         $r = parse_xml_string($activity, false);
590                         if(!$r)
591                                 return false;
592                         if($r->type)
593                                 xml_add_element($doc, $entry, "activity:object-type", $r->type);
594                         if($r->id)
595                                 xml_add_element($doc, $entry, "id", $r->id);
596                         if($r->title)
597                                 xml_add_element($doc, $entry, "title", $r->title);
598                         if($r->link) {
599                                 if(substr($r->link,0,1) === '<') {
600                                         if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
601                                                 $r->link = str_replace('&','&amp;', $r->link);
602
603                                         $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
604
605                                         $data = parse_xml_string($r->link, false);
606                                         foreach ($data->attributes() AS $parameter => $value)
607                                                 $attributes[$parameter] = $value;
608                                 } else
609                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
610
611                                 xml_add_element($doc, $entry, "link", "", $attributes);
612                         }
613                         if($r->content)
614                                 xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
615
616                         return $entry;
617                 }
618
619                 return false;
620         }
621
622         /**
623          * @brief Adds the elements for attachments
624          *
625          * @param object $doc XML document
626          * @param object $root XML root
627          * @param array $item Item element
628          *
629          * @return object XML attachment object
630          */
631         private function get_attachment($doc, $root, $item) {
632                 $arr = explode('[/attach],',$item['attach']);
633                 if(count($arr)) {
634                         foreach($arr as $r) {
635                                 $matches = false;
636                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
637                                 if($cnt) {
638                                         $attributes = array("rel" => "enclosure",
639                                                         "href" => $matches[1],
640                                                         "type" => $matches[3]);
641
642                                         if(intval($matches[2]))
643                                                 $attributes["length"] = intval($matches[2]);
644
645                                         if(trim($matches[4]) != "")
646                                                 $attributes["title"] = trim($matches[4]);
647
648                                         xml_add_element($doc, $root, "link", "", $attributes);
649                                 }
650                         }
651                 }
652         }
653
654         /**
655          * @brief Adds the "entry" elements for the DFRN protocol
656          *
657          * @param object $doc XML document
658          * @param string $type "text" or "html"
659          * @param array $item Item element
660          * @param array $owner Owner record
661          * @param bool $comment Trigger the sending of the "comment" element
662          * @param int $cid Contact ID of the recipient
663          *
664          * @return object XML entry object
665          */
666         private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
667
668                 $mentioned = array();
669
670                 if(!$item['parent'])
671                         return;
672
673                 if($item['deleted']) {
674                         $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
675                         return xml_create_element($doc, "at:deleted-entry", "", $attributes);
676                 }
677
678                 $entry = $doc->createElement("entry");
679
680                 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
681                         $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
682                 else
683                         $body = $item['body'];
684
685                 if ($type == 'html') {
686                         $htmlbody = $body;
687
688                         if ($item['title'] != "")
689                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
690
691                         $htmlbody = bbcode($htmlbody, false, false, 7);
692                 }
693
694                 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
695                 $entry->appendChild($author);
696
697                 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
698                 $entry->appendChild($dfrnowner);
699
700                 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
701                         $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
702                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
703                         $attributes = array("ref" => $parent_item, "type" => "text/html", "href" => app::get_baseurl().'/display/'.$parent[0]['guid']);
704                         xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
705                 }
706
707                 xml_add_element($doc, $entry, "id", $item["uri"]);
708                 xml_add_element($doc, $entry, "title", $item["title"]);
709
710                 xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
711                 xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
712
713                 xml_add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
714                 xml_add_element($doc, $entry, "content", (($type === 'html') ? $htmlbody : $body), array("type" => $type));
715
716                 xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
717                                                                 "href" => app::get_baseurl()."/display/".$item["guid"]));
718
719                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
720                 // It is included in the rewritten code for completeness
721                 if ($comment)
722                         xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
723
724                 if($item['location'])
725                         xml_add_element($doc, $entry, "dfrn:location", $item['location']);
726
727                 if($item['coord'])
728                         xml_add_element($doc, $entry, "georss:point", $item['coord']);
729
730                 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
731                         xml_add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
732
733                 if($item['extid'])
734                         xml_add_element($doc, $entry, "dfrn:extid", $item['extid']);
735
736                 if($item['bookmark'])
737                         xml_add_element($doc, $entry, "dfrn:bookmark", "true");
738
739                 if($item['app'])
740                         xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
741
742                 xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
743
744                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
745                 // It is needed for relayed comments to Diaspora.
746                 if($item['signed_text']) {
747                         $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
748                         xml_add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
749                 }
750
751                 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
752
753                 $actobj = self::create_activity($doc, "activity:object", $item['object']);
754                 if ($actobj)
755                         $entry->appendChild($actobj);
756
757                 $actarg = self::create_activity($doc, "activity:target", $item['target']);
758                 if ($actarg)
759                         $entry->appendChild($actarg);
760
761                 $tags = item_getfeedtags($item);
762
763                 if(count($tags)) {
764                         foreach($tags as $t)
765                                 if (($type != 'html') OR ($t[0] != "@"))
766                                         xml_add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
767                 }
768
769                 if(count($tags))
770                         foreach($tags as $t)
771                                 if ($t[0] == "@")
772                                         $mentioned[$t[1]] = $t[1];
773
774                 foreach ($mentioned AS $mention) {
775                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
776                                 intval($owner["uid"]),
777                                 dbesc(normalise_link($mention)));
778                         if ($r[0]["forum"] OR $r[0]["prv"])
779                                 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
780                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
781                                                                                         "href" => $mention));
782                         else
783                                 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
784                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
785                                                                                         "href" => $mention));
786                 }
787
788                 self::get_attachment($doc, $entry, $item);
789
790                 return $entry;
791         }
792
793         /**
794          * @brief Delivers the atom content to the contacts
795          *
796          * @param array $owner Owner record
797          * @param array $contactr Contact record of the receiver
798          * @param string $atom Content that will be transmitted
799          * @param bool $dissolve (to be documented)
800          *
801          * @return int Deliver status. -1 means an error.
802          */
803         function deliver($owner,$contact,$atom, $dissolve = false) {
804
805                 $a = get_app();
806
807                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
808
809                 if($contact['duplex'] && $contact['dfrn-id'])
810                         $idtosend = '0:' . $orig_id;
811                 if($contact['duplex'] && $contact['issued-id'])
812                         $idtosend = '1:' . $orig_id;
813
814
815                 $rino = get_config('system','rino_encrypt');
816                 $rino = intval($rino);
817                 // use RINO1 if mcrypt isn't installed and RINO2 was selected
818                 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
819
820                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
821
822                 $ssl_val = intval(get_config('system','ssl_policy'));
823                 $ssl_policy = '';
824
825                 switch($ssl_val){
826                         case SSL_POLICY_FULL:
827                                 $ssl_policy = 'full';
828                                 break;
829                         case SSL_POLICY_SELFSIGN:
830                                 $ssl_policy = 'self';
831                                 break;
832                         case SSL_POLICY_NONE:
833                         default:
834                                 $ssl_policy = 'none';
835                                 break;
836                 }
837
838                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
839
840                 logger('dfrn_deliver: ' . $url);
841
842                 $xml = fetch_url($url);
843
844                 $curl_stat = $a->get_curl_code();
845                 if(! $curl_stat)
846                         return(-1); // timed out
847
848                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
849
850                 if(! $xml)
851                         return 3;
852
853                 if(strpos($xml,'<?xml') === false) {
854                         logger('dfrn_deliver: no valid XML returned');
855                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
856                         return 3;
857                 }
858
859                 $res = parse_xml_string($xml);
860
861                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
862                         return (($res->status) ? $res->status : 3);
863
864                 $postvars     = array();
865                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
866                 $challenge    = hex2bin((string) $res->challenge);
867                 $perm         = (($res->perm) ? $res->perm : null);
868                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
869                 $rino_remote_version = intval($res->rino);
870                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
871
872                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
873
874                 if($owner['page-flags'] == PAGE_PRVGROUP)
875                         $page = 2;
876
877                 $final_dfrn_id = '';
878
879                 if($perm) {
880                         if((($perm == 'rw') && (! intval($contact['writable'])))
881                                 || (($perm == 'r') && (intval($contact['writable'])))) {
882                                 q("update contact set writable = %d where id = %d",
883                                         intval(($perm == 'rw') ? 1 : 0),
884                                         intval($contact['id'])
885                                 );
886                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
887                         }
888                 }
889
890                 if(($contact['duplex'] && strlen($contact['pubkey']))
891                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
892                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
893                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
894                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
895                 } else {
896                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
897                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
898                 }
899
900                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
901
902                 if(strpos($final_dfrn_id,':') == 1)
903                         $final_dfrn_id = substr($final_dfrn_id,2);
904
905                 if($final_dfrn_id != $orig_id) {
906                         logger('dfrn_deliver: wrong dfrn_id.');
907                         // did not decode properly - cannot trust this site
908                         return 3;
909                 }
910
911                 $postvars['dfrn_id']      = $idtosend;
912                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
913                 if($dissolve)
914                         $postvars['dissolve'] = '1';
915
916
917                 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
918                         $postvars['data'] = $atom;
919                         $postvars['perm'] = 'rw';
920                 } else {
921                         $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
922                         $postvars['perm'] = 'r';
923                 }
924
925                 $postvars['ssl_policy'] = $ssl_policy;
926
927                 if($page)
928                         $postvars['page'] = $page;
929
930
931                 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
932                         logger('rino version: '. $rino_remote_version);
933
934                         switch($rino_remote_version) {
935                                 case 1:
936                                         // Deprecated rino version!
937                                         $key = substr(random_string(),0,16);
938                                         $data = aes_encrypt($postvars['data'],$key);
939                                         break;
940                                 case 2:
941                                         // RINO 2 based on php-encryption
942                                         try {
943                                                 $key = Crypto::createNewRandomKey();
944                                         } catch (CryptoTestFailed $ex) {
945                                                 logger('Cannot safely create a key');
946                                                 return -1;
947                                         } catch (CannotPerformOperation $ex) {
948                                                 logger('Cannot safely create a key');
949                                                 return -1;
950                                         }
951                                         try {
952                                                 $data = Crypto::encrypt($postvars['data'], $key);
953                                         } catch (CryptoTestFailed $ex) {
954                                                 logger('Cannot safely perform encryption');
955                                                 return -1;
956                                         } catch (CannotPerformOperation $ex) {
957                                                 logger('Cannot safely perform encryption');
958                                                 return -1;
959                                         }
960                                         break;
961                                 default:
962                                         logger("rino: invalid requested verision '$rino_remote_version'");
963                                         return -1;
964                         }
965
966                         $postvars['rino'] = $rino_remote_version;
967                         $postvars['data'] = bin2hex($data);
968
969                         #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
970
971
972                         if($dfrn_version >= 2.1) {
973                                 if(($contact['duplex'] && strlen($contact['pubkey']))
974                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
975                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
976
977                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
978                                 else
979                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
980
981                         } else {
982                                 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
983                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
984                                 else
985                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
986
987                         }
988
989                         logger('md5 rawkey ' . md5($postvars['key']));
990
991                         $postvars['key'] = bin2hex($postvars['key']);
992                 }
993
994
995                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
996
997                 $xml = post_url($contact['notify'],$postvars);
998
999                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1000
1001                 $curl_stat = $a->get_curl_code();
1002                 if((! $curl_stat) || (! strlen($xml)))
1003                         return(-1); // timed out
1004
1005                 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1006                         return(-1);
1007
1008                 if(strpos($xml,'<?xml') === false) {
1009                         logger('dfrn_deliver: phase 2: no valid XML returned');
1010                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1011                         return 3;
1012                 }
1013
1014                 if($contact['term-date'] != '0000-00-00 00:00:00') {
1015                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1016                         require_once('include/Contact.php');
1017                         unmark_for_death($contact);
1018                 }
1019
1020                 $res = parse_xml_string($xml);
1021
1022                 return $res->status;
1023         }
1024 }