2 require_once('include/items.php');
3 require_once('include/Contact.php');
4 require_once('include/ostatus.php');
9 * @brief Generates the atom entries for delivery.php
11 * This function is used whenever content is transmitted via DFRN.
13 * @param array $items Item elements
14 * @param array $owner Owner record
16 * @return string DFRN entries
18 function entries($items,$owner) {
20 $doc = new DOMDocument('1.0', 'utf-8');
21 $doc->formatOutput = true;
23 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
26 return trim($doc->saveXML());
28 foreach($items as $item) {
29 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
30 $root->appendChild($entry);
33 return(trim($doc->saveXML()));
37 * @brief Generate an atom feed for the given user
39 * This function is called when another server is pulling data from the user feed.
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.
46 * @return string DFRN feed entries
48 function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) {
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
57 if($public_feed && $a->argc > 2) {
58 for($x = 2; $x < $a->argc; $x++) {
59 if($a->argv[$x] == 'converse')
61 if($a->argv[$x] == 'starred')
63 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
64 $category = $a->argv[$x+1];
70 // default permissions - anonymous user
72 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
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",
84 $owner_id = $owner['user_uid'];
85 $owner_nick = $owner['nickname'];
95 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
99 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
100 $my_id = '1:' . $dfrn_id;
103 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
104 $my_id = '0:' . $dfrn_id;
111 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
119 require_once('include/security.php');
120 $groups = init_groups_visitor($contact['id']);
123 for($x = 0; $x < count($groups); $x ++)
124 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
125 $gs = implode('|', $groups);
127 $gs = '<<>>' ; // Impossible to match
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')
135 intval($contact['id']),
136 intval($contact['id']),
147 $date_field = "`changed`";
148 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
150 if(! strlen($last_update))
151 $last_update = 'now -30 days';
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');
161 $sql_extra .= " AND `contact`.`self` = 1 ";
164 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
166 // AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
167 // dbesc($check_date),
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'
182 ORDER BY $sql_order LIMIT 0, 300",
188 // Will check further below if this actually returned results.
189 // We will provide an empty feed if that is the case.
193 $doc = new DOMDocument('1.0', 'utf-8');
194 $doc->formatOutput = true;
196 $alternatelink = $owner['url'];
199 $alternatelink .= "/category/".$category;
202 $author = "dfrn:owner";
206 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
208 // This hook can't work anymore
209 // call_hooks('atom_feed', $atom);
211 if(! count($items)) {
212 $atom = trim($doc->saveXML());
214 call_hooks('atom_feed_end', $atom);
219 foreach($items as $item) {
221 // prevent private email from leaking.
222 if($item['network'] === NETWORK_MAIL)
225 // public feeds get html, our own nodes use bbcode
229 // catch any email that's in a public conversation and make sure it doesn't leak
235 $entry = self::entry($doc, $type, $item, $owner, true);
236 $root->appendChild($entry);
240 $atom = trim($doc->saveXML());
242 call_hooks('atom_feed_end', $atom);
248 * @brief Create XML text for DFRN mails
250 * @param array $item message elements
251 * @param array $owner Owner record
253 * @return string DFRN mail
255 function mail($item, $owner) {
256 $doc = new DOMDocument('1.0', 'utf-8');
257 $doc->formatOutput = true;
259 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
261 $mail = $doc->createElement("dfrn:mail");
262 $sender = $doc->createElement("dfrn:sender");
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']);
268 $mail->appendChild($sender);
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']);
276 $root->appendChild($mail);
278 return(trim($doc->saveXML()));
282 * @brief Create XML text for DFRN friend suggestions
284 * @param array $item suggestion elements
285 * @param array $owner Owner record
287 * @return string DFRN suggestions
289 function fsuggest($item, $owner) {
290 $doc = new DOMDocument('1.0', 'utf-8');
291 $doc->formatOutput = true;
293 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
295 $suggest = $doc->createElement("dfrn:suggest");
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']);
303 $root->appendChild($suggest);
305 return(trim($doc->saveXML()));
309 * @brief Create XML text for DFRN relocations
311 * @param array $owner Owner record
312 * @param int $uid User ID
314 * @return string DFRN relocations
316 function relocate($owner, $uid) {
318 /* get site pubkey. this could be a new installation with no site keys*/
319 $pubkey = get_config('system','site_pubkey');
321 $res = new_keypair(1024);
322 set_config('system','site_prvkey', $res['prvkey']);
323 set_config('system','site_pubkey', $res['pubkey']);
326 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
327 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
329 $ext = Photo::supportedTypes();
332 $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
336 $doc = new DOMDocument('1.0', 'utf-8');
337 $doc->formatOutput = true;
339 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
341 $relocate = $doc->createElement("dfrn:relocate");
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'));
354 $root->appendChild($relocate);
356 return(trim($doc->saveXML()));
360 * @brief Adds the header elements for the DFRN protocol
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?
368 * @return object XML root object
370 private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
372 if ($alternatelink == "")
373 $alternatelink = $owner['url'];
375 $root = $doc->createElementNS(NS_ATOM, 'feed');
376 $doc->appendChild($root);
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);
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"]);
392 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
393 xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
395 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
396 xml_add_element($doc, $root, "link", "", $attributes);
398 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
399 xml_add_element($doc, $root, "link", "", $attributes);
401 ostatus_hublinks($doc, $root);
404 $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
405 xml_add_element($doc, $root, "link", "", $attributes);
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);
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);
414 if ($owner['page-flags'] == PAGE_COMMUNITY)
415 xml_add_element($doc, $root, "dfrn:community", 1);
417 xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
419 $author = self::add_author($doc, $owner, $authorelement, $public);
420 $root->appendChild($author);
426 * @brief Adds the author element in the header for the DFRN protocol
428 * @param object $doc XML document
429 * @param array $owner Owner record
430 * @param string $authorelement Element name for the author
432 * @return object XML author object
434 private function add_author($doc, $owner, $authorelement, $public) {
436 $author = $doc->createElement($authorelement);
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);
442 $attributes = array("dfrn:updated" => $namdate);
443 xml_add_element($doc, $author, "name", $owner["name"], $attributes);
445 $attributes = array("dfrn:updated" => $namdate);
446 xml_add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
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);
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);
456 $birthday = feed_birthday($owner['user_uid'], $owner['timezone']);
459 xml_add_element($doc, $author, "dfrn:birthday", $birthday);
461 // The following fields will only be generated if this isn't for a public feed
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`
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']));
474 xml_add_element($doc, $author, "poco:displayName", $profile["name"]);
475 xml_add_element($doc, $author, "poco:updated", $namdate);
477 if (trim($profile["dob"]) != "0000-00-00")
478 xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
480 xml_add_element($doc, $author, "poco:note", $profile["about"]);
481 xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
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);
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);
496 if (trim($profile["pub_keywords"]) != "") {
497 $keywords = explode(",", $profile["pub_keywords"]);
499 foreach ($keywords AS $keyword)
500 xml_add_element($doc, $author, "poco:tags", trim($keyword));
504 /// @todo When we are having the XMPP address in the profile we should propagate it here
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);
514 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
515 $element = $doc->createElement("poco:address");
517 xml_add_element($doc, $element, "poco:formatted", formatted_location($profile));
519 if (trim($profile["locality"]) != "")
520 xml_add_element($doc, $element, "poco:locality", $profile["locality"]);
522 if (trim($profile["region"]) != "")
523 xml_add_element($doc, $element, "poco:region", $profile["region"]);
525 if (trim($profile["country-name"]) != "")
526 xml_add_element($doc, $element, "poco:country", $profile["country-name"]);
528 $author->appendChild($element);
536 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
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
543 * @return object XML author object
545 private function add_entry_author($doc, $element, $contact_url, $item) {
547 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
549 $author = $doc->createElement($element);
550 xml_add_element($doc, $author, "name", $contact["name"]);
551 xml_add_element($doc, $author, "uri", $contact["url"]);
554 /// - Check real image type and image size
555 /// - Check which of these boths elements we should use
558 "type" => "image/jpeg",
560 "media:height" => 80,
561 "href" => $contact["photo"]);
562 xml_add_element($doc, $author, "link", "", $attributes);
566 "type" => "image/jpeg",
568 "media:height" => 80,
569 "href" => $contact["photo"]);
570 xml_add_element($doc, $author, "link", "", $attributes);
576 * @brief Adds the activity elements
578 * @param object $doc XML document
579 * @param string $element Element name for the activity
580 * @param string $activity activity value
582 * @return object XML activity object
584 private function create_activity($doc, $element, $activity) {
587 $entry = $doc->createElement($element);
589 $r = parse_xml_string($activity, false);
593 xml_add_element($doc, $entry, "activity:object-type", $r->type);
595 xml_add_element($doc, $entry, "id", $r->id);
597 xml_add_element($doc, $entry, "title", $r->title);
599 if(substr($r->link,0,1) === '<') {
600 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
601 $r->link = str_replace('&','&', $r->link);
603 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
605 $data = parse_xml_string($r->link, false);
606 foreach ($data->attributes() AS $parameter => $value)
607 $attributes[$parameter] = $value;
609 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
611 xml_add_element($doc, $entry, "link", "", $attributes);
614 xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
623 * @brief Adds the elements for attachments
625 * @param object $doc XML document
626 * @param object $root XML root
627 * @param array $item Item element
629 * @return object XML attachment object
631 private function get_attachment($doc, $root, $item) {
632 $arr = explode('[/attach],',$item['attach']);
634 foreach($arr as $r) {
636 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
638 $attributes = array("rel" => "enclosure",
639 "href" => $matches[1],
640 "type" => $matches[3]);
642 if(intval($matches[2]))
643 $attributes["length"] = intval($matches[2]);
645 if(trim($matches[4]) != "")
646 $attributes["title"] = trim($matches[4]);
648 xml_add_element($doc, $root, "link", "", $attributes);
655 * @brief Adds the "entry" elements for the DFRN protocol
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
664 * @return object XML entry object
666 private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
668 $mentioned = array();
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);
678 $entry = $doc->createElement("entry");
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);
683 $body = $item['body'];
685 if ($type == 'html') {
688 if ($item['title'] != "")
689 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
691 $htmlbody = bbcode($htmlbody, false, false, 7);
694 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
695 $entry->appendChild($author);
697 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
698 $entry->appendChild($dfrnowner);
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);
707 xml_add_element($doc, $entry, "id", $item["uri"]);
708 xml_add_element($doc, $entry, "title", $item["title"]);
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));
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));
716 xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
717 "href" => app::get_baseurl()."/display/".$item["guid"]));
719 // "comment-allow" is some old fashioned stuff for old Friendica versions.
720 // It is included in the rewritten code for completeness
722 xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
724 if($item['location'])
725 xml_add_element($doc, $entry, "dfrn:location", $item['location']);
728 xml_add_element($doc, $entry, "georss:point", $item['coord']);
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));
734 xml_add_element($doc, $entry, "dfrn:extid", $item['extid']);
736 if($item['bookmark'])
737 xml_add_element($doc, $entry, "dfrn:bookmark", "true");
740 xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
742 xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
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);
751 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
753 $actobj = self::create_activity($doc, "activity:object", $item['object']);
755 $entry->appendChild($actobj);
757 $actarg = self::create_activity($doc, "activity:target", $item['target']);
759 $entry->appendChild($actarg);
761 $tags = item_getfeedtags($item);
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]));
772 $mentioned[$t[1]] = $t[1];
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));
783 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
784 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
785 "href" => $mention));
788 self::get_attachment($doc, $entry, $item);
794 * @brief Delivers the atom content to the contacts
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)
801 * @return int Deliver status. -1 means an error.
803 function deliver($owner,$contact,$atom, $dissolve = false) {
807 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
809 if($contact['duplex'] && $contact['dfrn-id'])
810 $idtosend = '0:' . $orig_id;
811 if($contact['duplex'] && $contact['issued-id'])
812 $idtosend = '1:' . $orig_id;
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;
820 logger("Local rino version: ". $rino, LOGGER_DEBUG);
822 $ssl_val = intval(get_config('system','ssl_policy'));
826 case SSL_POLICY_FULL:
827 $ssl_policy = 'full';
829 case SSL_POLICY_SELFSIGN:
830 $ssl_policy = 'self';
832 case SSL_POLICY_NONE:
834 $ssl_policy = 'none';
838 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
840 logger('dfrn_deliver: ' . $url);
842 $xml = fetch_url($url);
844 $curl_stat = $a->get_curl_code();
846 return(-1); // timed out
848 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
853 if(strpos($xml,'<?xml') === false) {
854 logger('dfrn_deliver: no valid XML returned');
855 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
859 $res = parse_xml_string($xml);
861 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
862 return (($res->status) ? $res->status : 3);
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);
872 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
874 if($owner['page-flags'] == PAGE_PRVGROUP)
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'])
886 $contact['writable'] = (string) 1 - intval($contact['writable']);
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']);
896 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
897 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
900 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
902 if(strpos($final_dfrn_id,':') == 1)
903 $final_dfrn_id = substr($final_dfrn_id,2);
905 if($final_dfrn_id != $orig_id) {
906 logger('dfrn_deliver: wrong dfrn_id.');
907 // did not decode properly - cannot trust this site
911 $postvars['dfrn_id'] = $idtosend;
912 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
914 $postvars['dissolve'] = '1';
917 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
918 $postvars['data'] = $atom;
919 $postvars['perm'] = 'rw';
921 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
922 $postvars['perm'] = 'r';
925 $postvars['ssl_policy'] = $ssl_policy;
928 $postvars['page'] = $page;
931 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
932 logger('rino version: '. $rino_remote_version);
934 switch($rino_remote_version) {
936 // Deprecated rino version!
937 $key = substr(random_string(),0,16);
938 $data = aes_encrypt($postvars['data'],$key);
941 // RINO 2 based on php-encryption
943 $key = Crypto::createNewRandomKey();
944 } catch (CryptoTestFailed $ex) {
945 logger('Cannot safely create a key');
947 } catch (CannotPerformOperation $ex) {
948 logger('Cannot safely create a key');
952 $data = Crypto::encrypt($postvars['data'], $key);
953 } catch (CryptoTestFailed $ex) {
954 logger('Cannot safely perform encryption');
956 } catch (CannotPerformOperation $ex) {
957 logger('Cannot safely perform encryption');
962 logger("rino: invalid requested verision '$rino_remote_version'");
966 $postvars['rino'] = $rino_remote_version;
967 $postvars['data'] = bin2hex($data);
969 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
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'])))
977 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
979 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
982 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
983 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
985 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
989 logger('md5 rawkey ' . md5($postvars['key']));
991 $postvars['key'] = bin2hex($postvars['key']);
995 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
997 $xml = post_url($contact['notify'],$postvars);
999 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1001 $curl_stat = $a->get_curl_code();
1002 if((! $curl_stat) || (! strlen($xml)))
1003 return(-1); // timed out
1005 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
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);
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);
1020 $res = parse_xml_string($xml);
1022 return $res->status;