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