3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * https://github.com/friendica/friendica/wiki/Protocol
9 require_once('include/items.php');
10 require_once('include/Contact.php');
11 require_once('include/ostatus.php');
14 * @brief This class contain functions to create and send DFRN XML files
20 * @brief Generates the atom entries for delivery.php
22 * This function is used whenever content is transmitted via DFRN.
24 * @param array $items Item elements
25 * @param array $owner Owner record
27 * @return string DFRN entries
29 function entries($items,$owner) {
31 $doc = new DOMDocument('1.0', 'utf-8');
32 $doc->formatOutput = true;
34 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
37 return trim($doc->saveXML());
39 foreach($items as $item) {
40 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
41 $root->appendChild($entry);
44 return(trim($doc->saveXML()));
48 * @brief Generate an atom feed for the given user
50 * This function is called when another server is pulling data from the user feed.
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.
57 * @return string DFRN feed entries
59 function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) {
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
68 if($public_feed && $a->argc > 2) {
69 for($x = 2; $x < $a->argc; $x++) {
70 if($a->argv[$x] == 'converse')
72 if($a->argv[$x] == 'starred')
74 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
75 $category = $a->argv[$x+1];
81 // default permissions - anonymous user
83 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
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",
95 $owner_id = $owner['user_uid'];
96 $owner_nick = $owner['nickname'];
106 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
110 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
111 $my_id = '1:' . $dfrn_id;
114 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
115 $my_id = '0:' . $dfrn_id;
122 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
130 require_once('include/security.php');
131 $groups = init_groups_visitor($contact['id']);
134 for($x = 0; $x < count($groups); $x ++)
135 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
136 $gs = implode('|', $groups);
138 $gs = '<<>>' ; // Impossible to match
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')
146 intval($contact['id']),
147 intval($contact['id']),
158 $date_field = "`changed`";
159 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
161 if(! strlen($last_update))
162 $last_update = 'now -30 days';
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');
172 $sql_extra .= " AND `contact`.`self` = 1 ";
175 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
177 // AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
178 // dbesc($check_date),
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'
193 ORDER BY $sql_order LIMIT 0, 300",
199 // Will check further below if this actually returned results.
200 // We will provide an empty feed if that is the case.
204 $doc = new DOMDocument('1.0', 'utf-8');
205 $doc->formatOutput = true;
207 $alternatelink = $owner['url'];
210 $alternatelink .= "/category/".$category;
213 $author = "dfrn:owner";
217 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
219 // This hook can't work anymore
220 // call_hooks('atom_feed', $atom);
222 if(! count($items)) {
223 $atom = trim($doc->saveXML());
225 call_hooks('atom_feed_end', $atom);
230 foreach($items as $item) {
232 // prevent private email from leaking.
233 if($item['network'] === NETWORK_MAIL)
236 // public feeds get html, our own nodes use bbcode
240 // catch any email that's in a public conversation and make sure it doesn't leak
246 $entry = self::entry($doc, $type, $item, $owner, true);
247 $root->appendChild($entry);
251 $atom = trim($doc->saveXML());
253 call_hooks('atom_feed_end', $atom);
259 * @brief Create XML text for DFRN mails
261 * @param array $item message elements
262 * @param array $owner Owner record
264 * @return string DFRN mail
266 function mail($item, $owner) {
267 $doc = new DOMDocument('1.0', 'utf-8');
268 $doc->formatOutput = true;
270 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
272 $mail = $doc->createElement("dfrn:mail");
273 $sender = $doc->createElement("dfrn:sender");
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']);
279 $mail->appendChild($sender);
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']);
287 $root->appendChild($mail);
289 return(trim($doc->saveXML()));
293 * @brief Create XML text for DFRN friend suggestions
295 * @param array $item suggestion elements
296 * @param array $owner Owner record
298 * @return string DFRN suggestions
300 function fsuggest($item, $owner) {
301 $doc = new DOMDocument('1.0', 'utf-8');
302 $doc->formatOutput = true;
304 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
306 $suggest = $doc->createElement("dfrn:suggest");
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']);
314 $root->appendChild($suggest);
316 return(trim($doc->saveXML()));
320 * @brief Create XML text for DFRN relocations
322 * @param array $owner Owner record
323 * @param int $uid User ID
325 * @return string DFRN relocations
327 function relocate($owner, $uid) {
329 /* get site pubkey. this could be a new installation with no site keys*/
330 $pubkey = get_config('system','site_pubkey');
332 $res = new_keypair(1024);
333 set_config('system','site_prvkey', $res['prvkey']);
334 set_config('system','site_pubkey', $res['pubkey']);
337 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
338 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
340 $ext = Photo::supportedTypes();
343 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
347 $doc = new DOMDocument('1.0', 'utf-8');
348 $doc->formatOutput = true;
350 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
352 $relocate = $doc->createElement("dfrn:relocate");
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'));
365 $root->appendChild($relocate);
367 return(trim($doc->saveXML()));
371 * @brief Adds the header elements for the DFRN protocol
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?
379 * @return object XML root object
381 private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
383 if ($alternatelink == "")
384 $alternatelink = $owner['url'];
386 $root = $doc->createElementNS(NS_ATOM, 'feed');
387 $doc->appendChild($root);
389 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
390 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
391 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
392 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
393 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
394 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
395 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
396 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
397 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
399 xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
400 xml_add_element($doc, $root, "title", $owner["name"]);
402 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
403 xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
405 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
406 xml_add_element($doc, $root, "link", "", $attributes);
408 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
409 xml_add_element($doc, $root, "link", "", $attributes);
413 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
414 ostatus_hublinks($doc, $root);
416 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
417 xml_add_element($doc, $root, "link", "", $attributes);
419 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
420 xml_add_element($doc, $root, "link", "", $attributes);
422 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
423 xml_add_element($doc, $root, "link", "", $attributes);
426 if ($owner['page-flags'] == PAGE_COMMUNITY)
427 xml_add_element($doc, $root, "dfrn:community", 1);
429 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
431 xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
433 $author = self::add_author($doc, $owner, $authorelement, $public);
434 $root->appendChild($author);
440 * @brief Adds the author element in the header for the DFRN protocol
442 * @param object $doc XML document
443 * @param array $owner Owner record
444 * @param string $authorelement Element name for the author
446 * @return object XML author object
448 private function add_author($doc, $owner, $authorelement, $public) {
450 $author = $doc->createElement($authorelement);
452 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME);
453 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
454 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
456 $attributes = array("dfrn:updated" => $namdate);
457 xml_add_element($doc, $author, "name", $owner["name"], $attributes);
459 $attributes = array("dfrn:updated" => $namdate);
460 xml_add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
462 $attributes = array("dfrn:updated" => $namdate);
463 xml_add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
465 $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate,
466 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
467 xml_add_element($doc, $author, "link", "", $attributes);
469 $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate,
470 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
471 xml_add_element($doc, $author, "link", "", $attributes);
473 $birthday = feed_birthday($owner['user_uid'], $owner['timezone']);
476 xml_add_element($doc, $author, "dfrn:birthday", $birthday);
478 // The following fields will only be generated if this isn't for a public feed
482 // Only show contact details when we are allowed to
483 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`,
484 `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob`
486 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
487 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
488 intval($owner['user_uid']));
491 xml_add_element($doc, $author, "poco:displayName", $profile["name"]);
492 xml_add_element($doc, $author, "poco:updated", $namdate);
494 if (trim($profile["dob"]) != "0000-00-00")
495 xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
497 xml_add_element($doc, $author, "poco:note", $profile["about"]);
498 xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
500 $savetz = date_default_timezone_get();
501 date_default_timezone_set($profile["timezone"]);
502 xml_add_element($doc, $author, "poco:utcOffset", date("P"));
503 date_default_timezone_set($savetz);
505 if (trim($profile["homepage"]) != "") {
506 $urls = $doc->createElement("poco:urls");
507 xml_add_element($doc, $urls, "poco:type", "homepage");
508 xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
509 xml_add_element($doc, $urls, "poco:primary", "true");
510 $author->appendChild($urls);
513 if (trim($profile["pub_keywords"]) != "") {
514 $keywords = explode(",", $profile["pub_keywords"]);
516 foreach ($keywords AS $keyword)
517 xml_add_element($doc, $author, "poco:tags", trim($keyword));
521 /// @todo When we are having the XMPP address in the profile we should propagate it here
523 if (trim($xmpp) != "") {
524 $ims = $doc->createElement("poco:ims");
525 xml_add_element($doc, $ims, "poco:type", "xmpp");
526 xml_add_element($doc, $ims, "poco:value", $xmpp);
527 xml_add_element($doc, $ims, "poco:primary", "true");
528 $author->appendChild($ims);
531 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
532 $element = $doc->createElement("poco:address");
534 xml_add_element($doc, $element, "poco:formatted", formatted_location($profile));
536 if (trim($profile["locality"]) != "")
537 xml_add_element($doc, $element, "poco:locality", $profile["locality"]);
539 if (trim($profile["region"]) != "")
540 xml_add_element($doc, $element, "poco:region", $profile["region"]);
542 if (trim($profile["country-name"]) != "")
543 xml_add_element($doc, $element, "poco:country", $profile["country-name"]);
545 $author->appendChild($element);
553 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
555 * @param object $doc XML document
556 * @param string $element Element name for the author
557 * @param string $contact_url Link of the contact
558 * @param array $items Item elements
560 * @return object XML author object
562 private function add_entry_author($doc, $element, $contact_url, $item) {
564 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
566 $author = $doc->createElement($element);
567 xml_add_element($doc, $author, "name", $contact["name"]);
568 xml_add_element($doc, $author, "uri", $contact["url"]);
569 xml_add_element($doc, $author, "dfrn:handle", $contact["addr"]);
572 /// - Check real image type and image size
573 /// - Check which of these boths elements we should use
576 "type" => "image/jpeg",
578 "media:height" => 80,
579 "href" => $contact["photo"]);
580 xml_add_element($doc, $author, "link", "", $attributes);
584 "type" => "image/jpeg",
586 "media:height" => 80,
587 "href" => $contact["photo"]);
588 xml_add_element($doc, $author, "link", "", $attributes);
594 * @brief Adds the activity elements
596 * @param object $doc XML document
597 * @param string $element Element name for the activity
598 * @param string $activity activity value
600 * @return object XML activity object
602 private function create_activity($doc, $element, $activity) {
605 $entry = $doc->createElement($element);
607 $r = parse_xml_string($activity, false);
611 xml_add_element($doc, $entry, "activity:object-type", $r->type);
613 xml_add_element($doc, $entry, "id", $r->id);
615 xml_add_element($doc, $entry, "title", $r->title);
617 if(substr($r->link,0,1) === '<') {
618 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
619 $r->link = str_replace('&','&', $r->link);
621 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
623 $data = parse_xml_string($r->link, false);
624 foreach ($data->attributes() AS $parameter => $value)
625 $attributes[$parameter] = $value;
627 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
629 xml_add_element($doc, $entry, "link", "", $attributes);
632 xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
641 * @brief Adds the elements for attachments
643 * @param object $doc XML document
644 * @param object $root XML root
645 * @param array $item Item element
647 * @return object XML attachment object
649 private function get_attachment($doc, $root, $item) {
650 $arr = explode('[/attach],',$item['attach']);
652 foreach($arr as $r) {
654 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
656 $attributes = array("rel" => "enclosure",
657 "href" => $matches[1],
658 "type" => $matches[3]);
660 if(intval($matches[2]))
661 $attributes["length"] = intval($matches[2]);
663 if(trim($matches[4]) != "")
664 $attributes["title"] = trim($matches[4]);
666 xml_add_element($doc, $root, "link", "", $attributes);
673 * @brief Adds the "entry" elements for the DFRN protocol
675 * @param object $doc XML document
676 * @param string $type "text" or "html"
677 * @param array $item Item element
678 * @param array $owner Owner record
679 * @param bool $comment Trigger the sending of the "comment" element
680 * @param int $cid Contact ID of the recipient
682 * @return object XML entry object
684 private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
686 $mentioned = array();
691 if($item['deleted']) {
692 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
693 return xml_create_element($doc, "at:deleted-entry", "", $attributes);
696 $entry = $doc->createElement("entry");
698 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
699 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
701 $body = $item['body'];
703 if ($type == 'html') {
706 if ($item['title'] != "")
707 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
709 $htmlbody = bbcode($htmlbody, false, false, 7);
712 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
713 $entry->appendChild($author);
715 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
716 $entry->appendChild($dfrnowner);
718 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
719 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
720 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
721 $attributes = array("ref" => $parent_item, "type" => "text/html",
722 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
723 "dfrn:diaspora_guid" => $parent[0]['guid']);
724 xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
727 xml_add_element($doc, $entry, "id", $item["uri"]);
728 xml_add_element($doc, $entry, "title", $item["title"]);
730 xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
731 xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
733 // "dfrn:env" is used to read the content
734 xml_add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
736 // The "content" field is not read by the receiver. We could remove it when the type is "text"
737 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
738 xml_add_element($doc, $entry, "content", (($type === 'html') ? $htmlbody : $body), array("type" => $type));
740 // We save this value in "plink". Maybe we should read it from there as well?
741 xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
742 "href" => app::get_baseurl()."/display/".$item["guid"]));
744 // "comment-allow" is some old fashioned stuff for old Friendica versions.
745 // It is included in the rewritten code for completeness
747 xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
749 if($item['location'])
750 xml_add_element($doc, $entry, "dfrn:location", $item['location']);
753 xml_add_element($doc, $entry, "georss:point", $item['coord']);
755 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
756 xml_add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
759 xml_add_element($doc, $entry, "dfrn:extid", $item['extid']);
761 if($item['bookmark'])
762 xml_add_element($doc, $entry, "dfrn:bookmark", "true");
765 xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
767 xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
769 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
770 // It is needed for relayed comments to Diaspora.
771 if($item['signed_text']) {
772 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
773 xml_add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
776 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
778 if ($item['object-type'] != "")
779 xml_add_element($doc, $entry, "activity:object-type", $item['object-type']);
780 elseif ($item['id'] == $item['parent'])
781 xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
783 xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
785 $actobj = self::create_activity($doc, "activity:object", $item['object']);
787 $entry->appendChild($actobj);
789 $actarg = self::create_activity($doc, "activity:target", $item['target']);
791 $entry->appendChild($actarg);
793 $tags = item_getfeedtags($item);
797 if (($type != 'html') OR ($t[0] != "@"))
798 xml_add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
804 $mentioned[$t[1]] = $t[1];
806 foreach ($mentioned AS $mention) {
807 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
808 intval($owner["uid"]),
809 dbesc(normalise_link($mention)));
810 if ($r[0]["forum"] OR $r[0]["prv"])
811 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
812 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
813 "href" => $mention));
815 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
816 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
817 "href" => $mention));
820 self::get_attachment($doc, $entry, $item);
826 * @brief Delivers the atom content to the contacts
828 * @param array $owner Owner record
829 * @param array $contactr Contact record of the receiver
830 * @param string $atom Content that will be transmitted
831 * @param bool $dissolve (to be documented)
833 * @return int Deliver status. -1 means an error.
835 function deliver($owner,$contact,$atom, $dissolve = false) {
839 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
841 if($contact['duplex'] && $contact['dfrn-id'])
842 $idtosend = '0:' . $orig_id;
843 if($contact['duplex'] && $contact['issued-id'])
844 $idtosend = '1:' . $orig_id;
847 $rino = get_config('system','rino_encrypt');
848 $rino = intval($rino);
849 // use RINO1 if mcrypt isn't installed and RINO2 was selected
850 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
852 logger("Local rino version: ". $rino, LOGGER_DEBUG);
854 $ssl_val = intval(get_config('system','ssl_policy'));
858 case SSL_POLICY_FULL:
859 $ssl_policy = 'full';
861 case SSL_POLICY_SELFSIGN:
862 $ssl_policy = 'self';
864 case SSL_POLICY_NONE:
866 $ssl_policy = 'none';
870 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
872 logger('dfrn_deliver: ' . $url);
874 $xml = fetch_url($url);
876 $curl_stat = $a->get_curl_code();
878 return(-1); // timed out
880 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
885 if(strpos($xml,'<?xml') === false) {
886 logger('dfrn_deliver: no valid XML returned');
887 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
891 $res = parse_xml_string($xml);
893 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
894 return (($res->status) ? $res->status : 3);
897 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
898 $challenge = hex2bin((string) $res->challenge);
899 $perm = (($res->perm) ? $res->perm : null);
900 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
901 $rino_remote_version = intval($res->rino);
902 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
904 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
906 if($owner['page-flags'] == PAGE_PRVGROUP)
912 if((($perm == 'rw') && (! intval($contact['writable'])))
913 || (($perm == 'r') && (intval($contact['writable'])))) {
914 q("update contact set writable = %d where id = %d",
915 intval(($perm == 'rw') ? 1 : 0),
916 intval($contact['id'])
918 $contact['writable'] = (string) 1 - intval($contact['writable']);
922 if(($contact['duplex'] && strlen($contact['pubkey']))
923 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
924 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
925 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
926 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
928 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
929 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
932 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
934 if(strpos($final_dfrn_id,':') == 1)
935 $final_dfrn_id = substr($final_dfrn_id,2);
937 if($final_dfrn_id != $orig_id) {
938 logger('dfrn_deliver: wrong dfrn_id.');
939 // did not decode properly - cannot trust this site
943 $postvars['dfrn_id'] = $idtosend;
944 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
946 $postvars['dissolve'] = '1';
949 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
950 $postvars['data'] = $atom;
951 $postvars['perm'] = 'rw';
953 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
954 $postvars['perm'] = 'r';
957 $postvars['ssl_policy'] = $ssl_policy;
960 $postvars['page'] = $page;
963 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
964 logger('rino version: '. $rino_remote_version);
966 switch($rino_remote_version) {
968 // Deprecated rino version!
969 $key = substr(random_string(),0,16);
970 $data = aes_encrypt($postvars['data'],$key);
973 // RINO 2 based on php-encryption
975 $key = Crypto::createNewRandomKey();
976 } catch (CryptoTestFailed $ex) {
977 logger('Cannot safely create a key');
979 } catch (CannotPerformOperation $ex) {
980 logger('Cannot safely create a key');
984 $data = Crypto::encrypt($postvars['data'], $key);
985 } catch (CryptoTestFailed $ex) {
986 logger('Cannot safely perform encryption');
988 } catch (CannotPerformOperation $ex) {
989 logger('Cannot safely perform encryption');
994 logger("rino: invalid requested verision '$rino_remote_version'");
998 $postvars['rino'] = $rino_remote_version;
999 $postvars['data'] = bin2hex($data);
1001 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1004 if($dfrn_version >= 2.1) {
1005 if(($contact['duplex'] && strlen($contact['pubkey']))
1006 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1007 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1009 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1011 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1014 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1015 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1017 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1021 logger('md5 rawkey ' . md5($postvars['key']));
1023 $postvars['key'] = bin2hex($postvars['key']);
1027 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1029 $xml = post_url($contact['notify'],$postvars);
1031 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1033 $curl_stat = $a->get_curl_code();
1034 if((! $curl_stat) || (! strlen($xml)))
1035 return(-1); // timed out
1037 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1040 if(strpos($xml,'<?xml') === false) {
1041 logger('dfrn_deliver: phase 2: no valid XML returned');
1042 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1046 if($contact['term-date'] != '0000-00-00 00:00:00') {
1047 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1048 require_once('include/Contact.php');
1049 unmark_for_death($contact);
1052 $res = parse_xml_string($xml);
1054 return $res->status;